Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

worker changes #7

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions Engine/src/managers/GraphManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,12 @@ public GraphManager() {
userNameToUser = new HashMap<>();
}

public synchronized void addUser(String username, boolean isAdmin) {
IUser newUser;
if (isAdmin) {
newUser = new Admin(username);
} else {
newUser = new Worker(username);
}
userNameToUser.put(username, newUser);
public synchronized void addAdmin(String username) {
userNameToUser.put(username, new Admin(username));
}

public synchronized void addWorker(String username,int threads) {
userNameToUser.put(username, new Worker(username,threads));
}

// public synchronized void removeUser(String username) {
Expand Down
14 changes: 6 additions & 8 deletions Engine/src/managers/UserManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,12 @@ public UserManager() {
userNameToUser = new HashMap<>();
}

public synchronized void addUser(String username, boolean isAdmin) {
IUser newUser;
if (isAdmin) {
newUser = new Admin(username);
} else {
newUser = new Worker(username);
}
userNameToUser.put(username, newUser);
public synchronized void addAdmin(String username) {
userNameToUser.put(username, new Admin(username));
}

public synchronized void addWorker(String username,int threads) {
userNameToUser.put(username, new Worker(username,threads));
}

// public synchronized void removeUser(String username) {
Expand Down
89 changes: 48 additions & 41 deletions GPUPServer/src/main/java/servlets/LoginServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@

import java.io.IOException;

import static utils.Constants.USERNAME;
import static utils.Constants.ROLE;
import static utils.Constants.*;

@WebServlet(name = "Login", urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
Expand All @@ -35,22 +34,22 @@ public class LoginServlet extends HttpServlet {
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
String usernameFromSession = SessionUtils.getUsername(request);
UserManager userManager = ServletUtils.getUserManager(getServletContext());

if (usernameFromSession == null) {
String usernameFromParameter = request.getParameter(USERNAME);
String roleFromParameter = request.getParameter(ROLE);

if (usernameFromParameter == null || usernameFromParameter.isEmpty() || roleFromParameter == null) {
//no username in session and no username in parameter -
//redirect back to the index page
//this return an HTTP code back to the browser telling it to load
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad Request: wrong parameters");
} else {
//normalize the username value
usernameFromParameter = usernameFromParameter.trim();
try {
response.setContentType("text/plain;charset=UTF-8");
String usernameFromSession = SessionUtils.getUsername(request);
UserManager userManager = ServletUtils.getUserManager(getServletContext());

if (usernameFromSession == null) {
String usernameFromParameter = request.getParameter(USERNAME);
String roleFromParameter = request.getParameter(ROLE);
if (usernameFromParameter == null || usernameFromParameter.isEmpty() || roleFromParameter == null) {
//no username in session and no username in parameter -
//redirect back to the index page
//this return an HTTP code back to the browser telling it to load
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad Request: wrong parameters");
} else {
//normalize the username value
usernameFromParameter = usernameFromParameter.trim();
/*
One can ask why not enclose all the synchronizations inside the userManager object ?
Well, the atomic action we need to perform here includes both the question (isUserExists) and (potentially) the insertion
Expand All @@ -63,35 +62,43 @@ The synchronized is on this instance (the servlet).
A better code would be to perform only as little and as necessary things we need here inside the synchronized block and avoid
do here other not related actions (such as request dispatcher\redirection etc. this is shown here in that manner just to stress this issue
*/
synchronized (this) {
if (userManager.isUserExists(usernameFromParameter)) {
String errorMessage = "Username " + usernameFromParameter + " already exists. Please enter a different username.";
// username already exists, forward the request back to index.jsp
// with a parameter that indicates that an error should be displayed
// the request dispatcher obtained from the servlet context is one that MUST get an absolute path (starting with'/')
// and is relative to the web app root
// see this link for more details:
// http://timjansen.github.io/jarfiller/guide/servlet25/requestdispatcher.xhtml
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
response.getOutputStream().print(errorMessage);
synchronized (this) {
if (userManager.isUserExists(usernameFromParameter)) {
String errorMessage = "Username " + usernameFromParameter + " already exists. Please enter a different username.";
// username already exists, forward the request back to index.jsp
// with a parameter that indicates that an error should be displayed
// the request dispatcher obtained from the servlet context is one that MUST get an absolute path (starting with'/')
// and is relative to the web app root
// see this link for more details:
// http://timjansen.github.io/jarfiller/guide/servlet25/requestdispatcher.xhtml
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
response.getOutputStream().print(errorMessage);
// request.setAttribute(Constants.USER_NAME_ERROR, errorMessage);

// getServletContext().getRequestDispatcher(LOGIN_ERROR_URL).forward(request, response);
} else {
userManager.addUser(usernameFromParameter, roleFromParameter.equals("Admin"));
//set the username in a session so it will be available on each request
//the true parameter means that if a session object does not exists yet
//create a new one
request.getSession(true).setAttribute(Constants.USERNAME, usernameFromParameter);

//redirect the request to the chat room - in order to actually change the URL
response.setStatus(HttpServletResponse.SC_OK);
} else {
if (roleFromParameter.equals("Worker")) {
String threadsFromParameter = request.getParameter(THREADS);
userManager.addWorker(usernameFromParameter, Integer.parseInt(threadsFromParameter));
} else {
userManager.addAdmin(usernameFromParameter);
}
//set the username in a session so it will be available on each request
//the true parameter means that if a session object does not exists yet
//create a new one
request.getSession(true).setAttribute(Constants.USERNAME, usernameFromParameter);

//redirect the request to the chat room - in order to actually change the URL
response.setStatus(HttpServletResponse.SC_OK);
}
}
}
} else {
//user is already logged in
response.setStatus(HttpServletResponse.SC_OK);
}
} else {
//user is already logged in
response.setStatus(HttpServletResponse.SC_OK);
}catch (Exception e){
e.printStackTrace();
}
}

Expand Down
47 changes: 34 additions & 13 deletions GPUPServer/src/main/java/servlets/TaskUploadServlet.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package servlets;

import TargetGraph.Target;
import com.google.gson.JsonObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
Expand All @@ -14,6 +16,11 @@
import types.Worker;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

import static utils.Constants.*;

Expand All @@ -37,21 +44,35 @@ public class TaskUploadServlet extends HttpServlet {
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("text/plain;charset=UTF-8");
String usernameFromSession = SessionUtils.getUsername(request);
UserManager userManager = ServletUtils.getUserManager(getServletContext());
Admin admin = userManager.getAdmin(usernameFromSession);
if (admin != null) {
synchronized (this) {
String graphName = request.getParameter(GRAPHNAME);
Task task = GSON_INSTANCE.fromJson(request.getReader(), Task.class);
ServletUtils.getEngine(getServletContext()).addTask(task, graphName, admin);
response.setStatus(HttpServletResponse.SC_OK);
try (PrintWriter out = response.getWriter()) {
response.setContentType("text/plain;charset=UTF-8");
String usernameFromSession = SessionUtils.getUsername(request);
UserManager userManager = ServletUtils.getUserManager(getServletContext());
Admin admin = userManager.getAdmin(usernameFromSession);
if (admin != null) {
synchronized (this) {
String graphName = request.getParameter(GRAPHNAME);
// boolean fromScratch = Boolean.parseBoolean(request.getParameter(FROM_SCRATCH));
String requestData = request.getReader().lines().collect(Collectors.joining());
System.out.println("requestData = " + requestData);
JsonObject json = GSON_INSTANCE.fromJson(requestData, JsonObject.class);
JsonObject taskJson = json.get("task").getAsJsonObject();
Task task = GSON_INSTANCE.fromJson(requestData, (Class<? extends Task>) Class.forName(taskJson.get("type").getAsString()));

JsonObject targetsJson = json.get("targets").getAsJsonObject();
Set<Target> targets = Arrays.stream(GSON_INSTANCE.fromJson(targetsJson, Target[].class)).collect(Collectors.toSet());


ServletUtils.getEngine(getServletContext()).addTask(task, graphName, admin, targets);

response.setStatus(HttpServletResponse.SC_OK);
}
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} catch (Exception e) {
e.printStackTrace();
}

}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
Expand Down
45 changes: 45 additions & 0 deletions SharedEngine/src/types/GraphInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,26 @@ public class GraphInfo {
private final String middles;
private final String independents;
private final String roots;
private final String taskName;
private final String pricePerTarget;
private final String priceForTask;
private String taskStatus;
private String taskType;
private String workersOnTask;

public GraphInfo(TargetGraph graph) {
this.graphName = (graph.getGraphsName());
///////taskName;
///////task status;
///task type
///////price per target
////price for task;
//this.priceForTask = String.valueOf(Integer.valueOf(pricePerTarget)*graph.totalSize());
///get workers this.workersOnTask = graph.
this.priceForTask = "";
this.pricePerTarget = "";
this.taskName = "";
this.taskStatus = "";
this.createdBy = graph.getCreatedBy().getName();
this.totalTargets = String.valueOf(graph.totalSize());
Map<Type, Integer> typeIntegerMap = graph.getTypesStatistics();
Expand All @@ -27,6 +44,34 @@ public GraphInfo(TargetGraph graph) {
this.roots = String.valueOf(typeIntegerMap.get(Type.root));
}

public String getPriceForTask() {
return priceForTask;
}

public String getPricePerTarget() {
return pricePerTarget;
}

public String getTaskName() {
return taskName;
}

public String getTaskStatus() {
return taskStatus;
}

public String getWorkersOnTask() {
return workersOnTask;
}

public synchronized void addWorker() {
workersOnTask = String.valueOf(Integer.parseInt(this.workersOnTask)+1);
}

public synchronized void decreaseWorker(){
workersOnTask = String.valueOf(Integer.parseInt(this.workersOnTask)-1);
}

public String getGraphName() {
return this.graphName;
}
Expand Down
91 changes: 91 additions & 0 deletions SharedEngine/src/types/TargetsInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package types;

import TargetGraph.TargetGraph;
import TargetGraph.Type;
import lombok.ToString;

import java.util.Map;

@ToString
public class TargetsInfo {
private final String taskName;
private final String targetName;
private String taskType;
private String totalPrice;
private String targetStatus;
private String logs;


public TargetsInfo(Task task,Target target) {
this.taskName = task.getName();
this.targetName = target.toString();

this.priceForTask = "";
this.pricePerTarget = "";
this.taskName = "";
this.taskStatus = "";
this.createdBy = graph.getCreatedBy().getName();
this.totalTargets = String.valueOf(graph.totalSize());
Map<Type, Integer> typeIntegerMap = graph.getTypesStatistics();
this.leaves = String.valueOf(typeIntegerMap.get(Type.leaf));
this.independents = String.valueOf(typeIntegerMap.get(Type.independent));
this.middles = String.valueOf(typeIntegerMap.get(Type.middle));
this.roots = String.valueOf(typeIntegerMap.get(Type.root));
}

public String getPriceForTask() {
return priceForTask;
}

public String getPricePerTarget() {
return pricePerTarget;
}

public String getTaskName() {
return taskName;
}

public String getTaskStatus() {
return taskStatus;
}

public String getWorkersOnTask() {
return workersOnTask;
}

public synchronized void addWorker() {
workersOnTask = String.valueOf(Integer.parseInt(this.workersOnTask)+1);
}

public synchronized void decreaseWorker(){
workersOnTask = String.valueOf(Integer.parseInt(this.workersOnTask)-1);
}

public String getGraphName() {
return this.graphName;
}

public String getCreatedBy() {
return this.createdBy;
}

public String getTotalTargets() {
return this.totalTargets;
}

public String getLeaves() {
return this.leaves;
}

public String getMiddles() {
return this.middles;
}

public String getIndependents() {
return this.independents;
}

public String getRoots() {
return this.roots;
}
}
1 change: 1 addition & 0 deletions SharedEngine/src/types/TaskStatus.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types;

public enum TaskStatus {
NEW_MISSION,
ACTIVE,
PAUSED,
STOPPED,
Expand Down
Loading