Commit 945b20fb authored by hasan  khaddour's avatar hasan khaddour

Intiate The Project

parents
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.taskmanager</groupId>
<artifactId>webTaskManager</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
\ 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.print(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 static final String TASKS_PACKAGE = "task.";
public String run(String parameters) {
String taskName, input = "";
List<String> list = Arrays.stream(parameters.split("&")).collect(Collectors.toList());
long start = System.currentTimeMillis();
if (list.size() != 2) {
taskName = "TaskIncorrectParams";
} else {
taskName = list.get(0);
input = list.get(1);
}
Task task = createTask(taskName);
task.setInput(input);
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();
}
private Task createTask(String className) {
Task task = null;
try {
task = (Task)Class.forName(TASKS_PACKAGE + className).newInstance();
} catch (Exception e) {
try {
task = (Task)Class.forName(TASKS_PACKAGE + "TaskNotFound").newInstance();
} catch (Exception e1) {
e1.printStackTrace();
}
}
return task;
}
}
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 interface Task {
String getInput();
void setInput(String input);
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 {
@Override
public void execute() {
try {
int times = Integer.valueOf(input);
result = getInfo(times);
} catch (Exception e) {
result = "Exception: " + e.getMessage();
}
}
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 {
@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 {
@Override
public void execute() {
try {
int n = Integer.valueOf(input);
result = String.valueOf(fibonacci(n));
} catch (Exception e) {
result = "Exception: " + e.getMessage();
}
}
/**
* 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;
@Override
public String getInput() {
return input;
}
@Override
public void setInput(String input) {
this.input = 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();
}
}
package task;
public final class TaskIncorrectParams extends TaskImpl {
@Override
public void execute() { }
@Override
public String getResult() {
return "ERROR: A task must have 2 parameters.\n";
}
}
\ No newline at end of file
package task;
public final class TaskNotFound extends TaskImpl {
@Override
public void execute() { }
@Override
public String getResult() {
return "ERROR: This task doesn't exist.\n";
}
}
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