Advertisement
Guest User

Untitled

a guest
Nov 16th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.53 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package robot;
  7.  
  8. import java.io.BufferedInputStream;
  9. import java.io.IOException;
  10. import java.io.PrintWriter;
  11. import java.net.ServerSocket;
  12. import java.net.Socket;
  13. import java.util.concurrent.Executors;
  14. import java.util.concurrent.ScheduledExecutorService;
  15. import java.util.logging.Level;
  16. import java.util.logging.Logger;
  17.  
  18. /** Class Robot
  19.  * Contains main method and creates new thread for each robot
  20.  *
  21.  * @author beata
  22.  */
  23. public class Robot {
  24.     private static final Logger logger = Logger.getLogger(ClientHandler.class.getName());
  25.     // thread pool
  26.     private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
  27.    
  28.     /**
  29.      *
  30.      * @param args
  31.      */
  32.     public static void main(String[] args) {
  33.         try {
  34.             ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));
  35.             while (true) {
  36.                 // waiting for client to be connected
  37.                 Socket socket = serverSocket.accept(); // waiting for client to be connected
  38.                 executor.execute(new ClientHandler(socket)); // new thread
  39.             }
  40.         } catch (IOException ex) {
  41.             logger.log(Level.SEVERE, null, ex);
  42.         }
  43.     }
  44. }
  45.  
  46.  
  47. /** Class ClientHandler
  48.  * Handles connection and communication with robot
  49.  *
  50.  * @author beata
  51.  */
  52. class ClientHandler implements Runnable {
  53.     private static final Logger logger = Logger.getLogger(ClientHandler.class.getName());
  54.    
  55.     private boolean closed = false;
  56.    
  57.     private final Socket socket;
  58.     private final PrintWriter output;
  59.     private final BufferedInputStream input;
  60.  
  61.     public ClientHandler(Socket socket) throws IOException {
  62.         this.socket = socket;
  63.         this.output = new PrintWriter(socket.getOutputStream(), true);
  64.         this.input = new BufferedInputStream(socket.getInputStream());
  65.     }
  66.    
  67.     /** Reading until new line
  68.      * Returns string of line
  69.      *
  70.      * @return returns string (line)
  71.      */
  72.     public String readUntilNewLine() {
  73.         int character;
  74.         String word = "";
  75.         try {
  76.             while ((character = input.read()) != -1) {
  77.                 if (character != '\n') {
  78.                     word += Character.toString((char)character);
  79.                 } else {
  80.                     if (word.charAt(word.length() - 1) == '\r') {
  81.                         return word.substring(0, word.length() - 1);
  82.                     } else {
  83.                         word += Character.toString((char)character);
  84.                     }
  85.                 }
  86.             }
  87.         } catch (IOException ex) {
  88.             logger.log(Level.SEVERE, null, ex);
  89.         }
  90.         return word;
  91.     }
  92.    
  93.     /** Login validation
  94.      * Gets username and password and returns true if correct
  95.      *
  96.      * @param username
  97.      * @param password
  98.      * @return returns true if correct, false if not
  99.      */
  100.     public boolean validateLogin(String username, String password) {
  101.         String checkUsername = "";
  102.         for (int i = 0; i < 5; i++) {
  103.             checkUsername += username.charAt(i);
  104.         }
  105.         if (!checkUsername.equals("Robot")) {
  106.             return false;
  107.         }
  108.        
  109.         int intUsername = 0;
  110.         for (int i = 0; i < username.length(); i++) {
  111.             intUsername += (int)username.charAt(i);
  112.         }
  113.        
  114.         try{
  115.             int intPassword = Integer.parseInt(password);
  116.             if (intUsername == intPassword) {
  117.                 return true;
  118.             }
  119.         } catch (NumberFormatException ex) {
  120.             logger.log(Level.SEVERE, null, ex);
  121.         }
  122.        
  123.         return false;
  124.     }
  125.    
  126.     /** Photo validation
  127.  Returns OK if valid, saves photo to photoXXX.png, if dataCounter of Bytes is less than 1, returns SYNTAX_ERROR,
  128.  if check sum is not equal, returns BAD_CHECKSUM
  129.      *
  130.      * @return String OK if valid,
  131.      */
  132.     public String validatePhoto() {
  133.         // FOTO 8 ABCDEFGH\x00\x00\x02\x24
  134.         String result = "";
  135.         int character;
  136.         int checkSumFirst = 0;
  137.         int checkSumSecond = 0;
  138.         int numberOfBytes = 0;
  139.         String numberOfBytesString = "";
  140.         try {
  141.             // dataCounter of Bytes
  142.             while ((char)(character = input.read()) != ' ') {
  143.                 numberOfBytesString += (char)character;
  144.             }
  145.             numberOfBytes = Integer.parseInt(numberOfBytesString);
  146.            
  147.             if (numberOfBytes < 1) {
  148.                 result = "SYNTAX_ERROR";
  149.             }
  150.            
  151.             // data, check sum
  152.             for (int i = 0; i < numberOfBytes; i++) {
  153.                 character = input.read();
  154.                 checkSumFirst += character;
  155.             }
  156.  
  157.             // last 4 control bytes, check sum          
  158.             for (int i = 0; i < 4; i++) {
  159.                 character = input.read();
  160.                 System.out.println("Character: " + character);
  161.                 checkSumSecond += character * Math.pow(16, 2 * (3 - i));
  162.             }
  163.            
  164.             // printing
  165.             System.out.println("---------------------");
  166.             System.out.println("Number of bytes: " + numberOfBytes);
  167.             System.out.println("First check sum: " + checkSumFirst);
  168.             System.out.println("Second check sum: " + checkSumSecond);
  169.         } catch (IOException ex) {
  170.             logger.log(Level.SEVERE, null, ex);
  171.         }
  172.         return result;
  173.     }
  174.    
  175.     /** Comparing two strings
  176.      * If they are equal, returns true, else false
  177.      *
  178.      * @param first First string
  179.      * @param second Second string
  180.      * @return returns true if equal, else false
  181.      */
  182.     public boolean compareStrings(String first, String second) {
  183.         if (first.length() < second.length()) {
  184.             for (int i = 0; i < first.length(); i++) {
  185.                 if (first.charAt(i) != second.charAt(i)) {
  186.                     return false;
  187.                 }
  188.             }
  189.         } else {
  190.             for (int i = 0; i < second.length(); i++) {
  191.                 if (first.charAt(i) != second.charAt(i)) {
  192.                     return false;
  193.                 }
  194.             }
  195.         }
  196.         return true;
  197.     }
  198.    
  199.     /** Closing connection
  200.      * Closes the connection
  201.      */
  202.     public void closeConnection() {
  203.         if (closed == false) {
  204.             try {
  205.                 socket.close();
  206.             } catch (IOException ex) {
  207.                 logger.log(Level.SEVERE, null, ex);
  208.             }
  209.         }
  210.     }
  211.    
  212.     @Override
  213.     public void run() {
  214.        
  215.         try {
  216.             // Login
  217.             output.printf(Messages.LOGIN);
  218.             String username = readUntilNewLine();
  219.             output.printf(Messages.PASSWORD);
  220.             String password = readUntilNewLine();
  221.            
  222.            
  223.             // Login validation
  224.             if (validateLogin(username, password) == true) {
  225.                 output.printf(Messages.OK);
  226.             } else {
  227.                 output.printf(Messages.LOGIN_FAILED);
  228.                 closeConnection();
  229.                 closed = true;
  230.             }
  231.            
  232.            
  233.             // Messages
  234.             int character;
  235.             int counter = 0;
  236.             String word = "";
  237.             while (true) {
  238.                 while ((character = input.read()) != -1 && counter != 5) {
  239.                     word += Character.toString((char)character);
  240.                     // Info message
  241.                     if (word.startsWith("I")) {
  242.                         if (compareStrings(word, "INFO ") == false) {
  243.                             output.printf(Messages.SYNTAX_ERROR);
  244.                             closeConnection();
  245.                             closed = true;
  246.                         }
  247.                     // Foto message
  248.                     } else if (word.startsWith("F")) {
  249.                         if (compareStrings(word, "FOTO ") == false) {
  250.                             output.printf(Messages.SYNTAX_ERROR);
  251.                             closeConnection();
  252.                             closed = true;
  253.                         }
  254.                     } else {
  255.                         output.printf(Messages.SYNTAX_ERROR);
  256.                         closeConnection();
  257.                         closed = true;
  258.                     }
  259.                     if (counter == 4) {
  260.                         break;
  261.                     }
  262.                     counter++;
  263.                 }
  264.                 if (word.equals("INFO ")) {
  265.                     word = readUntilNewLine();
  266.                     output.printf(Messages.OK);
  267.                 } else if (word.equals("FOTO ")) {
  268.                     String result = validatePhoto();
  269.                 }
  270.             }
  271.         } catch (IOException ex) {
  272.             logger.log(Level.SEVERE, null, ex);
  273.         }
  274.        
  275.     }
  276. }
  277.  
  278. /** Class Messages
  279.  * Holds messages to be sent to robot
  280.  *
  281.  * @author beata
  282.  */
  283. class Messages {
  284.     public static final String LOGIN = "200 LOGIN\r\n";
  285.     public static final String PASSWORD = "201 PASSWORD\r\n";
  286.     public static final String OK = "202 OK\r\n";
  287.     public static final String BAD_CHECKSUM = "300 BAD CHECKSUM\r\n";
  288.     public static final String LOGIN_FAILED = "500 LOGIN FAILED\r\n";
  289.     public static final String SYNTAX_ERROR = "501 SYNTAX ERROR\r\n";
  290.     public static final String TIMEOUT = "502 TIMEOUT\r\n";
  291. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement