Commit bccc6ece authored by Wagner Franchin's avatar Wagner Franchin

Added src/ folder and Dockerfile

parent 531c6eb7
FROM openjdk:8-jdk-alpine
LABEL maintainer="Wagner Franchin"
ENV WEBPATH=/webserver/
ENV WEBSERVER="WebServerSocket"
RUN apk update && apk add ca-certificates wget && update-ca-certificates
RUN mkdir -p $WEBPATH
COPY src/ $WEBPATH
WORKDIR $WEBPATH
RUN javac *.java
EXPOSE 8000
CMD java $WEBSERVER
\ No newline at end of file
import com.sun.net.httpserver.HttpServer;
import handler.RequestsHandlerHttp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
public class WebServerHttp {
private static final int PORT = 8000;
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0);
server.createContext("/", new RequestsHandlerHttp());
//server.setExecutor(Executors.newFixedThreadPool(1));
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("WebServerHttp is listening on port " + PORT);
}
}
import handler.RequestsHandlerSocket;
import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* This program demonstrates a simple TCP/IP socket server.
*
* @author www.codejava.net
*/
public class WebServerSocket {
private static ExecutorService executorService;
private static final int PORT = 8000;
private static boolean running = true;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("WebServerSocket is listening on port " + PORT);
//executorService = Executors.newFixedThreadPool(1);
executorService = Executors.newCachedThreadPool();
while (running) {
RequestsHandlerSocket handler = new RequestsHandlerSocket(serverSocket.accept());
executorService.submit(handler);
}
} catch (IOException ex) {
System.out.println("Web server socket exception: " + ex.getMessage());
ex.printStackTrace();
} finally {
if (executorService != null) {
executorService.shutdown();
}
}
}
}
package handler;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import singleton.TaskExecutor;
import singleton.TasksList;
import java.io.*;
public class RequestsHandlerHttp implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
Headers requestHeaders = httpExchange.getRequestHeaders();
String response = "";
String requestMethod = httpExchange.getRequestMethod();
switch (requestMethod) {
case "GET":
response = TasksList.INSTANCE.list();
break;
case "POST":
InputStream input = httpExchange.getRequestBody();
StringBuilder params = new StringBuilder();
new BufferedReader(new InputStreamReader(input))
.lines()
.forEach(s -> params.append(s));
System.out.println("New request from " + requestHeaders.get("User-agent") + " -> " + params);
response = TaskExecutor.INSTANCE.run(params.toString());
break;
}
httpExchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
package handler;
import singleton.TaskExecutor;
import singleton.TasksList;
import java.io.*;
import java.net.Socket;
import java.util.*;
public class RequestsHandlerSocket implements Runnable {
private Socket socket;
public RequestsHandlerSocket(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
handle();
} catch (IOException e) {
e.printStackTrace();
}
}
private void handle() throws IOException {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
InputStream is = socket.getInputStream();
InputStreamReader isReader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isReader);
String response = "";
String requestType = getRequestType(br);
switch (requestType) {
case "GET":
response = TasksList.INSTANCE.list();
break;
case "POST":
String params = getParameters(br);
System.out.println("New task requested -> " + params);
response = TaskExecutor.INSTANCE.run(params);
break;
}
PrintWriter writer = new PrintWriter(out, true);
writer.println(response);
writer.close();
out.close();
br.close();
socket.close();
}
/**
* Get the type of the request: GET, POST and etc.
* @param in
* @return String
* @throws IOException
*/
private String getRequestType(BufferedReader in) throws IOException {
String request = in.readLine();
request = request.substring(0, request.indexOf(" ")).trim();
return request;
}
/**
* Get the POST parameters to be used to create the tasks
* @param in
* @return String
* @throws IOException
*/
private String getParameters(BufferedReader in) throws IOException {
StringBuilder values = new StringBuilder();
while(in.ready()){
values.append((char) in.read());
}
List<String> list = Arrays.asList(values.toString().split("\r"));
String result = list.get(list.size()-1).trim();
return result;
}
}
package singleton;
import task.*;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public enum TaskExecutor {
//Singleton
INSTANCE;
public String run(String parameters) {
List<String> list = Arrays.stream(parameters.split("&")).collect(Collectors.toList());
String taskName = list.get(0);
String input = list.get(1);
long start = System.currentTimeMillis();
Task task;
switch (taskName) {
case "TaskBubbleSort":
task = new TaskBubbleSort(input);
break;
case "TaskFiboRecursive":
task = new TaskFiboRecursive(input);
break;
case "TaskBitcoin":
task = new TaskBitcoin(input);
break;
default:
task = new NoTask("");
break;
}
task.execute();
TasksList.INSTANCE.add(task);
long end = System.currentTimeMillis();
String executedTime = new DecimalFormat("#0.00").format((end - start) / 1000d) + "s";
task.setExecutedTime(executedTime);
return task.getResult();
}
}
package singleton;
import task.Task;
import java.util.ArrayList;
import java.util.List;
public enum TasksList {
//Singleton
INSTANCE;
private List<Task> tasks;
TasksList() {
tasks = new ArrayList<>();
}
public void add(Task task) {
tasks.add(task);
}
public String list() {
StringBuilder stringBuilder = new StringBuilder();
tasks.forEach(task -> stringBuilder.append(task));
return stringBuilder.toString();
}
}
package task;
public class NoTask extends TaskImpl {
public NoTask(String input) {
super(input);
}
@Override
public void execute() { }
@Override
public String getResult() {
return "This task doesn't exist.\n";
}
}
package task;
public interface Task {
String getInput();
void execute();
void setExecutedTime(String executedTime);
String getResult();
}
package task;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class TaskBitcoin extends TaskImpl {
public TaskBitcoin(String input) {
super(input);
}
@Override
public void execute() {
String[] stringArray = input.split(",");
int times = Integer.valueOf(stringArray[0]);
result = getInfo(times);
}
public String getInfo(int times) {
List<String> values = new ArrayList<>();
String info;
try {
for (int i = 0; i < times; i++) {
info = getRequest("https://www.bitstamp.net/api/v2/ticker/btcusd");
info = info.substring(info.indexOf("\"last\": \""), info.indexOf(", \"times")).trim();
values.add(info);
Thread.sleep(1000);
}
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
return values.toString();
}
private String getRequest(String url) throws IOException {
StringBuilder response = new StringBuilder();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
if (in != null) in.close();
return response.toString();
}
}
package task;
import java.util.Arrays;
import java.util.StringJoiner;
public class TaskBubbleSort extends TaskImpl {
public TaskBubbleSort(String input) {
super(input);
}
@Override
public void execute() {
String[] stringArray = input.split(",");
int[] intArray = Arrays.stream(stringArray).mapToInt(s -> Integer.valueOf(s)).toArray();
sort(intArray);
result = printArray(intArray);
}
private void sort(int array[]) {
int n = array.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(array[j-1] > array[j]){
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
private String printArray(int[] array) {
StringJoiner stringJoiner = new StringJoiner(",", "[","]");
Arrays.stream(array).forEach(item -> stringJoiner.add(String.valueOf(item)));
return stringJoiner.toString();
}
}
package task;
public class TaskFiboRecursive extends TaskImpl {
public TaskFiboRecursive(String input) {
super(input);
}
@Override
public void execute() {
String[] stringArray = input.split(",");
// just one number is expected
int n = Integer.valueOf(stringArray[0]);
result = String.valueOf(fibonacci(n));
}
/**
* Recursive Fibonacci function
* @param n
* @return int
*/
private int fibonacci(int n) {
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
package task;
public abstract class TaskImpl implements Task {
protected String input;
protected String result;
protected String executedTime;
public TaskImpl(String input) {
this.input = input;
}
@Override
public String getInput() {
return input;
}
@Override
public String getResult() {
return "Result: " + result + "; Executed in: " + executedTime + "\n";
}
@Override
public void setExecutedTime(String executedTime) {
this.executedTime = executedTime;
}
@Override
public String toString() {
return this.getClass().getName() + "-> Params: " + input + "; " + this.getResult();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment