Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package jur.pawel.server;
- import jur.pawel.model.IModel;
- import jur.pawel.model.Model;
- import jur.pawel.model.generation.WrongParametersException;
- import java.io.*;
- import java.net.*;
- import java.util.Arrays;
- import java.util.Properties;
- public class Server {
- private IModel model = new Model();
- private Properties properties = new Properties();
- private ServerSocket server;
- private Socket service;
- public Server() {
- try (FileInputStream in = new FileInputStream(".properties")) {
- properties.load(in);
- server = new ServerSocket(Integer.parseInt(properties.getProperty("port")));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void run() {
- while (true) {
- try {
- service = server.accept();
- runService(service);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- private void runService(Socket service) throws IOException {
- BufferedReader input = new BufferedReader(new InputStreamReader(service.getInputStream()));
- PrintWriter output = new PrintWriter(service.getOutputStream(), true);
- String receivedString;
- while(true) {
- receivedString = input.readLine();
- if(receivedString != null) {
- String[] splitReceived = receivedString.trim().toLowerCase().split("[ ]");
- ReceivedCommand command = interpretReceived(splitReceived);
- switch (command) {
- case Validation:
- case Help:
- case Generation:
- output.println("200");
- default:
- output.println("500");
- break;
- }
- String[] parameters = Arrays.copyOfRange(splitReceived, 1, splitReceived.length);
- output.println(execute(command, parameters));
- }
- else break;
- }
- }
- private String execute(ReceivedCommand command, String[] parameters) {
- String response = "";
- switch(command){
- case Help:
- response = "available commands: v <number> (validation of palindrome), g <min number> <max number> (generating a palindrome)";
- break;
- case Validation:
- response = model.validatePalindrome(parameters[0]).toString();
- break;
- case Generation:
- try {
- response = model.generatePalindrome(Integer.parseInt(parameters[0]), Integer.parseInt(parameters[1]));
- } catch (WrongParametersException e) {
- response = e.getMessage();
- }
- break;
- case Fail:
- response = "Wrong parameters, send \"help\" for more information";
- break;
- }
- return response;
- }
- private ReceivedCommand interpretReceived(String[] input) {
- if(input[0].equals("v") && input.length >= 2)
- return ReceivedCommand.Validation;
- if(input[0].equals("g") && input.length >= 3)
- return ReceivedCommand.Generation;
- if(input[0].equals("help"))
- return ReceivedCommand.Help;
- return ReceivedCommand.Fail;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement