Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package robot;
- import java.io.BufferedInputStream;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /** Class Robot
- * Contains main method and creates new thread for each robot
- *
- * @author beata
- */
- public class Robot {
- private static final Logger logger = Logger.getLogger(ClientHandler.class.getName());
- // thread pool
- private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
- /**
- *
- * @param args
- */
- public static void main(String[] args) {
- try {
- ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));
- while (true) {
- // waiting for client to be connected
- Socket socket = serverSocket.accept(); // waiting for client to be connected
- executor.execute(new ClientHandler(socket)); // new thread
- }
- } catch (IOException ex) {
- logger.log(Level.SEVERE, null, ex);
- }
- }
- }
- /** Class ClientHandler
- * Handles connection and communication with robot
- *
- * @author beata
- */
- class ClientHandler implements Runnable {
- private static final Logger logger = Logger.getLogger(ClientHandler.class.getName());
- private boolean closed = false;
- private final Socket socket;
- private final PrintWriter output;
- private final BufferedInputStream input;
- public ClientHandler(Socket socket) throws IOException {
- this.socket = socket;
- this.output = new PrintWriter(socket.getOutputStream(), true);
- this.input = new BufferedInputStream(socket.getInputStream());
- }
- /** Reading until new line
- * Returns string of line
- *
- * @return returns string (line)
- */
- public String readUntilNewLine() {
- int character;
- String word = "";
- try {
- while ((character = input.read()) != -1) {
- if (character != '\n') {
- word += Character.toString((char)character);
- } else {
- if (word.charAt(word.length() - 1) == '\r') {
- return word.substring(0, word.length() - 1);
- } else {
- word += Character.toString((char)character);
- }
- }
- }
- } catch (IOException ex) {
- logger.log(Level.SEVERE, null, ex);
- }
- return word;
- }
- /** Login validation
- * Gets username and password and returns true if correct
- *
- * @param username
- * @param password
- * @return returns true if correct, false if not
- */
- public boolean validateLogin(String username, String password) {
- String checkUsername = "";
- for (int i = 0; i < 5; i++) {
- checkUsername += username.charAt(i);
- }
- if (!checkUsername.equals("Robot")) {
- return false;
- }
- int intUsername = 0;
- for (int i = 0; i < username.length(); i++) {
- intUsername += (int)username.charAt(i);
- }
- try{
- int intPassword = Integer.parseInt(password);
- if (intUsername == intPassword) {
- return true;
- }
- } catch (NumberFormatException ex) {
- logger.log(Level.SEVERE, null, ex);
- }
- return false;
- }
- /** Photo validation
- Returns OK if valid, saves photo to photoXXX.png, if dataCounter of Bytes is less than 1, returns SYNTAX_ERROR,
- if check sum is not equal, returns BAD_CHECKSUM
- *
- * @return String OK if valid,
- */
- public String validatePhoto() {
- // FOTO 8 ABCDEFGH\x00\x00\x02\x24
- String result = "";
- int character;
- int checkSumFirst = 0;
- int checkSumSecond = 0;
- int numberOfBytes = 0;
- String numberOfBytesString = "";
- try {
- // dataCounter of Bytes
- while ((char)(character = input.read()) != ' ') {
- numberOfBytesString += (char)character;
- }
- numberOfBytes = Integer.parseInt(numberOfBytesString);
- if (numberOfBytes < 1) {
- result = "SYNTAX_ERROR";
- }
- // data, check sum
- for (int i = 0; i < numberOfBytes; i++) {
- character = input.read();
- checkSumFirst += character;
- }
- // last 4 control bytes, check sum
- for (int i = 0; i < 4; i++) {
- character = input.read();
- System.out.println("Character: " + character);
- checkSumSecond += character * Math.pow(16, 2 * (3 - i));
- }
- // printing
- System.out.println("---------------------");
- System.out.println("Number of bytes: " + numberOfBytes);
- System.out.println("First check sum: " + checkSumFirst);
- System.out.println("Second check sum: " + checkSumSecond);
- } catch (IOException ex) {
- logger.log(Level.SEVERE, null, ex);
- }
- return result;
- }
- /** Comparing two strings
- * If they are equal, returns true, else false
- *
- * @param first First string
- * @param second Second string
- * @return returns true if equal, else false
- */
- public boolean compareStrings(String first, String second) {
- if (first.length() < second.length()) {
- for (int i = 0; i < first.length(); i++) {
- if (first.charAt(i) != second.charAt(i)) {
- return false;
- }
- }
- } else {
- for (int i = 0; i < second.length(); i++) {
- if (first.charAt(i) != second.charAt(i)) {
- return false;
- }
- }
- }
- return true;
- }
- /** Closing connection
- * Closes the connection
- */
- public void closeConnection() {
- if (closed == false) {
- try {
- socket.close();
- } catch (IOException ex) {
- logger.log(Level.SEVERE, null, ex);
- }
- }
- }
- @Override
- public void run() {
- try {
- // Login
- output.printf(Messages.LOGIN);
- String username = readUntilNewLine();
- output.printf(Messages.PASSWORD);
- String password = readUntilNewLine();
- // Login validation
- if (validateLogin(username, password) == true) {
- output.printf(Messages.OK);
- } else {
- output.printf(Messages.LOGIN_FAILED);
- closeConnection();
- closed = true;
- }
- // Messages
- int character;
- int counter = 0;
- String word = "";
- while (true) {
- while ((character = input.read()) != -1 && counter != 5) {
- word += Character.toString((char)character);
- // Info message
- if (word.startsWith("I")) {
- if (compareStrings(word, "INFO ") == false) {
- output.printf(Messages.SYNTAX_ERROR);
- closeConnection();
- closed = true;
- }
- // Foto message
- } else if (word.startsWith("F")) {
- if (compareStrings(word, "FOTO ") == false) {
- output.printf(Messages.SYNTAX_ERROR);
- closeConnection();
- closed = true;
- }
- } else {
- output.printf(Messages.SYNTAX_ERROR);
- closeConnection();
- closed = true;
- }
- if (counter == 4) {
- break;
- }
- counter++;
- }
- if (word.equals("INFO ")) {
- word = readUntilNewLine();
- output.printf(Messages.OK);
- } else if (word.equals("FOTO ")) {
- String result = validatePhoto();
- }
- }
- } catch (IOException ex) {
- logger.log(Level.SEVERE, null, ex);
- }
- }
- }
- /** Class Messages
- * Holds messages to be sent to robot
- *
- * @author beata
- */
- class Messages {
- public static final String LOGIN = "200 LOGIN\r\n";
- public static final String PASSWORD = "201 PASSWORD\r\n";
- public static final String OK = "202 OK\r\n";
- public static final String BAD_CHECKSUM = "300 BAD CHECKSUM\r\n";
- public static final String LOGIN_FAILED = "500 LOGIN FAILED\r\n";
- public static final String SYNTAX_ERROR = "501 SYNTAX ERROR\r\n";
- public static final String TIMEOUT = "502 TIMEOUT\r\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement