itzceekay

Ceekayserver

Apr 5th, 2013
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.80 KB | None | 0 0
  1. import java.net.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.io.*;
  5.  
  6.  
  7. class CeekayServerShutdown
  8.     extends Thread
  9. {
  10.    
  11.  
  12.     private CeekayServer server;
  13.    
  14.     public CeekayServerShutdown(CeekayServer s)
  15.     {
  16.     server = s;
  17.     }
  18.  
  19.     public void run()
  20.     {
  21.     if (server.stop)
  22.         return;
  23.  
  24.     server.externalShutdown = true;
  25.     server.shutdown();
  26.     }
  27. }
  28.  
  29. public class CeekayServer
  30.     extends Thread
  31. {
  32.     protected static String userPasswordFileName =
  33.  
  34. "User.passwords";
  35.     protected static String serverLogName = "Server.log";
  36.     protected static String messageFileName = "Messages.saved";
  37.     protected static String welcomeMessageName = "WELCOME.TXT";
  38.  
  39.     protected static String portnumberParam = "-portnumber";
  40.     protected static String usepasswordsParam = "-usepasswords";
  41.     protected static String newusersParam = "-newusers";
  42.     protected static String nographicsParam = "-nographics";
  43.     protected static String chatlogsParam = "-chatlogs";
  44.        
  45.     protected static int DEFAULTPORT = 12468;
  46.  
  47.     protected URL myURL;
  48.     protected int port;
  49.     protected CeekayServerWindow myWindow;
  50.     protected boolean graphics;
  51.     protected boolean requirePasswords;
  52.     protected boolean passwordEncryption;
  53.     protected boolean allowNewUsers;
  54.     protected boolean logChats;
  55.     private Integer userIdCounter = new Integer(1);
  56.  
  57.     protected ServerSocket myServerSocket;
  58.     protected Socket mySocket;
  59.     protected ThreadGroup myThreadGroup;
  60.  
  61.     public Vector connections;
  62.     public Vector messages;
  63.     public OrbitChatRoom mainRoom;
  64.     public Vector chatRooms;
  65.  
  66.     private FileOutputStream log;
  67.     protected OrbitPasswordEncryptor passwordEncryptor;
  68.  
  69.     protected OrbitClientSocket administratorClient;
  70.  
  71.     protected int currentConnections = 0;
  72.     protected int peakConnections = 0;
  73.     protected int totalConnections = 0;
  74.    
  75.     protected boolean stop = false;
  76.     protected boolean externalShutdown = false;
  77.  
  78.     protected SimpleDateFormat dateFormatter =
  79.     new SimpleDateFormat("MMM dd, yyyy hh:mm a");
  80.  
  81.     public CeekayServer(int askport, boolean passwords, boolean
  82.  
  83. newusers,
  84.              boolean isgraphics, boolean islog)
  85.     {
  86.     super("Intranet Chatting server");
  87.  
  88.     port = askport;
  89.     requirePasswords = passwords;
  90.     allowNewUsers = newusers;
  91.     graphics = isgraphics;
  92.     logChats = islog;
  93.     try {
  94.         File logFile = new File(serverLogName);
  95.         log = new FileOutputStream(logFile);
  96.     }
  97.     catch (IOException e) {
  98.         serverOutput("Unable to open " + serverLogName + "
  99.  
  100. file\n");
  101.     }
  102.  
  103.     if (graphics)
  104.         {
  105.         myWindow =
  106.             new CeekayServerWindow(this, "Intranet Chatting
  107.  
  108. v"
  109.                         + Ceekay.VERSION + "
  110.  
  111. Server");
  112.         myWindow.setSize(400, 400);
  113.         myWindow.setVisible(true);
  114.         }
  115.  
  116.     else
  117.         {
  118.         System.out.println("\nIntranet chatting server
  119.  
  120. status");
  121.         System.out.println("Listening on port " + port);
  122.         System.out.println("Connections:");
  123.         }
  124.  
  125.     try {
  126.         myServerSocket = new ServerSocket(port);
  127.     }
  128.     catch (IOException e) {
  129.         serverOutput("Couldn't create server socket\n");
  130.         System.exit(1);
  131.     }
  132.  
  133.     connections = new Vector();
  134.     messages = new Vector();
  135.     chatRooms = new Vector();
  136.     myThreadGroup = new ThreadGroup("Clients");
  137.     passwordEncryptor = new OrbitPasswordEncryptor();
  138.  
  139.     if (requirePasswords)
  140.         try {
  141.         new FileOutputStream(userPasswordFileName,
  142.  
  143. true).close();
  144.         }
  145.         catch (IOException f) {}
  146.     mainRoom = new OrbitChatRoom("Main", "Administrator",
  147.  
  148. false, null);
  149.     try {
  150.         mainRoom.setLogging(logChats);
  151.     }  
  152.     catch (IOException e) {
  153.         serverOutput("Unable to start chat log for room " +
  154.              mainRoom.name + "\n");
  155.     }
  156.  
  157.     serverOutput("Reading message file\n");
  158.     readMessages();
  159.  
  160.     serverOutput("Waiting for connections\n");
  161.  
  162.     float javaVersion = Float
  163.         .parseFloat(System.getProperty
  164.  
  165. ("java.version").substring(0, 3));
  166.     if (javaVersion >= 1.3)
  167.         Runtime.getRuntime()
  168.         .addShutdownHook(new CeekayServerShutdown(this));
  169.  
  170.     start();
  171.     }
  172.  
  173.     public boolean checkPassword(String fileName, String userName,
  174.                  String password)
  175.     throws Exception
  176.     {
  177.  
  178.  
  179. match
  180.    
  181.     DataInputStream passwordStream = null;
  182.  
  183. try {
  184.        
  185.         passwordStream =
  186.         new DataInputStream(new FileInputStream(fileName));
  187.  
  188.         while(true)
  189.         {
  190.             String tempUserName = "";
  191.             String tempPassword = "";
  192.             try {
  193.             tempUserName = passwordStream.readUTF();
  194.             tempPassword = passwordStream.readUTF();
  195.             }
  196.             catch (EOFException e) {
  197.        
  198.             throw new Exception("User does not exist");
  199.             }
  200.  
  201.    
  202.             if (tempUserName.equals(userName))
  203.             {
  204.                 if (tempPassword.equals(password))
  205.                 return (true);
  206.                 else
  207.            
  208.                 return (false);
  209.             }
  210.         }
  211.     }
  212.     catch (IOException e) {
  213.         serverOutput("Error reading password file: " +
  214.  
  215. e.toString() +
  216.              "\n");
  217.         return (false);
  218.     }
  219.     }
  220.  
  221.     protected OrbitChatRoom findChatRoom(String roomName)
  222.     {
  223.  
  224.     OrbitChatRoom tempRoom = null;
  225.     OrbitChatRoom returnRoom = null;
  226.  
  227.     if (mainRoom.name.equals(roomName))
  228.         returnRoom = mainRoom;
  229.  
  230.     else
  231.         {
  232.         for (int count = 0; count < chatRooms.size(); count
  233.  
  234. ++)
  235.             {
  236.             tempRoom = (OrbitChatRoom)
  237.                 chatRooms.elementAt(count);
  238.  
  239.             if (tempRoom.name.equals(roomName))
  240.                 {
  241.                 returnRoom = tempRoom;
  242.                 break;
  243.                 }
  244.             }
  245.         }
  246.  
  247.     return (returnRoom);
  248.     }
  249.  
  250.     public boolean isUserAllowed(OrbitChatRoom room,
  251.                    OrbitClientSocket client, String
  252.  
  253. password)
  254.     {
  255.     if (room.priv)
  256.         {
  257.         boolean invited = false;
  258.            
  259.         if (!room.password.equals(password))
  260.             {
  261.            
  262.  
  263.             for (int count2 = 0;
  264.                  count2 < room.invitedUsers.size();
  265.  
  266. count2 ++)
  267.                 {
  268.                 Integer Id = (Integer)
  269.  
  270. room.invitedUsers
  271.                     .elementAt(count2);
  272.                
  273.                 if (Id.intValue() ==
  274.  
  275. client.user.id)
  276.                     {
  277.                     invited = true;
  278.                     break;
  279.                     }
  280.                 }
  281.        
  282.             if (!invited)
  283.                 {
  284.                 try {
  285.                     client.sendServerMessage(
  286.                      "Not invited to/incorrect
  287.  
  288. password " +
  289.                      "for the private room " +
  290.                      room.name);
  291.                 }
  292.                 catch (IOException e) {
  293.                     disconnect(client, false);
  294.                     return (false);
  295.                 }
  296.                 return (false);
  297.                 }
  298.             }
  299.         }
  300.  
  301.     for (int count1 = 0; count1 < room.bannedUserNames.size();
  302.  
  303. count1 ++)
  304.         {
  305.         if (room.bannedUserNames.elementAt(count1)
  306.             .equals(client.user.name))
  307.             {
  308.            
  309.             try {
  310.                 client.sendBanUser(client.user.id,
  311.  
  312. room.name);
  313.             }
  314.             catch (IOException e) {
  315.                 disconnect(client, false);
  316.                 return (false);
  317.             }
  318.             return (false);
  319.             }
  320.         }
  321.        
  322.  
  323.     return (true);
  324.     }
  325.  
  326.     public synchronized void disconnect(OrbitClientSocket who,
  327.                     boolean notify)
  328.     {
  329.     int count;
  330.     OrbitChatRoom chatRoom;
  331.  
  332.     if (notify)
  333.         {
  334.         try {
  335.             // Try to let the user know they're being
  336.  
  337. disconnected
  338.             who.sendDisconnect(who.user.id, "You are being
  339.  
  340. " +
  341.                        "disconnected.  Goodbye.");
  342.         }
  343.         catch (IOException e) {}
  344.         }
  345.  
  346.     who.shutdown();
  347.  
  348.     try {
  349.         who.leaveChatRoom();
  350.     }
  351.     catch (IOException e) {}
  352.  
  353.     synchronized (connections)
  354.         {
  355.         connections.removeElement(who);
  356.         connections.trimToSize();
  357.         currentConnections = connections.size();
  358.         }
  359.  
  360.     serverOutput("User " + who.user.name + " disconnected at "
  361.              + dateFormatter.format(new Date()) + "\n");
  362.  
  363.     serverOutput("There are " + currentConnections +
  364.              " users connected\n");
  365.    
  366.     // Tell all the other clients to ditch this user
  367.     for (count = 0; count < currentConnections; count ++)
  368.         {
  369.         OrbitClientSocket other = (OrbitClientSocket)
  370.             connections.elementAt(count);
  371.         try {
  372.             other.sendDisconnect(who.user.id, "");
  373.         }
  374.         catch (IOException e) {}
  375.         }
  376.  
  377.     try {
  378.         sleep(250);
  379.     }
  380.     catch (InterruptedException I) {}
  381.  
  382.     if (graphics)
  383.         {
  384.         synchronized (myWindow.userList) {
  385.    
  386.             for (count = 0; count <
  387.  
  388. myWindow.userList.getItemCount();
  389.              count ++)
  390.             {
  391.                 if (myWindow.userList.getItem(
  392.                       count).equals
  393.  
  394. (who.user.name))
  395.                 {
  396.                     myWindow.userList.remove
  397.  
  398. (who.user.name);
  399.                     break;
  400.                 }
  401.             }
  402.         }
  403.        
  404.         myWindow.updateStats();
  405.  
  406.         if (currentConnections <= 1)
  407.             myWindow.disconnectAll.setEnabled(false);
  408.         if (currentConnections <= 0)
  409.             myWindow.disconnect.setEnabled(false);
  410.         }
  411.     return;
  412.     }
  413.  
  414.  
  415.     public synchronized void disconnectAll(boolean notify)
  416.     {
  417.     int count;
  418.     for(count = (currentConnections - 1); count >= 0; count --)
  419.         {
  420.         OrbitClientSocket temp =
  421.             (OrbitClientSocket) connections.elementAt
  422.  
  423. (count);
  424.  
  425.         if (temp == null)
  426.             continue;
  427.  
  428.         disconnect(temp, notify);
  429.         }
  430.     return;
  431.     }
  432.  
  433.  
  434.     public void run()
  435.     {
  436.     while (!stop)
  437.         {
  438.         try {
  439.             mySocket = myServerSocket.accept();
  440.         }
  441.         catch (IOException e) {
  442.             serverOutput("Socket error\n");
  443.             try {
  444.             myServerSocket.close();
  445.             }
  446.             catch (IOException f) {
  447.             serverOutput("Couldn't close socket\n");
  448.             }
  449.             System.exit(1);
  450.         }
  451.  
  452.         if (mySocket == null)
  453.             {
  454.             serverOutput("Server tried to start up NULL
  455.  
  456. "
  457.                      + "socket\n");
  458.             try {
  459.                 myServerSocket.close();
  460.             }
  461.             catch (IOException g) {
  462.                 serverOutput("Couldn't close socket
  463.  
  464. \n");
  465.             }
  466.             System.exit(1);
  467.             }
  468.  
  469.         OrbitClientSocket cs =
  470.             new OrbitClientSocket(this, mySocket,
  471.  
  472. myThreadGroup);
  473.         }
  474.     }
  475.  
  476.     protected int getUserId()
  477.     {
  478.     // Returns a number to be used as a user Id
  479.    
  480.     int tmp;
  481.  
  482.     synchronized (userIdCounter)
  483.         {
  484.         tmp = userIdCounter.intValue();
  485.         userIdCounter = new Integer(tmp + 1);
  486.         }
  487.  
  488.     return (tmp);
  489.     }
  490.  
  491.     protected void createNewUser(String userName, String
  492.  
  493. encryptedPassword)
  494.     throws Exception
  495.     {
  496.  
  497.     new OrbitUserTool().createUser(userName,
  498.  
  499. encryptedPassword);
  500.     }
  501.  
  502.     protected void serverOutput(String message)
  503.     {
  504.     if (graphics)
  505.         myWindow.logWindow.append(message);
  506.     else
  507.         System.out.print(message);
  508.  
  509.  
  510.     if (log != null)
  511.         {
  512.         try {
  513.             byte[] messagebytes = message.getBytes();
  514.             log.write(messagebytes);
  515.         }
  516.         catch (IOException F) {
  517.             if (graphics)
  518.             myWindow.logWindow
  519.                 .append("Unable to write to log file
  520.  
  521. \n");
  522.             else
  523.             System.out.print("Unable to write to log
  524.  
  525. file\n");
  526.         }
  527.         }
  528.  
  529.     return;
  530.     }
  531.  
  532.     protected void readMessages()
  533.     {
  534.     String tempFor = "";
  535.     String tempFrom = "";
  536.     String tempMessage = "";
  537.    
  538.     DataInputStream messageStream = null;
  539.  
  540.     try {
  541.         messageStream =
  542.         new DataInputStream(new FileInputStream
  543.  
  544. (messageFileName));
  545.  
  546.         while(true)
  547.         {
  548.             try {
  549.             tempFor = messageStream.readUTF();
  550.             tempFrom = messageStream.readUTF();
  551.             tempMessage = messageStream.readUTF();
  552.             }
  553.             catch (EOFException e) {
  554.             break;
  555.             }
  556.            
  557.             messages.addElement(new OrbitMessage(tempFor,
  558.  
  559. tempFrom,
  560.                                
  561.  
  562. tempMessage));
  563.         }
  564.  
  565.         messageStream.close();
  566.     }
  567.     catch (IOException E) {}
  568.    
  569.     return;
  570.     }
  571.  
  572.     protected void saveMessages()
  573.     {
  574.     DataOutputStream messageStream = null;
  575.  
  576.     try {
  577.         messageStream =
  578.         new DataOutputStream(new FileOutputStream
  579.  
  580. (messageFileName));
  581.        
  582.         for (int count = 0; count < messages.size(); count ++)
  583.         {
  584.             OrbitMessage tempMessage =
  585.             (OrbitMessage) messages.elementAt(count);
  586.            
  587.             messageStream.writeUTF(tempMessage.messageFor);
  588.             messageStream.writeUTF
  589.  
  590. (tempMessage.messageFrom);
  591.             messageStream.writeUTF(tempMessage.text);
  592.         }
  593.        
  594.         messageStream.close();
  595.     }
  596.     catch (IOException E) {
  597.         serverOutput("Error writing the messages file\n");
  598.     }
  599.  
  600.     return;
  601.     }
  602.  
  603.     protected void shutdown()
  604.     {
  605.     serverOutput("Server shutting down...\n");
  606.  
  607.     if (currentConnections > 0)
  608.         {
  609.         serverOutput("Disconnecting users\n");
  610.  
  611.        
  612.         for (int count = 0; count < currentConnections;
  613.  
  614. count ++)
  615.             {
  616.             OrbitClientSocket who = (OrbitClientSocket)
  617.                 connections.elementAt(count);
  618.             try {
  619.                 who.sendDisconnect(who.user.id,
  620.                        "The server is shutting
  621.  
  622. down.  " +
  623.                        "Goodbye.");
  624.             }
  625.             catch (IOException e) {}
  626.             }
  627.         disconnectAll(true);
  628.         }
  629.     else
  630.         serverOutput("No users connected\n");
  631.     serverOutput("Peak connections this session: "
  632.              + peakConnections + "\n");
  633.     serverOutput("Total connections this session: "
  634.              + totalConnections + "\n");
  635.  
  636.     serverOutput("Saving user messages\n");
  637.     saveMessages();
  638.  
  639.     serverOutput("Closing log file\n");
  640.     try {
  641.         log.close();
  642.     }
  643.     catch (IOException F) {
  644.         serverOutput("Unable to close server log file\n");
  645.     }
  646.  
  647.     if (graphics)
  648.         myWindow.dispose();
  649.  
  650.     stop = true;
  651.  
  652.     if (!graphics)
  653.         {
  654.         System.out.println("");
  655.         System.out.println("Intranet Chatting server
  656.  
  657. shutdown complete");
  658.         }
  659.  
  660.  
  661.  
  662.     if (!externalShutdown)
  663.         System.exit(0);
  664.     }
  665.  
  666.     private static void usage()
  667.     {
  668.     System.out.println("\nIntranet Chatting server usage:");
  669.     System.out.println("java CeekayServer [" +
  670.                portnumberParam + " number] [" +
  671.                usepasswordsParam + "] [" +
  672.                newusersParam + "] [" +
  673.                nographicsParam + "] [" +
  674.                chatlogsParam + "]");
  675.     return;
  676.     }
  677.  
  678.     public static void main(String[] args)
  679.     {
  680.     int usePort = DEFAULTPORT;
  681.     boolean reqPass = false;
  682.     boolean allowNew = false;
  683.     boolean useGraphics = true;
  684.     boolean logChats = false;
  685.     CeekayServer server;
  686.  
  687.     for (int count = 0; count < args.length; count ++)
  688.         {
  689.         if (args[count].equals(portnumberParam))
  690.             {
  691.             if (++count < args.length)
  692.                 {
  693.                 try {
  694.                     usePort = Integer.parseInt
  695.  
  696. (args[count]);
  697.                 }
  698.                 catch (Exception E) {
  699.                     System.out.println("\nIntranet
  700.  
  701. Chatting Server: "
  702.                            + "illegal port
  703.  
  704. number "
  705.                            + args[count]);
  706.                     System.out.println("Type 'java
  707.  
  708. "
  709.                            + "CeekayServer -
  710.  
  711. help' "
  712.                            + "for usage
  713.  
  714. information");
  715.                     System.exit(1);
  716.                 }          
  717.                 }
  718.             }
  719.  
  720.         else if (args[count].equals(usepasswordsParam))
  721.             reqPass = true;
  722.  
  723.         else if (args[count].equals(newusersParam))
  724.             allowNew = true;
  725.  
  726.         else if (args[count].equals(nographicsParam))
  727.             useGraphics = false;
  728.  
  729.         else if (args[count].equals(chatlogsParam))
  730.             logChats = true;
  731.  
  732.         else if (args[count].equals("-help"))
  733.             {
  734.             usage();
  735.             System.exit(1);
  736.             }
  737.  
  738.         else
  739.             {
  740.             System.out.println("\nIntranet Chatting
  741.  
  742. Server: unknown "
  743.                        + "argument " + args
  744.  
  745. [count]);
  746.             System.out.println("Type 'java CeekayServer
  747.  
  748. -help' "
  749.                        + "for usage
  750.  
  751. information");
  752.             System.exit(1);
  753.             }
  754.         }
  755.  
  756.     server = new CeekayServer(usePort, reqPass, allowNew,
  757.  
  758. useGraphics,
  759.                    logChats);
  760.  
  761.     try {
  762.         server.myURL = new URL("file", "localhost", "./");
  763.     }
  764.     catch (Exception E) {
  765.         System.out.println(E);
  766.         System.exit(1);
  767.     }
  768.    
  769.     return;
  770.     }
  771. }
Advertisement
Add Comment
Please, Sign In to add comment