From 2d5dbe00f7e46f0743c33fc4d1a31587e5e95749 Mon Sep 17 00:00:00 2001 From: Manos Date: Thu, 29 Oct 2015 01:06:42 +0200 Subject: [PATCH] Initial commit --- nb-configuration.xml | 18 + pom.xml | 111 ++ .../java/com/www/server/DeviceService.java | 194 +++ .../java/com/www/server/DeviceUnregister.java | 112 ++ src/main/java/com/www/server/Edit.java | 180 +++ src/main/java/com/www/server/EditProp.java | 57 + src/main/java/com/www/server/EditStatus.java | 53 + src/main/java/com/www/server/Globals.java | 76 + src/main/java/com/www/server/Signin.java | 66 + .../java/com/www/server/SigninFilter.java | 33 + src/main/java/com/www/server/Signout.java | 15 + src/main/java/com/www/server/Signup.java | 111 ++ src/main/java/com/www/server/Task.java | 39 + src/main/java/com/www/server/TaskService.java | 676 +++++++++ src/main/java/com/www/server/Upload.java | 425 ++++++ src/main/java/com/www/server/UserService.java | 76 + src/main/java/com/www/server/Utils.java | 806 +++++++++++ .../java/com/www/server/privacy/Edit.java | 145 ++ .../com/www/server/privacy/EditStatus.java | 72 + .../www/server/privacy/PrivacyService.java | 419 ++++++ .../java/com/www/server/privacy/Upload.java | 245 ++++ src/main/webapp/META-INF/context.xml | 2 + src/main/webapp/WEB-INF/web.xml | 102 ++ src/main/webapp/img/apps.png | Bin 0 -> 3624 bytes src/main/webapp/main/edit.jsp | 391 +++++ src/main/webapp/main/home.jsp | 150 ++ src/main/webapp/main/upload.jsp | 195 +++ src/main/webapp/main/view.jsp | 423 ++++++ src/main/webapp/ppc.ico | Bin 0 -> 1150 bytes src/main/webapp/privacy/edit.jsp | 197 +++ src/main/webapp/privacy/home.jsp | 106 ++ src/main/webapp/privacy/upload.jsp | 114 ++ src/main/webapp/privacy/view.jsp | 156 ++ src/main/webapp/signin.jsp | 38 + src/main/webapp/signup.jsp | 68 + src/main/webapp/style.css | 1268 +++++++++++++++++ 36 files changed, 7139 insertions(+) create mode 100644 nb-configuration.xml create mode 100644 pom.xml create mode 100644 src/main/java/com/www/server/DeviceService.java create mode 100644 src/main/java/com/www/server/DeviceUnregister.java create mode 100644 src/main/java/com/www/server/Edit.java create mode 100644 src/main/java/com/www/server/EditProp.java create mode 100644 src/main/java/com/www/server/EditStatus.java create mode 100644 src/main/java/com/www/server/Globals.java create mode 100644 src/main/java/com/www/server/Signin.java create mode 100644 src/main/java/com/www/server/SigninFilter.java create mode 100644 src/main/java/com/www/server/Signout.java create mode 100644 src/main/java/com/www/server/Signup.java create mode 100644 src/main/java/com/www/server/Task.java create mode 100644 src/main/java/com/www/server/TaskService.java create mode 100644 src/main/java/com/www/server/Upload.java create mode 100644 src/main/java/com/www/server/UserService.java create mode 100644 src/main/java/com/www/server/Utils.java create mode 100644 src/main/java/com/www/server/privacy/Edit.java create mode 100644 src/main/java/com/www/server/privacy/EditStatus.java create mode 100644 src/main/java/com/www/server/privacy/PrivacyService.java create mode 100644 src/main/java/com/www/server/privacy/Upload.java create mode 100644 src/main/webapp/META-INF/context.xml create mode 100644 src/main/webapp/WEB-INF/web.xml create mode 100644 src/main/webapp/img/apps.png create mode 100644 src/main/webapp/main/edit.jsp create mode 100644 src/main/webapp/main/home.jsp create mode 100644 src/main/webapp/main/upload.jsp create mode 100644 src/main/webapp/main/view.jsp create mode 100644 src/main/webapp/ppc.ico create mode 100644 src/main/webapp/privacy/edit.jsp create mode 100644 src/main/webapp/privacy/home.jsp create mode 100644 src/main/webapp/privacy/upload.jsp create mode 100644 src/main/webapp/privacy/view.jsp create mode 100644 src/main/webapp/signin.jsp create mode 100644 src/main/webapp/signup.jsp create mode 100644 src/main/webapp/style.css diff --git a/nb-configuration.xml b/nb-configuration.xml new file mode 100644 index 0000000..4da1f6c --- /dev/null +++ b/nb-configuration.xml @@ -0,0 +1,18 @@ + + + + + + ide + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..0666e87 --- /dev/null +++ b/pom.xml @@ -0,0 +1,111 @@ + + + 4.0.0 + + com.www + EasyHarvestServer + 1.0 + war + + EasyHarvestServer + + + ${project.build.directory}/endorsed + UTF-8 + + + + + mysql + mysql-connector-java + 5.1.35 + + + commons-fileupload + commons-fileupload + 1.3.1 + + + jdom + jdom + 1.0 + + + org.codehaus.jettison + jettison + 1.3.7 + + + com.sun.jersey + jersey-servlet + 1.12 + + + com.sun.jersey + jersey-json + 1.12 + + + org.apache.commons + commons-lang3 + 3.4 + + + javax + javaee-web-api + 7.0 + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + ${endorsed.dir} + + + + + org.apache.maven.plugins + maven-war-plugin + 2.3 + + false + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.6 + + + validate + + copy + + + ${endorsed.dir} + true + + + javax + javaee-endorsed-api + 7.0 + jar + + + + + + + + + + diff --git a/src/main/java/com/www/server/DeviceService.java b/src/main/java/com/www/server/DeviceService.java new file mode 100644 index 0000000..016ef0c --- /dev/null +++ b/src/main/java/com/www/server/DeviceService.java @@ -0,0 +1,194 @@ +package com.www.server; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.ParseException; +import java.util.UUID; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +@Path("devs") +public class DeviceService { + + @Context + UriInfo uriInfo; + + @Context + Request request; + + @GET + @Produces(MediaType.TEXT_PLAIN) + public String respondAsReady() { + return "DeviceService is ready."; + } + + @GET + @Path("register_test") + @Produces(MediaType.TEXT_PLAIN) + public Response register_test() throws Exception { + String username = "emkatsom"; + String model = "nexus"; + String os = "android"; + +// String id = getNewId(); + String id = "0"; + + String date = Utils.getDate(); + String time = Utils.getTime(); + Class.forName("com.mysql.jdbc.Driver"); + ResultSet rs; + try ( + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement()) { + String sql = "INSERT INTO devices (`username`, `model`, `os`, `reg_date`, `reg_time`, `last_date`, `last_time`) " + + "VALUES ('" + username + "', '" + model + "', '" + os + "', '" + date + "', '" + time + "', '" + date + "', '" + time + "')"; + s.executeUpdate(sql); + s.executeQuery("SELECT * FROM devices ORDER BY id DESC LIMIT 1"); + rs = s.getResultSet(); + if (rs.next()) { + id = rs.getString("id"); + } + } + System.out.println("DeviceService/register: Device (" + username + "|" + model + "|" + os + ") with id " + id + " successfully registered."); + + deviceUnregister(); + return Response.ok().entity(id).build(); + } + + @POST + @Path("register") + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Produces(MediaType.APPLICATION_JSON) + public Response register(MultivaluedMap deviceParams) throws Exception { + String username = deviceParams.getFirst("username"); + String model = deviceParams.getFirst("model"); + String os = deviceParams.getFirst("os"); + +// String id = getNewId(); + String id = "0"; + + String date = Utils.getDate(); + String time = Utils.getTime(); + Class.forName("com.mysql.jdbc.Driver"); + ResultSet rs; + try ( + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement()) { + String sql = "INSERT INTO devices (`username`, `model`, `os`, `reg_date`, `reg_time`, `last_date`, `last_time`) " + + "VALUES ('" + username + "', '" + model + "', '" + os + "', '" + date + "', '" + time + "', '" + date + "', '" + time + "')"; + s.executeUpdate(sql); + s.executeQuery("SELECT * FROM devices ORDER BY id DESC LIMIT 1"); + rs = s.getResultSet(); + if (rs.next()) { + id = rs.getString("id"); + } + } + System.out.println("DeviceService/register: Device (" + username + "|" + model + "|" + os + ") with id " + id + " successfully registered."); + + deviceUnregister(); + return Response.ok().entity(id).build(); + } + + @GET + @Path("{id}/unregister") + public Response unregister(@PathParam("id") String id) throws Exception { + Class.forName("com.mysql.jdbc.Driver"); + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement(); + s.executeQuery("SELECT * FROM devices WHERE id='" + id + "'"); + ResultSet rs = s.getResultSet(); + String result; + if (rs.next()) { + s.executeUpdate("DELETE FROM devices WHERE id='" + id + "'"); + System.out.println("DeviceService.unregister: Device with id " + id + " successfully unregistered."); + result = "OK"; + } else { + System.out.println("DeviceService.unregister: Device with id " + id + " not found."); + result = "Not registered"; + } + rs.close(); + s.close(); + c.close();/**/ + + deviceUnregister(); + return Response.ok().entity(result).build(); + } + + @POST + @Path("test") + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Produces(MediaType.APPLICATION_JSON) + public Response test(MultivaluedMap deviceParams) throws ClassNotFoundException, SQLException, ParseException { + System.out.println("test"); + + System.out.println(deviceParams.toString()); + + String username = deviceParams.getFirst("username"); + String model = deviceParams.getFirst("model"); + String os = deviceParams.getFirst("os"); + + System.out.println(username + "|" + model + "|" + os); + + return Response.ok().entity("OK").build(); + } + + private String getNewId() throws ClassNotFoundException, SQLException { + String id = ""; + Class.forName("com.mysql.jdbc.Driver"); + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = null; + ResultSet rs; + do { + id = UUID.randomUUID().toString().replaceAll("-", ""); + s = c.createStatement(); + s.executeQuery("SELECT * FROM devices WHERE id='" + id + "'"); + rs = s.getResultSet(); + } while (rs.next()); + s.close(); + rs.close(); + c.close(); + return id; + } + + /* + Description: + Called periodically to delete inactive devices. + + Changelog: + */ + public void deviceUnregister() throws SQLException, ClassNotFoundException, ParseException { + Class.forName("com.mysql.jdbc.Driver"); + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement(); + s.executeQuery("SELECT * FROM devices"); + ResultSet rs = s.getResultSet(); + while (rs.next()) { + String id = rs.getString("id"); + String date = rs.getString("last_date"); + String time = rs.getString("last_time"); + //if (!Utils.isTimeRecent(time, 0, 1, 0)) { + if (!Utils.isDateRecent(date, 1, 0, 0)) { + System.out.println("DeviceService/DeviceUnregister: Unregistering device with id " + id + "..."); + s = c.createStatement(); + s.executeUpdate("DELETE FROM devices WHERE id='" + id + "'"); + } + } + s.close(); + rs.close(); + c.close(); + } + +} diff --git a/src/main/java/com/www/server/DeviceUnregister.java b/src/main/java/com/www/server/DeviceUnregister.java new file mode 100644 index 0000000..0b0c0b5 --- /dev/null +++ b/src/main/java/com/www/server/DeviceUnregister.java @@ -0,0 +1,112 @@ +package com.www.server; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class DeviceUnregister extends Thread { + + String DB_SERVER = Globals.db_server; + String DB_USERNAME = Globals.db_username; + String DB_PASSWORD = Globals.db_password; + + ResultSet rs = null; + Statement s = null; + Connection c = null; + + DeviceUnregister() { + super("DeviceUnregister thread"); + System.out.println("DeviceUnregister: " + this); + try { + Class.forName("com.mysql.jdbc.Driver"); + c = DriverManager.getConnection(DB_SERVER, DB_USERNAME, DB_PASSWORD); + } catch (ClassNotFoundException | SQLException ex) { + Logger.getLogger(DeviceUnregister.class.getName()).log(Level.SEVERE, null, ex); + } + start(); + } + + public void run() { + try { + while (true) { + s = c.createStatement(); + s.executeQuery("SELECT * FROM devices"); + rs = s.getResultSet(); + if (rs.next()) { + do { + String id = rs.getString("id"); + String date = rs.getString("last_date"); + String time = rs.getString("last_time"); + if (!isTimeRecent(time)) { + System.out.println("DeviceUnregister: Unregistering device with id " + id + "..."); + s = c.createStatement(); + s.executeUpdate("DELETE FROM devices WHERE id='" + id + "'"); + }/**/ + /*if (!isDateRecent(date)) { + System.out.println("DeviceUnregister: Unregistering device with id " + id + "..."); + s = c.createStatement(); + s.executeUpdate("DELETE FROM devices WHERE id='" + id + "'"); + }/**/ + + } while (rs.next()); + Thread.sleep(6 * 10000); + //Thread.sleep(86400000); + } else { + break; + } + } + } catch (InterruptedException e) { + System.out.println("DeviceUnregister: Interrupted."); + } catch (SQLException | ParseException ex) { + Logger.getLogger(DeviceUnregister.class.getName()).log(Level.SEVERE, null, ex); + } + System.out.println("DeviceUnregister: Exiting thread..."); + try { + s.close(); + rs.close(); + c.close(); + } catch (SQLException ex) { + Logger.getLogger(DeviceUnregister.class.getName()).log(Level.SEVERE, null, ex); + } + + } + + private Boolean isDateRecent(String date) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); + Calendar calPrev = Calendar.getInstance(); + Date datePrev = sdf.parse(date); + calPrev.setTime(datePrev); + Calendar calCurr = Calendar.getInstance(); + Date dateCurr = sdf.parse(sdf.format(calCurr.getTime())); + calCurr.setTime(dateCurr); + calCurr.add(Calendar.MONTH, -1); + /*System.out.println("calCurr: " + sdf.format(calCurr.getTime())); + System.out.println("calPrev: " + sdf.format(calPrev.getTime())); + System.out.println("calPrev after calCurr: " + calPrev.after(calCurr));/**/ + return calPrev.after(calCurr); + } + + private Boolean isTimeRecent(String time) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); + Calendar calPrev = Calendar.getInstance(); + Date datePrev = sdf.parse(time); + calPrev.setTime(datePrev); + Calendar calCurr = Calendar.getInstance(); + Date dateCurr = sdf.parse(sdf.format(calCurr.getTime())); + calCurr.setTime(dateCurr); + calCurr.add(Calendar.MINUTE, -2); + /*System.out.println("calCurr: " + sdf.format(calCurr.getTime())); + System.out.println("calPrev: " + sdf.format(calPrev.getTime())); + System.out.println("calPrev after calCurr: " + calPrev.after(calCurr));/**/ + return calPrev.after(calCurr); + } + +} diff --git a/src/main/java/com/www/server/Edit.java b/src/main/java/com/www/server/Edit.java new file mode 100644 index 0000000..97d941a --- /dev/null +++ b/src/main/java/com/www/server/Edit.java @@ -0,0 +1,180 @@ +package com.www.server; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.sql.SQLException; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.jdom.JDOMException; + +public class Edit extends HttpServlet { + + private String CONSOLE_CMD, DB_DIR, SERVER_URL, LIB_URL, JAVAC_CMD, DX_CMD, DB_SERVER, DB_USERNAME, DB_PASSWORD; + private Boolean isCompiled = true; + private Boolean isCompiledClient = false; + private Boolean hasServer = false; + private Boolean isCompiledServer = false; + private String userName, userDir, + fileId, fileDir, xmlUrl, + fileNameClient, fileCodeClient, fileCompileClient, dirClient, fileUrlClient, fileTimeClient, fileDateClient, + fileNameServer, fileCodeServer, fileCompileServer, dirServer, fileUrlServer, fileTimeServer, fileDateServer; + + @Override + public void init() { + SERVER_URL = Globals.server_url; + DB_DIR = Globals.db_dir; + CONSOLE_CMD = Globals.console_cmd; + LIB_URL = Globals.lib_url; + JAVAC_CMD = Globals.javac_cmd; + DX_CMD = Globals.dx_cmd; + DB_USERNAME = Globals.db_username; + DB_PASSWORD = Globals.db_password; + DB_SERVER = Globals.db_server; + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { + HttpSession session = request.getSession(true); + userName = (String) session.getAttribute("username"); + try { + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + for (FileItem item : items) { + String fieldName = item.getFieldName(); + if (item.isFormField()) { + String fieldValue = item.getString(); + if ("file_id".equals(fieldName)) { + fileId = fieldValue; + } + if ("client_name".equals(fieldName)) { + fileNameClient = fieldValue; + } + if ("server_name".equals(fieldName)) { + if (Utils.stringIsEmpty(fieldValue)) { + hasServer = false; + } else { + fileNameServer = fieldValue; + hasServer = true; + } + } + if ("client_code".equals(fieldName)) { + fileCodeClient = fieldValue; + } + if ("server_code".equals(fieldName)) { + fileCodeServer = fieldValue; + } + if ("client_compiled".equals(fieldName)) { + if ("true".equals(fieldValue)) { + isCompiledClient = true; + } else { + isCompiledClient = false; + } + } + if ("server_compiled".equals(fieldName)) { + if ("true".equals(fieldValue)) { + isCompiledServer = true; + } else { + isCompiledServer = false; + } + } + } + } + } catch (FileUploadException e) { + throw new ServletException("Cannot parse multipart request.", e); + } + System.out.println("userName: " + userName + + "\nfileId: " + fileId + + "\nclient_name: " + fileNameClient + + "\nisCompiledClient: " + isCompiledClient + + "\nserver_name: " + fileNameServer + + "\nisCompiledServer: " + isCompiledServer); + try { + initFile(); + if (!isCompiledClient) { + File file = new File(fileUrlClient); + FileWriter fw = new FileWriter(file.getAbsoluteFile()); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(fileCodeClient); + bw.close(); + fileCompileClient = Utils.compileAndroidFile(dirClient, fileNameClient); + fileCompileClient += "\n" + Utils.compileDex(dirClient, fileNameClient); + fileDateClient = Utils.getDate(); + fileTimeClient = Utils.getTime(); + if (Utils.stringIsEmpty(fileCompileClient)) { + isCompiledClient = true; + isCompiled = true; + Utils.setText(xmlUrl, "client", "compile", "status", "true"); + Utils.setText(fileDir + "/" + fileId + ".xml", "client", "zip_size", Utils.zipDex(dirClient, fileId)); + } else { + isCompiledClient = false; + isCompiled = false; + } + Utils.setText(xmlUrl, "client", "compile", "date", fileDateClient); + Utils.setText(xmlUrl, "client", "compile", "time", fileTimeClient); + Utils.setText(xmlUrl, "client", "compile", "output", fileCompileClient); + + } + if (hasServer) { + if (!isCompiledServer) { + File file = new File(fileUrlServer); + FileWriter fw = new FileWriter(file.getAbsoluteFile()); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(fileCodeServer); + bw.close(); + fileCompileServer = Utils.compileFile(dirServer, fileNameServer); + fileDateServer = Utils.getDate(); + fileTimeServer = Utils.getTime(); + if (Utils.stringIsEmpty(fileCompileServer)) { + isCompiledServer = true; + Utils.setText(xmlUrl, "server", "compile", "status", "true"); + } else { + isCompiledServer = false; + isCompiled = false; + } + Utils.setText(xmlUrl, "server", "compile", "date", fileDateServer); + Utils.setText(xmlUrl, "server", "compile", "time", fileTimeServer); + Utils.setText(xmlUrl, "server", "compile", "output", fileCompileServer); + } + } + if (isCompiled) { + Utils.updateReady("tasks", fileId, "YES"); + } + destroyFile(); + response.sendRedirect(response.encodeRedirectURL(SERVER_URL + "/main/view.jsp?id=" + fileId)); + } catch (InterruptedException | JDOMException | ClassNotFoundException | SQLException ex) { + Logger.getLogger(Edit.class.getName()).log(Level.SEVERE, null, ex); + } + } + + private void initFile() throws ClassNotFoundException, SQLException { + userDir = DB_DIR + "/" + userName; + fileDir = userDir + "/sensing/" + fileId; + xmlUrl = fileDir + "/" + fileId + ".xml"; + dirClient = fileDir + "/client"; + fileUrlClient = dirClient + "/" + fileNameClient; + dirServer = fileDir + "/server"; + fileUrlServer = dirServer + "/" + fileNameServer; + } + + private void destroyFile() { + isCompiled = true; + hasServer = false; + fileNameServer = ""; + fileCodeServer = ""; + isCompiledServer = false; + fileNameServer = ""; + fileCodeServer = ""; + isCompiledClient = false; + } +} diff --git a/src/main/java/com/www/server/EditProp.java b/src/main/java/com/www/server/EditProp.java new file mode 100644 index 0000000..cc9e538 --- /dev/null +++ b/src/main/java/com/www/server/EditProp.java @@ -0,0 +1,57 @@ +package com.www.server; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import org.jdom.JDOMException; + +public class EditProp extends HttpServlet { + + private String CONSOLE_CMD, DB_DIR, LIB_URL, JAVAC_CMD, DX_CMD, SERVER_URL, DB_SERVER, DB_USERNAME, DB_PASSWORD; + private boolean isMultipart; + String userName, jspName, fileId; + String mapCheckBox, sw_lat, sw_lng, ne_lat, ne_lng; + String timeCheckBox, timeFrom, timeTo; + + @Override + public void init() { + SERVER_URL = Globals.server_url; + DB_DIR = Globals.db_dir; + CONSOLE_CMD = Globals.console_cmd; + LIB_URL = Globals.lib_url; + JAVAC_CMD = Globals.javac_cmd; + DX_CMD = Globals.dx_cmd; + DB_USERNAME = Globals.db_username; + DB_PASSWORD = Globals.db_password; + DB_SERVER = Globals.db_server; + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + HttpSession session = request.getSession(true); + userName = (String) session.getAttribute("username"); + fileId = (String) request.getParameter("file_id"); + String fileDir = ""; + String app = "privacy"; + fileDir = Utils.getDir(app, fileId); + String xmlUrl = fileDir + "/" + fileId + ".xml"; + if ("on".equals(Utils.getText(xmlUrl, "client", "map", "status"))) { + Utils.setText(xmlUrl, "client", "map", "sw_lat", (String) request.getParameter("view_map_sw_lat")); + Utils.setText(xmlUrl, "client", "map", "sw_lng", (String) request.getParameter("view_map_sw_lng")); + Utils.setText(xmlUrl, "client", "map", "ne_lat", (String) request.getParameter("view_map_ne_lat")); + Utils.setText(xmlUrl, "client", "map", "ne_lng", (String) request.getParameter("view_map_ne_lng")); + } + if ("on".equals(Utils.getText(xmlUrl, "client", "time", "status"))) { + Utils.setText(xmlUrl, "client", "time", "from", (String) request.getParameter("view_time_selection_from")); + Utils.setText(xmlUrl, "client", "time", "to", (String) request.getParameter("view_time_selection_to")); + } + + response.sendRedirect(response.encodeRedirectURL("./main/view.jsp?id=" + fileId)); + } +} diff --git a/src/main/java/com/www/server/EditStatus.java b/src/main/java/com/www/server/EditStatus.java new file mode 100644 index 0000000..a7d197f --- /dev/null +++ b/src/main/java/com/www/server/EditStatus.java @@ -0,0 +1,53 @@ +package com.www.server; + +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +public class EditStatus extends HttpServlet { + + private String CONSOLE_CMD, DB_DIR, LIB_URL, JAVAC_CMD, DX_CMD, SERVER_URL, DB_SERVER, DB_USERNAME, DB_PASSWORD; + private boolean isMultipart; + String userName, jspName, fileId; + + @Override + public void init() { + SERVER_URL = Globals.server_url; + DB_DIR = Globals.db_dir; + CONSOLE_CMD = Globals.console_cmd; + LIB_URL = Globals.lib_url; + JAVAC_CMD = Globals.javac_cmd; + DX_CMD = Globals.dx_cmd; + DB_USERNAME = Globals.db_username; + DB_PASSWORD = Globals.db_password; + DB_SERVER = Globals.db_server; + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + HttpSession session = request.getSession(true); + userName = (String) session.getAttribute("username"); + jspName = (String) request.getParameter("jsp_name"); + fileId = (String) request.getParameter("view_file_id"); + String fileDir = ""; + fileDir = Utils.getDir("sensing", fileId); + String xmlUrl = fileDir + "/" + fileId + ".xml"; + String status = (String) request.getParameter("view_status_button"); + if ("START".equals(status)) { + Utils.setText(xmlUrl, "status", "start"); + } else if ("PAUSE".equals(status)) { + Utils.setText(xmlUrl, "status", "pause"); + } else { + Utils.setText(xmlUrl, "status", "stop"); + Utils.updateReady("tasks", fileId, "NO"); + } + if ("edit".equals(jspName)) { + response.sendRedirect(response.encodeRedirectURL("./main/edit.jsp?id=" + fileId)); + } else { + response.sendRedirect(response.encodeRedirectURL("./main/view.jsp?id=" + fileId)); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/www/server/Globals.java b/src/main/java/com/www/server/Globals.java new file mode 100644 index 0000000..fa45d19 --- /dev/null +++ b/src/main/java/com/www/server/Globals.java @@ -0,0 +1,76 @@ +package com.www.server; + +import static java.lang.Boolean.*; + +/* + * Description: + * Paths and variables. + * + * Changelog: + * 150523 - Miscellaneous path changes. + */ +public class Globals { + /* + public static String logo = "πpc"; + public static String h1 = "πing - pong computing"; + public static String p = "Execute code on mobile devices through the web."; + /**/ + + public static String logo = "EasyHarvest"; + public static String h1 = "EasyHarvest"; + public static String p = "Supporting the Deployment and Management of Sensing Applications on Smartphones.";/**/ + + public static Boolean DBG = FALSE; +// public static Boolean DBG = TRUE; + + /* + * PC values. + */ + /**/ + public static String db_dir = "C:/EasyHarvest"; + public static String db_server = "jdbc:mysql://localhost:3306/server"; + public static String db_username = "root"; + public static String db_password = "root"; + public static String server_url = "http://localhost:8084/Server"; + public static String console_cmd = "cmd"; + public static String javac_cmd = "C:/Program Files/Java/jdk1.8.0_25/bin/javac"; + public static String lib_url = "C:/Program Files (x86)/Android/android-sdk/platforms/android-23/android.jar"; + public static String dx_cmd = "C:/Program Files (x86)/Android/android-sdk/build-tools/23.0.1/dx"; + public static String zip_cmd = "C:/Program Files/7-Zip/7z"; + public static String zip_args = "a"; + /**/ + + /* + * MAC values. + */ + /* + public static String db_dir = "/Users/emkatsom/EasyHarvest"; + public static String db_server = "jdbc:mysql://localhost:3306/server"; + public static String db_username = "root"; + public static String db_password = "root"; + public static String server_url = "http://localhost:8084/Server"; + public static String console_cmd = "sh"; + public static String javac_cmd = "javac"; + public static String lib_url = "/Users/emkatsom/Library/Android/sdk/platforms/android-22/android.jar"; + public static String dx_cmd = "/Users/emkatsom/Library/Android/sdk/build-tools/22.0.1/dx"; + public static String zip_cmd = "zip"; + public static String zip_args = ""; + /**/ + + /* + * HOST values. + */ + /* + public static String db_dir = "/var/lib/tomcat6/webapps/db"; + public static String db_server = "jdbc:mysql://localhost:3306/server"; + public static String db_username = "root"; + public static String db_password = "root"; + public static String server_url = ""; + public static String console_cmd = "sh"; + public static String javac_cmd = "javac"; + public static String lib_url = "/opt/android/android.jar"; + public static String dx_cmd = "/opt/android/dx"; + public static String zip_cmd = "zip"; + public static String zip_args = ""; + /**/ +} diff --git a/src/main/java/com/www/server/Signin.java b/src/main/java/com/www/server/Signin.java new file mode 100644 index 0000000..f220891 --- /dev/null +++ b/src/main/java/com/www/server/Signin.java @@ -0,0 +1,66 @@ +package com.www.server; + +import java.io.*; +import java.sql.*; +import javax.servlet.*; +import javax.servlet.http.*; + +public class Signin extends HttpServlet { + + //private ServletConfig config; + private String DB_USERNAME; + private String DB_PASSWORD; + private String DB_SERVER; + + @Override + public void init() throws ServletException { + DB_USERNAME = Globals.db_username; + DB_PASSWORD = Globals.db_password; + DB_SERVER = Globals.db_server; + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + HttpSession session; + PrintWriter out = response.getWriter(); + Connection connection; + ResultSet rs; + Statement s; + String username = request.getParameter("username"); + String password = request.getParameter("password"); + String message = ""; + Boolean error = true; + response.setContentType("text/html"); + try { + Class.forName("com.mysql.jdbc.Driver"); + connection = DriverManager.getConnection(DB_SERVER, DB_USERNAME, DB_PASSWORD); + String sql = "SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'"; + s = connection.createStatement(); + s.executeQuery(sql); + rs = s.getResultSet(); + if (rs.next()) { + error = false; + } + rs.close(); + s.close(); + connection.close(); + if (!error) { + session = request.getSession(true); + session.setAttribute("username", username); + response.sendRedirect(response.encodeRedirectURL("./main/home.jsp")); + } else { + message = "The username or password you entered is incorrect."; + request.setAttribute("errorMessage", message); + RequestDispatcher view = request.getRequestDispatcher("/signin.jsp"); + view.forward(request, response); + } + } catch (Exception e) { + System.out.println("Exception: " + e); + } + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.sendRedirect(response.encodeRedirectURL("signin.jsp")); + } +} diff --git a/src/main/java/com/www/server/SigninFilter.java b/src/main/java/com/www/server/SigninFilter.java new file mode 100644 index 0000000..7575c5a --- /dev/null +++ b/src/main/java/com/www/server/SigninFilter.java @@ -0,0 +1,33 @@ +package com.www.server; +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +public class SigninFilter implements Filter { + @Override + public void init(FilterConfig filterConfig) {} + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) req; + HttpServletResponse response = (HttpServletResponse) res; + HttpSession session = request.getSession(); + //System.out.println("filter: " + (String) session.getAttribute("username")); + if (session == null || session.getAttribute("username") == null) { + // No logged-in user found, so redirect to login page. + response.sendRedirect(Globals.server_url + "/signin.jsp"); + } else { + response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. + response.setHeader("Pragma", "no-cache"); // HTTP 1.0. + response.setDateHeader("Expires", 0); // Proxies. + chain.doFilter(req, res); + } + } + @Override + public void destroy() {} +} \ No newline at end of file diff --git a/src/main/java/com/www/server/Signout.java b/src/main/java/com/www/server/Signout.java new file mode 100644 index 0000000..d4012d6 --- /dev/null +++ b/src/main/java/com/www/server/Signout.java @@ -0,0 +1,15 @@ +package com.www.server; +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +public class Signout extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setHeader("Cache-Control", "no-cache, no-store"); + response.setHeader("Pragma", "no-cache"); + request.getSession().invalidate(); + response.sendRedirect(request.getContextPath() + "/signin.jsp"); + } +} diff --git a/src/main/java/com/www/server/Signup.java b/src/main/java/com/www/server/Signup.java new file mode 100644 index 0000000..ce52fc0 --- /dev/null +++ b/src/main/java/com/www/server/Signup.java @@ -0,0 +1,111 @@ +package com.www.server; + +import java.io.*; +import java.io.File; +import java.sql.*; +import javax.servlet.*; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +public class Signup extends HttpServlet { + + private String DB_DIR; + private String DB_SERVER; + private String DB_USERNAME; + private String DB_PASSWORD; + + @Override + public void init() { + DB_DIR = Globals.db_dir; + DB_SERVER = Globals.db_server; + DB_USERNAME = Globals.db_username; + DB_PASSWORD = Globals.db_password; + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + PrintWriter out = response.getWriter(); + HttpSession session; + ResultSet rs; + Statement s; + String email = request.getParameter("email"); + String username = request.getParameter("username"); + String password = request.getParameter("password"); + response.setContentType("text/html"); + String remoteAddr = ""; + Boolean error = false; + try { + Class.forName("com.mysql.jdbc.Driver"); + Connection connection = DriverManager.getConnection(DB_SERVER, DB_USERNAME, DB_PASSWORD); + s = connection.createStatement(); + s.executeQuery("SELECT * FROM users WHERE email='" + email + "'"); + rs = s.getResultSet(); + if (rs.next()) { + String message = "Email \"" + email + "\" is already in use."; + request.setAttribute("errorMessageEmail", message); + System.out.println("Signup: " + message); + error = true; + } + s = connection.createStatement(); + s.executeQuery("SELECT * FROM users WHERE username='" + username + "'"); + rs = s.getResultSet(); + if (rs.next()) { + String message = "Username \"" + username + "\" is already in use."; + request.setAttribute("errorMessageUsername", message); + System.out.println("Signup: " + message); + error = true; + } + remoteAddr = request.getRemoteAddr(); + //ReCaptchaImpl reCaptcha = new ReCaptchaImpl(); + //reCaptcha.setPrivateKey("6LezstoSAAAAAEE9lfB6TR2kEX81_peDt4n03K4l"); + //String challenge = request.getParameter("recaptcha_challenge_field"); + //String uresponse = request.getParameter("recaptcha_response_field"); + //ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse); + /*if (!reCaptchaResponse.isValid()) { + print_wrong_once(error); + out.print("

Validation code is wrong.

"); + error = 1; + }*/ + if (error) { + rs.close(); + s.close(); + connection.close(); + request.setCharacterEncoding("UTF-8"); + RequestDispatcher rd = request.getRequestDispatcher(response.encodeURL("signup.jsp")); + rd.forward(request, response); + } else { + s.executeUpdate("INSERT INTO users (`username`, `password`, `email`) VALUES ('" + username + "', '" + password + "', '" + email + "')"); + rs.close(); + s.close(); + connection.close(); + // User directory + File dir = new File(DB_DIR + "/" + username); + dir.mkdir(); + System.out.println("Signup: " + "Created directory at " + dir.getPath()); + + // Sensing tasks directory + dir = new File(DB_DIR + "/" + username + "/sensing"); + dir.mkdir(); + System.out.println("Signup: " + "Created directory at " + dir.getPath()); + + // Privacy mechanisms directory + dir = new File(DB_DIR + "/" + username + "/privacy"); + dir.mkdir(); + System.out.println("Signup: " + "Created directory at " + dir.getPath()); + + session = request.getSession(true); + session.setAttribute("username", request.getParameter("username")); + response.sendRedirect(response.encodeRedirectURL("./main/home.jsp")); + } + } catch (Exception e) { + System.out.println("Exception: " + e); + } + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.sendRedirect(response.encodeRedirectURL("signup.jsp")); + } +} diff --git a/src/main/java/com/www/server/Task.java b/src/main/java/com/www/server/Task.java new file mode 100644 index 0000000..364f355 --- /dev/null +++ b/src/main/java/com/www/server/Task.java @@ -0,0 +1,39 @@ +package com.www.server; + +import javax.xml.bind.annotation.XmlRootElement; +import org.apache.commons.io.FilenameUtils; + +@XmlRootElement +public class Task { + + public String taskID, taskName, taskSize, taskStatus, className; + public String timeStatus, timeFrom, timeTo; + public String locStatus, locSWlat, locSWlng, locNElat, locNElng; + + public Task(String xmlUrl) { + try { + this.taskID = Utils.getText(xmlUrl, "id"); + this.taskName = Utils.getText(xmlUrl, "client", "name"); + this.taskSize = Utils.getText(xmlUrl, "client", "zip_size"); + this.taskStatus = Utils.getText(xmlUrl, "status"); + + this.className = FilenameUtils.removeExtension(taskName); + + this.timeStatus = Utils.getText(xmlUrl, "client", "time", "status"); + if (!this.timeStatus.isEmpty()) { + this.timeFrom = Utils.getText(xmlUrl, "client", "time", "from"); + this.timeTo = Utils.getText(xmlUrl, "client", "time", "to"); + } + + this.locStatus = Utils.getText(xmlUrl, "client", "map", "status"); + if (!this.locStatus.isEmpty()) { + this.locSWlat = Utils.getText(xmlUrl, "client", "map", "sw_lat"); + this.locSWlng = Utils.getText(xmlUrl, "client", "map", "sw_lng"); + this.locNElat = Utils.getText(xmlUrl, "client", "map", "ne_lat"); + this.locNElng = Utils.getText(xmlUrl, "client", "map", "ne_lng"); + } + } catch (Exception ex) { + //Logger.getLogger(Task.class.getName()).log(Level.SEVERE, null, ex); + } + } +} diff --git a/src/main/java/com/www/server/TaskService.java b/src/main/java/com/www/server/TaskService.java new file mode 100644 index 0000000..1043846 --- /dev/null +++ b/src/main/java/com/www/server/TaskService.java @@ -0,0 +1,676 @@ +package com.www.server; + +import java.io.*; +import java.lang.reflect.*; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.*; +import java.util.logging.*; +import java.util.zip.*; +import javax.ws.rs.*; +import javax.ws.rs.core.*; +import javax.ws.rs.core.Response.*; +import org.apache.commons.io.*; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.jdom.*; +import org.jdom.input.*; +import org.jdom.output.*; + +@Path("tasks") +public class TaskService { + + String app = "sensing"; + + @Context + private UriInfo context; + + @GET + @Produces(MediaType.TEXT_PLAIN) + public String respondAsReady() { + return "TaskService is ready."; + } + + @GET + @Path("test/{param}") + @Produces(MediaType.TEXT_PLAIN) + public String test(@PathParam("param") String id) { + return id; + } + + @GET + @Path("gettaskinfo_test/{deviceID}") + @Produces(MediaType.APPLICATION_JSON) + public Task getTaskInfo_test(@PathParam("deviceID") String deviceID) throws Exception { + String taskID = getReadyTask(); + String taskDir = ""; + String xmlUrl = ""; + Task task = null; + if (!taskID.isEmpty()) { + System.out.println("TaskService/getTaskInfo: Returning task info with id " + taskID + " ..."); + taskDir = Utils.getDir(app, taskID); + updateDownloaded(taskID); + xmlUrl = taskDir + "/" + taskID + ".xml"; + if (Utils.getText(xmlUrl, "status").isEmpty()) { + Utils.setText(xmlUrl, "status", "start"); + } + task = new Task(taskDir + "/" + taskID + ".xml"); + } + Utils.updateDeviceActivity(deviceID); + return task; + } + + @GET + @Path("gettaskinfo/{deviceID}") + @Produces(MediaType.APPLICATION_JSON) + public Task getTaskInfo(@PathParam("deviceID") String deviceID) throws Exception { + String taskID = getReadyTask(); + String taskDir = ""; + String xmlUrl = ""; + Task task = null; + if (!taskID.isEmpty()) { + System.out.println("TaskService/getTaskInfo: Returning task info with id " + taskID + " ..."); + taskDir = Utils.getDir(app, taskID); + updateDownloaded(taskID); + xmlUrl = taskDir + "/" + taskID + ".xml"; + if (Utils.getText(xmlUrl, "status").isEmpty()) { + Utils.setText(xmlUrl, "status", "start"); + } + task = new Task(taskDir + "/" + taskID + ".xml"); + } + Utils.updateDeviceActivity(deviceID); + return task; + } + + @GET + @Path("{taskID}/getbin/{deviceID}") + public Response getBin( + @PathParam("taskID") String taskID, + @PathParam("deviceID") String deviceID) throws Exception { + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + ResponseBuilder response = Response.ok(null); + if (clientDir != null && !clientDir.isEmpty()) { + File bin = Utils.returnFileFrom(clientDir, ".zip"); + System.out.println("TaskService/getBin: Returning " + bin.getPath() + " ..."); + response = Response.ok((Object) bin); + } + Utils.updateDeviceActivity(deviceID); + return response.build(); + } + + @GET + @Path("{taskID}/getbin/{length}/{deviceID}") + public Response getBin( + @PathParam("taskID") String taskID, + @PathParam("length") final Long length, + @PathParam("deviceID") String deviceID) throws Exception { + String result = "Oops!"; + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + final String binUrl = clientDir + "/" + taskID + ".zip"; + Utils.updateDeviceActivity(deviceID); + if (clientDir != null && !clientDir.isEmpty() && new File(binUrl).length() > length) { + if (Utils.deviceExists(deviceID)) { + StreamingOutput stream = new StreamingOutput() { + @Override + public void write(OutputStream os) throws IOException, WebApplicationException { + Utils.returnPart(new RandomAccessFile(new File(binUrl), "r"), os, length); + } + }; + System.out.println("TaskService/getBin: Returning part of " + binUrl + " from " + length + " to " + deviceID + "..."); + return Response.ok("OK").entity(stream).build(); + } else { + return Response.ok("Device not found").build(); + } + } else { + return Response.ok(result).build(); + } + } + + @POST + @Path("{taskID}/putdata/{dataName}/{deviceID}") + public Response putData( + InputStream is, + @PathParam("dataName") String dataName, + @PathParam("taskID") String taskID, + @PathParam("deviceID") String deviceID) throws Exception { + String url = Utils.getDir(app, taskID) + "/client/" + dataName + "@" + deviceID + ".dat"; + System.out.println("TaskService/putData: Writing to " + url); +// +// Utils.writeToFile(data, url); +// +// ObjectInputStream ois = new ObjectInputStream(is); +// List data = (List) ois.readObject(); +// saveDataToFile(data, url); +// + Utils.writeToFile(is, url); + + Utils.updateDeviceActivity(deviceID); + return Response.ok().entity("OK").build(); + } + + @GET + @Path("{taskID}/checkdata/{dataName}_{dataSize}/{deviceID}") + @Produces(MediaType.APPLICATION_JSON) + public Response checkData( + @PathParam("taskID") String taskID, + @PathParam("dataName") String dataName, + @PathParam("dataSize") long dataSize, + @PathParam("deviceID") String deviceID) throws JSONException { + String TAG = getClass().getName() + "@checkData: "; + + JSONObject response = new JSONObject(); + + response.append("response", "oops"); + + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + String serverDir = taskDir + "/server"; + String dataUrl = clientDir + "/" + taskID + ".dat"; + String newDataUrl = clientDir + "/" + dataName + "@" + deviceID + ".dat"; + + System.out.println(TAG + "Checking data " + newDataUrl + " | " + new File(newDataUrl).length() + "/" + dataSize); + + if (Utils.seekFile(newDataUrl)) { + String compareResult = Utils.compareFiles(newDataUrl, dataSize); + if ("equal".equals(compareResult)) { + File file = Utils.returnFileFrom(taskDir, ".xml"); + String fileName = FilenameUtils.removeExtension(file.getName()); + String xmlUrl = taskDir + "/" + fileName + ".xml"; + Utils.setText(xmlUrl, "new", "yes"); + Utils.setText(xmlUrl, "counter", String.valueOf(Integer.valueOf(Utils.getText(xmlUrl, "counter")) + 1)); + addLog(xmlUrl, dataName, deviceID); +// +// mergeData(dataUrl, newDataUrl); +// + + try { + FileInputStream fis = new FileInputStream(newDataUrl); + ObjectInputStream ois = new ObjectInputStream(fis); + List newData = (List) ois.readObject(); + saveDataToFile(newData, dataUrl); + + close(ois); + close(fis); + System.gc(); + + File newDataFile = new File(newDataUrl); + if (newDataFile.delete()) { + System.out.println(TAG + "Deleted " + newDataUrl); + } else { + System.out.println(TAG + "Error deleting " + newDataUrl); + } + } catch (IOException | ClassNotFoundException ex) { + System.out.println(TAG + ex.getMessage()); + } + + /*if (Utils.getText(xmlUrl, "server") != null) { + FileInputStream fis; + ObjectInputStream in; + fis = new FileInputStream(newDataUrl); + in = new ObjectInputStream(fis); + Object object = (Object) in.readObject(); + String serverFileName = Utils.getText(xmlUrl, "server", "name"); + String serverClassName = serverFileName.substring(0, serverFileName.indexOf(".")); + loadClass(serverDir, serverClassName, object); + }/**/ + response.put("response", "OK"); + } else if ("larger".equals(compareResult)) { + response.put("response", "put"); + response.append("checked", String.valueOf(Utils.getFileSize(newDataUrl))); + } else { + new File(newDataUrl).delete(); + } + } + Utils.updateDeviceActivity(deviceID); + + System.out.println(TAG + response.toString()); + + return Response.ok().entity(response.toString()).build(); + } + + @GET + @Path("{taskID}/getprop/{deviceID}") + @Produces(MediaType.APPLICATION_JSON) + public Task getProp( + @PathParam("taskID") String taskID, + @PathParam("deviceID") String deviceID) throws Exception { + String taskDir = Utils.getDir(app, taskID); + String xmlUrl = taskDir + "/" + taskID + ".xml"; + Task task = null; + //System.out.println("TaskService/getProp: Returning task prop with id " + taskID + " ..."); + taskDir = Utils.getDir(app, taskID); + xmlUrl = taskDir + "/" + taskID + ".xml"; + task = new Task(xmlUrl); + Utils.updateDeviceActivity(deviceID); + return task; + } + + /* + * Description: Return the source code of a task. + * Parameters : - The task ID. + * Returns : - The task source code. + * Changelog : - . + */ + @GET + @Path("{taskID}/getsrc/") + @Produces(MediaType.APPLICATION_JSON) + public Object getSrc(@PathParam("taskID") String taskID) { + String TAG = TaskService.class.getName() + "@getSrc: "; + String taskDir = Utils.getDir(app, taskID); + String xmlUrl = taskDir + "/" + taskID + ".xml"; + String taskName = Utils.getText(xmlUrl, "name"); + String srcUrl = taskDir + "/client/" + taskName; + System.out.println(TAG + "Returning task source with id " + taskID + " from " + taskName + "..."); + FileInputStream fis = null; + String src = "/*\n"; + src += " * " + Utils.getText(xmlUrl, "name") + "\n"; + src += " * " + Utils.getText(xmlUrl, "comment") + "\n"; + src += " * " + "assigned id " + Utils.getText(xmlUrl, "id") + "\n"; + src += " * " + "submitted by " + Utils.getText(xmlUrl, "username") + "\n"; + src += " * " + "on " + Utils.getText(xmlUrl, "date") + " at " + Utils.getText(xmlUrl, "time") + "\n"; + src += " */\n\n"; + try { + fis = new FileInputStream(srcUrl); + BufferedInputStream bis = new BufferedInputStream(fis); + DataInputStream dis = new DataInputStream(bis); + while (dis.available() != 0) { + src += (dis.readLine()) + "\n"; + } + close(dis); + close(bis); + close(fis); + + } catch (IOException ex) { + System.out.println(TAG + ex.getMessage()); + } + return src; + } + + /* + * Description: Return the source code of a task. + * Parameters : - The task ID. + * Returns : - The task source code. + * Changelog : - . + */ + @GET + @Path("getlist/") + @Produces(MediaType.TEXT_HTML) + public InputStream getList() { + String TAG = TaskService.class.getName() + "@getList: "; + String html = "

List of submitted Sensing Tasks

"; + try { + Class.forName("com.mysql.jdbc.Driver"); + try (Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password)) { + ResultSet rs; + try (Statement s = c.createStatement()) { + rs = s.executeQuery("SELECT * FROM tasks WHERE ready='YES'"); + html += "
    "; + while (rs.next()) { + String id = rs.getString("id"); + String dir = Utils.getDir(app, id); + String xml = dir + "/" + id + ".xml"; + html += "
  1. " + + Utils.getText(xml, "name") + "" + + ": " + Utils.getText(xml, "comment") + "" + + " submitted by " + Utils.getText(xml, "username") + "" + + " on " + Utils.getText(xml, "date") + " at " + Utils.getText(xml, "time") + + "
  2. "; + } + html += "
"; + } + rs.close(); + c.close(); + } + } catch (ClassNotFoundException | SQLException ex) { + Logger.getLogger(TaskService.class.getName()).log(Level.SEVERE, null, ex); + } + InputStream is = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)); + return is; + } + + /* + * Data + */ + @GET + @Path("{taskID}/getdata") + @Produces(MediaType.MULTIPART_FORM_DATA) + public Object getData(@PathParam("taskID") String taskID) throws Exception { + String TAG = getClass().getName() + "@getData: "; + + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + String dataUrl = clientDir + "/" + taskID + ".dat"; + File data = new File(dataUrl); +// File data = new File(Globals.db_dir + "/data"); + if (data.exists()) { + System.out.println(TAG + "Returning data " + dataUrl); + //data.delete(); + return Response.ok("OK").header("Content-Disposition", "attachment; filename=\"" + taskID + ".dat\"").entity(data).build(); + } else { + System.out.println(TAG + "No data found " + dataUrl); + return Response.ok("OK").header("Content-Disposition", "attachment; filename=\"" + taskID + ".dat\"").entity(null).build(); + } + } + + @GET + @Path("{taskID}/getdataOLD") + @Produces(MediaType.MULTIPART_FORM_DATA) + public Object getDataOLD(@PathParam("taskID") String taskID) throws Exception { + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + String dataUrl = clientDir + "/" + taskID + ".dat"; + final File data = new File(dataUrl); + if (data.exists()) { + String response = FileUtils.readFileToString(data); + //data.delete(); + return Response.ok("OK").header("Content-Disposition", "attachment; filename=\"" + taskID + ".dat\"").entity(response).build(); + } else { + return "Empty."; + } + } + + @GET + @Path("{taskID}/deletedata") + public void deleteData(@PathParam("taskID") String taskID) throws Exception { + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + String dataUrl = clientDir + "/" + taskID + ".dat"; + String xmlUrl = taskDir + "/" + taskID + ".xml"; + System.out.println("TaskService/deleteData: " + "Deleting data " + dataUrl); + File data = new File(dataUrl); + if (data.exists()) { + File dir = new File(clientDir); + for (File f : dir.listFiles()) { + if (f.getName().endsWith(".dat")) { + f.delete(); + } + } + + rmvLog(xmlUrl); + } + } + + @GET + @Path("{taskID}/getdata/delete") + @Produces(MediaType.MULTIPART_FORM_DATA) + public Object downdelData(@PathParam("taskID") String taskID) throws Exception { + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + String dataUrl = clientDir + "/" + taskID + ".dat"; + String xmlUrl = taskDir + "/" + taskID + ".xml"; + final File data = new File(dataUrl); + if (data.exists()) { + String response = FileUtils.readFileToString(data); + data.delete(); + rmvLog(xmlUrl); + return Response.ok("OK").header("Content-Disposition", "attachment; filename=\"" + taskID + ".dat\"").entity(response).build(); + } else { + return Response.serverError().build(); + } + } + + /* + + */ + @GET + @Path("{taskID}/getdata/{dataName}") + @Produces(MediaType.MULTIPART_FORM_DATA) + public Object getData( + @PathParam("taskID") String taskID, + @PathParam("dataName") String dataName) throws Exception { + ResponseBuilder response = Response.ok("ERROR"); + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + String serverDir = taskDir + "/server"; + String dataUrl = clientDir + "/" + dataName; + System.out.println("TaskService/getdata: " + "Returning data " + dataUrl); + File data = new File(dataUrl); + if (data.exists()) { + return data; + } else { + return null; + } + } + + @GET + @Path("{taskID}/getdata/dat.zip") + @Produces(MediaType.MULTIPART_FORM_DATA) + public Object getDataZip(@PathParam("taskID") String taskID) throws Exception { + ResponseBuilder response = Response.ok("ERROR"); + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + System.out.println("TaskService/getdata: " + "Returning all data from " + clientDir); + + byte[] buffer = new byte[1024]; + FileOutputStream fos = new FileOutputStream(clientDir + "/" + "dat.zip"); + ZipOutputStream zos = new ZipOutputStream(fos); + File[] list = new File(clientDir).listFiles(); + for (File file : list) { + if ("dat".equals(FilenameUtils.getExtension(file.getName()))) { + String name = file.getAbsoluteFile().toString().substring(clientDir.length() + 1, file.getAbsoluteFile().toString().length()); + ZipEntry ze = new ZipEntry(name); + zos.putNextEntry(ze); + FileInputStream in = new FileInputStream(clientDir + File.separator + name); + int len; + while ((len = in.read(buffer)) > 0) { + zos.write(buffer, 0, len); + } + close(in); + } + } + close(zos); + close(fos); + return new File(clientDir + "/" + "dat.zip"); + } + + @GET + @Path("{taskID}/deletedata/{dataName}") + public void deleteData( + @PathParam("taskID") String taskID, + @PathParam("dataName") String dataName) throws Exception { + //ResponseBuilder response = Response.ok("ERROR"); + String taskDir = Utils.getDir(app, taskID); + String clientDir = taskDir + "/client"; + String serverDir = taskDir + "/server"; + String dataUrl = clientDir + "/" + dataName; + System.out.println("TaskService/deletedata: " + "Deleting data " + dataUrl); + rmvLog(taskDir + "/" + taskID + ".xml", dataName.substring(0, dataName.indexOf('@'))); + File data = new File(dataUrl); + if (data.exists()) { + data.delete(); + } + } + + private void mergeData(String dataUrl, String newDataUrl) { + FileWriter fw = null; + try { + fw = new FileWriter(new File(dataUrl), true); + fw.write(FileUtils.readFileToString(new File(newDataUrl))); + } catch (IOException ex) { + Logger.getLogger(TaskService.class.getName()).log(Level.SEVERE, null, ex); + } finally { + Utils.close(fw); + } + } + + /* + * Log + */ + private void addLog(String url, String dataName, String deviceID) { + String TAG = getClass().getName() + "@addLog: "; + SAXBuilder builder = new SAXBuilder(); + File xml = new File(url); + try { + Document doc = (Document) builder.build(xml); + Element root = doc.getRootElement().getChild("client").getChild("log"); + Element data = new Element("data"); + root.addContent(data); + + data.setAttribute("id", dataName); + data.addContent(new Element("date").setText(Utils.getDate())); + data.addContent(new Element("time").setText(Utils.getTime())); + data.addContent(new Element("device").setText(deviceID)); + + XMLOutputter xmlOutputter = new XMLOutputter(); + xmlOutputter.setFormat(Format.getPrettyFormat()); + xmlOutputter.output(doc, new FileWriter(url)); + + } catch (JDOMException | IOException ex) { + System.out.println(TAG + ex.getMessage()); + } + + } + + private void rmvLog(String url, String dataName) throws Exception { + SAXBuilder builder = new SAXBuilder(); + File xml = new File(url); + Document doc = (Document) builder.build(xml); + Element root = doc.getRootElement().getChild("client").getChild("log"); + List list = root.getChildren("data"); + for (int i = 0; i < list.size(); i++) { + Element element = (Element) list.get(i); + if (dataName.equals(element.getAttributeValue("id").toString())) { + element.getParent().removeContent(element); + } + } + XMLOutputter xmlOutputter = new XMLOutputter(); + xmlOutputter.setFormat(Format.getPrettyFormat()); + xmlOutputter.output(doc, new FileWriter(url)); + } + + private void rmvLog(String url) throws Exception { + SAXBuilder builder = new SAXBuilder(); + File xml = new File(url); + Document doc = (Document) builder.build(xml); + Element root = doc.getRootElement().getChild("client").getChild("log"); + root.removeContent(); + XMLOutputter xmlOutputter = new XMLOutputter(); + xmlOutputter.setFormat(Format.getPrettyFormat()); + xmlOutputter.output(doc, new FileWriter(url)); + } + + /* + * Data + */ + boolean saveDataToFile(List data, String url) { + String TAG = getClass().getName() + "@saveData: "; + + try { + System.out.println(TAG + "Saving data to " + url); + List oldData = getDataFromFile(url); + if (!oldData.isEmpty()) { + oldData.addAll(data); + data = oldData; + } + FileOutputStream fos = new FileOutputStream(url); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(data); + close(oos); + close(fos); + System.gc(); + } catch (Exception ex) { + System.out.println(TAG + ex.getMessage()); + return false; + } + System.out.println(TAG + "OK"); + return true; + } + + List getDataFromFile(String url) { + String TAG = getClass().getName() + "@getDataFromFile: "; + + FileInputStream fis; + ObjectInputStream ois; + + List data = new ArrayList<>(); + + try { + System.out.println(TAG + "Returning data from " + url); + if (new File(url).exists()) { + fis = new FileInputStream(url); + ois = new ObjectInputStream(fis); + data = (List) ois.readObject(); + close(ois); + close(fis); + } else { + System.out.println(TAG + "File does not exist"); + } + } catch (IOException | ClassNotFoundException ex) { + System.out.println(TAG + ex.getMessage()); + } + System.out.println(TAG + "OK"); + return data; + } + + /* + * Misc + */ + private void loadClass(String dir, String className, Object object) throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, NoClassDefFoundError, IllegalArgumentException, InvocationTargetException { + URL url = new File(dir).toURI().toURL(); + ClassLoader cl = new URLClassLoader(new URL[]{url}, getClass().getClassLoader()); + Class clss = cl.loadClass(className); + Object instance = clss.newInstance(); + Method method = clss.getMethod("main", new Class[]{Object.class + } + ); + method.invoke(instance, new Object[]{object}); + } + + private String getReadyTask() throws ClassNotFoundException, SQLException { + String id = ""; + Class.forName("com.mysql.jdbc.Driver"); + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement(); + /*rs = s.executeQuery("SELECT * FROM tasks WHERE compiled='YES' AND downloaded=0"); + if (rs.next()) { + id = rs.getString("id"); + }/**/ + ResultSet rs = s.executeQuery("SELECT * FROM tasks WHERE ready='YES'"); + int min; + if (rs.next()) { + min = rs.getInt("downloaded"); + id = rs.getString("id"); + while (rs.next()) { + if (rs.getInt("downloaded") < min) { + min = rs.getInt("downloaded"); + id = rs.getString("id"); + } + } + } + rs.close(); + s.close(); + c.close(); + return id; + } + + private void updateDownloaded(String id) throws Exception { + Class.forName("com.mysql.jdbc.Driver"); + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement(); + s.executeUpdate("UPDATE tasks SET downloaded=downloaded+1 WHERE id='" + id + "'"); + s = c.createStatement(); + ResultSet rs = s.executeQuery("SELECT * FROM tasks WHERE id='" + id + "'"); + rs.next(); + Utils.setText(Utils.getDir(app, id) + "/" + id + ".xml", "client", "downloaded", "counter", rs.getString("downloaded")); + rs.close(); + s.close(); + c.close(); + + } + + public static void close(Closeable resource) { + if (resource != null) { + try { + resource.close(); + } catch (IOException ignore) { + } + } + } +} diff --git a/src/main/java/com/www/server/Upload.java b/src/main/java/com/www/server/Upload.java new file mode 100644 index 0000000..8a81dff --- /dev/null +++ b/src/main/java/com/www/server/Upload.java @@ -0,0 +1,425 @@ +package com.www.server; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.io.FilenameUtils; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; + +public class Upload extends HttpServlet { + + private String CONSOLE_CMD, DB_DIR, SERVER_URL, LIB_URL, JAVAC_CMD, DX_CMD, DB_SERVER, DB_USERNAME, DB_PASSWORD; + private String userName; + private String errorMessage = ""; + private boolean hasFileClient = false; + private boolean isCompiledClient = false; + private boolean hasFileServer = false; + private boolean hasLibServer = false; + private boolean isCompiledServer = false; + Boolean fileCompiled = false; + private String fileId, fileComment, fileDate, fileTime, userDir, fileDir, + dirClient, fileUrlClient, fileNameClient, fileSizeClient, fileSizeZipClient, fileCompileClient, fileTimeClient, fileDateClient, + dirServer, fileUrlServer, fileNameServer, fileSizeServer, fileCompileServer, fileTimeServer, fileDateServer, + zipFileNameServer, libUrlServer, libNameServer, libSizeServer; + private FileItem fileContentClient, fileContentServer, libContentServer; + private String timeCheckbox, timeFrom, timeTo; + private String mapCheckbox, sw_lat, sw_lng, ne_lat, ne_lng; + private String libCheckboxServer; + + @Override + public void init() { + SERVER_URL = Globals.server_url; + DB_DIR = Globals.db_dir; + CONSOLE_CMD = Globals.console_cmd; + LIB_URL = Globals.lib_url; + JAVAC_CMD = Globals.javac_cmd; + DX_CMD = Globals.dx_cmd; + DB_USERNAME = Globals.db_username; + DB_PASSWORD = Globals.db_password; + DB_SERVER = Globals.db_server; + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileNotFoundException { + HttpSession session = request.getSession(true); + userName = (String) session.getAttribute("username"); + try { + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + for (FileItem item : items) { + String fieldName = item.getFieldName(); + if (item.isFormField()) { + String fieldValue = item.getString(); + if ("upload_comment_value".equals(fieldName)) { + fileComment = "(no comment)"; + if (!Utils.stringIsEmpty(fieldValue)) { + fileComment = item.getString(); + } + } + if ("upload_time_checkbox".equals(fieldName)) { + timeCheckbox = fieldValue; + } + if ("on".equals(timeCheckbox)) { + if ("upload_time_selection_from".equals(fieldName)) { + timeFrom = fieldValue; + } + if ("upload_time_selection_to".equals(fieldName)) { + timeTo = fieldValue; + } + } + if ("upload_map_checkbox".equals(fieldName)) { + mapCheckbox = fieldValue; + } + if ("on".equals(mapCheckbox)) { + if ("upload_map_sw_lat".equals(fieldName)) { + sw_lat = fieldValue; + } + if ("upload_map_sw_lng".equals(fieldName)) { + sw_lng = fieldValue; + } + if ("upload_map_ne_lat".equals(fieldName)) { + ne_lat = fieldValue; + } + if ("upload_map_ne_lng".equals(fieldName)) { + ne_lng = fieldValue; + } + } + //if ("upload_lib_server_checkbox".equals(fieldName)) { + //libCheckboxServer = fieldValue; + //} + } else { + String fileName = FilenameUtils.getName(item.getName()); + FileItem file = item; + if ("upload_code_client_value".equals(fieldName)) { + if (Utils.stringIsEmpty(fileName)) { + errorMessage += "No client part file chosen
"; + } else { + if (fileName.substring(fileName.lastIndexOf(".") + 1).equalsIgnoreCase("java")) { + hasFileClient = true; + fileNameClient = fileName; + fileContentClient = file; + } else { + errorMessage += "Client part must be a .java file
"; + } + } + } else if ("upload_code_server_value".equals(fieldName) && !Utils.stringIsEmpty(fileName)) { + if (fileName.substring(fileName.lastIndexOf(".") + 1).equalsIgnoreCase("zip")) { + hasFileServer = true; + zipFileNameServer = fileName; + fileContentServer = file; + } else { + errorMessage += "Server part must be a .zip file
"; + } + } + //if ("upload_lib_server_value".equals(fieldName) && fileServer && "on".equals(libCheckboxServer)) { + //if (fileName.substring(fileName.lastIndexOf(".") + 1).equalsIgnoreCase("jar")) { + //libServer = true; + //libNameServer = fileName; + //libContentServer = file; + //} else { + //errorMessage += "Server library must be a .jar file
"; + //} + //} + } + } + } catch (FileUploadException e) { + throw new ServletException("Cannot parse multipart request.", e); + }/**/ + + if (!Utils.stringIsEmpty(errorMessage)) { + request.setAttribute("errorMessage", errorMessage); + errorMessage = ""; + destroyFile(); + request.getRequestDispatcher("main/upload.jsp").forward(request, response); + } else { + try { + fileId = String.valueOf(getNewTaskId()); + insertTask(fileId, fileNameClient, userName); + initFile(); + + fileSizeClient = Utils.writeToFile(fileContentClient, fileUrlClient); + fileCompileClient = Utils.compileAndroidFile(dirClient, fileNameClient); + fileCompileClient += "\n" + Utils.compileDex(dirClient, fileNameClient); + fileDateClient = Utils.getDate(); + fileTimeClient = Utils.getTime(); + + if (hasFileServer) { + Utils.writeToFile(fileContentServer, dirServer + "/" + zipFileNameServer); + fileDateServer = Utils.getDate(); + fileTimeServer = Utils.getTime(); + //if (libServer) { + //libSizeServer = writeToFile(libContentServer, libUrlServer); + //fileCompileServer = compileFile(dirServer, fileNameServer, libNameServer); + //} else { + Utils.unZip(dirServer, zipFileNameServer); + fileNameServer = Utils.returnFileFrom(dirServer, ".java").getName(); + if (Utils.returnFileFrom(dirServer, ".jar") != null) { + hasLibServer = true; + } + fileCompileServer = Utils.compileFile(dirServer, fileNameServer); + } + + composeXml(); + + if (isCompiledClient) { + fileSizeZipClient = Utils.zipDex(dirClient, fileId); + Utils.setText(fileDir + "/" + fileId + ".xml", "client", "zip_size", fileSizeZipClient); + } + if (fileCompiled) { + Utils.updateReady("tasks", fileId, "YES"); + } + + } catch (ClassNotFoundException | SQLException | IOException | InterruptedException | JDOMException ex) { + Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); + } + systemOut(); + destroyFile(); + response.sendRedirect(response.encodeRedirectURL("/Server/main/view.jsp?id=" + fileId)); + }/**/ + + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { + response.sendRedirect(response.encodeRedirectURL("/Server/main/upload.jsp")); + } + + private void systemOut() { + System.out.println( + "\n/********** Upload **********/\n" + + "\nUser: " + userName + + "\nComment: " + fileComment + + "\nId: " + fileId + + "\nDate: " + fileDate + + "\nTime: " + fileTime + ); + if (hasFileClient) { + System.out.println( + "\nClient: " + fileNameClient + + "\n Size: " + fileSizeClient + + "\n Time: " + timeCheckbox + ); + if ("on".equals(timeCheckbox)) { + System.out.println( + " From: " + timeFrom + + "\n To: " + timeTo + ); + } + System.out.println(" Location: " + mapCheckbox); + if ("on".equals(mapCheckbox)) { + System.out.println( + " sw_lat: " + sw_lat + + "\n sw_lng: " + sw_lng + + "\n ne_lat: " + ne_lat + + "\n ne_lng: " + ne_lng + ); + } + } + if (hasFileServer) { + System.out.println( + "\nServer: " + fileNameServer + + "\n Size: " + fileSizeServer + ); + if (hasLibServer) { + System.out.println(" Library: " + libNameServer); + } + } + System.out.println("\n/****************************/\n"); + } + + private void insertTask(String fileId, String fileName, String userName) throws ClassNotFoundException, SQLException { + Class.forName("com.mysql.jdbc.Driver"); + Connection c = DriverManager.getConnection(DB_SERVER, DB_USERNAME, DB_PASSWORD); + Statement s = c.createStatement(); + String sql = "INSERT INTO tasks (`id`, `filename`, `username`, `ready`, `downloaded`) VALUES ('" + + fileId + "', '" + fileName + "', '" + userName + "', '" + "NO" + "', '" + "0" + "')"; + s.executeUpdate(sql); + s.close(); + c.close(); + } + + private int getNewTaskId() throws ClassNotFoundException, SQLException { + Class.forName("com.mysql.jdbc.Driver"); + Connection c = DriverManager.getConnection(DB_SERVER, DB_USERNAME, DB_PASSWORD); + Statement s; + s = c.createStatement(); + s.executeQuery("SELECT COUNT(*) FROM tasks"); + ResultSet rs = s.getResultSet(); + rs.next(); + int id = rs.getInt(1); + rs.close(); + s.close(); + c.close(); + return ++id; + } + + private void initFile() throws ClassNotFoundException, SQLException { + fileDate = Utils.getDate(); + fileTime = Utils.getTime(); + userDir = DB_DIR + "/" + userName; + fileDir = userDir + "/sensing/" + fileId; + new File(fileDir).mkdir(); + dirClient = fileDir + "/client"; + fileUrlClient = dirClient + "/" + fileNameClient; + new File(dirClient).mkdir(); + if (hasFileServer) { + dirServer = fileDir + "/server"; + new File(dirServer).mkdir(); + //fileUrlServer = dirServer + "/" + fileNameServer; + //if (libServer) { + //libUrlServer = dirServer + "/" + libNameServer; + //} + } + } + + private void destroyFile() { + hasFileServer = false; + fileNameServer = ""; + fileContentServer = null; + + hasLibServer = false; + libNameServer = ""; + libContentServer = null; + + isCompiledServer = false; + + hasFileClient = false; + fileNameClient = ""; + fileContentClient = null; + isCompiledClient = false; + + fileCompiled = false; + } + + private void composeXml() { + try { + Element root = new Element("file"); + Document doc = new Document(root); + doc.setRootElement(root); + root.addContent(new Element("username").setText(userName)); + root.addContent(new Element("name").setText(fileNameClient)); + root.addContent(new Element("id").setText(fileId)); + root.addContent(new Element("comment").setText(fileComment)); + root.addContent(new Element("date").setText(fileDate)); + root.addContent(new Element("time").setText(fileTime)); + root.addContent(new Element("status").setText("")); + root.addContent(new Element("new").setText("no")); + root.addContent(new Element("counter").setText("0")); + + Element client = new Element("client"); + root.addContent(client); + client.addContent(new Element("name").setText(fileNameClient)); + client.addContent(new Element("size").setText(fileSizeClient)); + client.addContent(new Element("zip_size").setText("0")); + + Element downloaded = new Element("downloaded"); + client.addContent(downloaded); + downloaded.addContent(new Element("counter").setText("0")); + downloaded.addContent(new Element("devices").setText("")); + + Element time = new Element("time"); + client.addContent(time); + time.addContent(new Element("status").setText(timeCheckbox)); + if ("on".equals(timeCheckbox)) { + time.addContent(new Element("from").setText(timeFrom)); + time.addContent(new Element("to").setText(timeTo)); + } + + Element map = new Element("map"); + client.addContent(map); + map.addContent(new Element("status").setText(mapCheckbox)); + if ("on".equals(mapCheckbox)) { + map.addContent(new Element("sw_lat").setText(sw_lat)); + map.addContent(new Element("sw_lng").setText(sw_lng)); + map.addContent(new Element("ne_lat").setText(ne_lat)); + map.addContent(new Element("ne_lng").setText(ne_lng)); + } + Element compileClient = new Element("compile"); + client.addContent(compileClient); + if (Utils.stringIsEmpty(fileCompileClient)) { + compileClient.addContent(new Element("status").setText("true")); + isCompiledClient = true; + fileCompiled = true; + } else { + compileClient.addContent(new Element("status").setText("false")); + isCompiledClient = false; + fileCompiled = false; + } + compileClient.addContent(new Element("date").setText(fileDateClient)); + compileClient.addContent(new Element("time").setText(fileTimeClient)); + compileClient.addContent(new Element("output").setText(fileCompileClient)); + client.addContent(new Element("log")); + + if (hasFileServer) { + Element server = new Element("server"); + root.addContent(server); + server.addContent(new Element("name").setText(fileNameServer)); + server.addContent(new Element("size").setText(fileSizeServer)); + if (hasLibServer) { + Element libs = new Element("libraries"); + server.addContent(libs); + + File folder = new File(dirServer); + String fileName; + File file = null; + File[] listOfFiles = folder.listFiles(); + for (int i = 0; i < listOfFiles.length; i++) { + if (listOfFiles[i].isFile()) { + fileName = listOfFiles[i].getName(); + if (fileName.endsWith(".jar")) { + file = new File(dirServer + "/" + fileName); + Element lib = new Element("library"); + libs.addContent(lib); + lib.addContent(new Element("name").setText(file.getName())); + lib.addContent(new Element("size").setText(Long.toString(file.length()))); + } + } + } + + } + Element compileServer = new Element("compile"); + server.addContent(compileServer); + if (Utils.stringIsEmpty(fileCompileServer)) { + compileServer.addContent(new Element("status").setText("true")); + isCompiledServer = true; + } else { + compileServer.addContent(new Element("status").setText("false")); + isCompiledServer = false; + fileCompiled = false; + } + compileServer.addContent(new Element("date").setText(fileDateServer)); + compileServer.addContent(new Element("time").setText(fileTimeServer)); + compileServer.addContent(new Element("output").setText(fileCompileServer)); + } + + XMLOutputter xmlOutputter = new XMLOutputter(); + xmlOutputter.setFormat(Format.getPrettyFormat()); + xmlOutputter.output(doc, new FileWriter(fileDir + "/" + fileId + ".xml")); + } catch (IOException ex) { + Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); + } + } +} diff --git a/src/main/java/com/www/server/UserService.java b/src/main/java/com/www/server/UserService.java new file mode 100644 index 0000000..5aae4c5 --- /dev/null +++ b/src/main/java/com/www/server/UserService.java @@ -0,0 +1,76 @@ +package com.www.server; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +@Path("/user") +public class UserService { + + String DEVICES_INFO = "jdbc:mysql://localhost:3306/devices_info"; + String USERNAME = Globals.db_username; + String PASSWORD = Globals.db_password; + + @Context + UriInfo uriInfo; + + @Context + Request request; + + @GET + @Produces(MediaType.TEXT_PLAIN) + public String respondAsReady() { + return "User service is ready."; + } + + @GET + @Path("register_device/{username}_{model}_{os}") + public Response registerDevice(@PathParam("username") String username, @PathParam("model") String model, @PathParam("os") String os) throws ClassNotFoundException, SQLException { + int id = getNewId(); + registerNewDevice(id, username, model, os); + return Response.ok().entity(String.valueOf(id)).build(); + } + + private int getNewId() throws ClassNotFoundException, SQLException { + String driver = "com.mysql.jdbc.Driver"; + Class.forName(driver); + Connection conn = DriverManager.getConnection(DEVICES_INFO, USERNAME, PASSWORD); + ResultSet rs; + Statement s = conn.createStatement(); + String sql = "SELECT id FROM counter"; + rs = s.executeQuery(sql); + rs.next(); + int id = Integer.parseInt(rs.getString("id")); + s.executeUpdate("UPDATE counter SET id = (id + 1)"); + s.close(); + rs.close(); + conn.close(); + return id; + } + + private void registerNewDevice(int id, String username, String model, String os) throws ClassNotFoundException, SQLException { + System.out.println("id: " + id); + System.out.println("username: " + username); + System.out.println("model: " + model); + System.out.println("os: " + os); + String driver = "com.mysql.jdbc.Driver"; + Class.forName(driver); + Connection conn = DriverManager.getConnection(DEVICES_INFO, USERNAME, PASSWORD); + Statement s = conn.createStatement(); + String sql = "INSERT INTO devices_info.devices (`id`, `username`, `model`, `os`) VALUES ('" + id + "', '" + username + "', '" + model + "', '" + os + "')"; + s.executeUpdate(sql); + s.close(); + conn.close(); + } +} diff --git a/src/main/java/com/www/server/Utils.java b/src/main/java/com/www/server/Utils.java new file mode 100644 index 0000000..93d2e6d --- /dev/null +++ b/src/main/java/com/www/server/Utils.java @@ -0,0 +1,806 @@ +package com.www.server; + +import java.io.BufferedReader; +import java.io.Closeable; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.io.FilenameUtils; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.input.SAXBuilder; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; + +public class Utils { + + /* XML utilities */ + /* + * Description: Return from the url xml file the content of node. + * Parameters : - . + * Returns : - . + * Changelog : 150523 - Added console output. + */ + public static String getText(String url, String node) { + if (Globals.DBG) { + System.out.println("Utils.getText1: " + url + " " + node); + } + String text = ""; + SAXBuilder builder = new SAXBuilder(); + File xmlFile = new File(url); + try { + Document document = (Document) builder.build(xmlFile); + Element root = document.getRootElement(); + text = root.getChildText(node); + } catch (JDOMException | IOException e) { + if (Globals.DBG) { + System.out.println("Utils.getText1: " + e.getMessage()); + } + return text; + } + if (Globals.DBG) { + System.out.println("Utils.getText1: " + text); + } + return text; + } + + public static String getText(String url, String node1, String node2) { + if (Globals.DBG) { + System.out.println("Utils.getText2: " + url + " " + node1 + " > " + node2); + } + String text = ""; + SAXBuilder builder = new SAXBuilder(); + File xmlFile = new File(url); + try { + Document document = (Document) builder.build(xmlFile); + Element root = document.getRootElement(); + Element child = root.getChild(node1); + text = child.getChildText(node2); + } catch (JDOMException | IOException e) { + if (Globals.DBG) { + System.out.println("Utils.getText2: " + e.getMessage()); + } + return " "; + } + if (Globals.DBG) { + System.out.println("Utils.getText2: " + text); + } + return text; + } + + public static String getText(String url, String node1, String node2, String node3) { + if (Globals.DBG) { + System.out.println("Utils.getText3: " + url + " " + node1 + " > " + node2 + " > " + node3); + } + String text = ""; + SAXBuilder builder = new SAXBuilder(); + File xmlFile = new File(url); + try { + Document document = (Document) builder.build(xmlFile); + Element root = document.getRootElement(); + Element child1 = root.getChild(node1); + Element child2 = child1.getChild(node2); + text = child2.getChildText(node3); + } catch (JDOMException | IOException e) { + if (Globals.DBG) { + System.out.println("Utils.getText3: " + e.getMessage()); + } + return text; + } + if (Globals.DBG) { + System.out.println("Utils.getText3: " + text); + } + return text; + } + + /* + * Description: Set in url xml file the content of node to string. + * Parameters : - . + * Returns : - . + * Changelog : 150523 - Commented out errors and added console output. + */ + public static void setText(String url, String node, String string) { + if (Globals.DBG) { + System.out.println("Utils.setText1: " + url + " " + node + " > " + string); + } + SAXBuilder builder = new SAXBuilder(); + File xmlFile = new File(url); + try { + Document document = (Document) builder.build(xmlFile); + Element root = document.getRootElement(); + root.getChild(node).setText(string); + XMLOutputter xmlOutputter = new XMLOutputter(); + xmlOutputter.setFormat(Format.getPrettyFormat()); + xmlOutputter.output(document, new FileWriter(url)); + } catch (JDOMException | IOException e) { + if (Globals.DBG) { + System.out.println("Utils.setText1: " + e.getMessage()); + } + } + } + + public static void setText(String url, String child1, String child2, String string) { + if (Globals.DBG) { + System.out.println("Utils.setText2: " + url + " " + child1 + " > " + child2 + " > " + string); + } + SAXBuilder builder = new SAXBuilder(); + File xmlFile = new File(url); + try { + Document document = (Document) builder.build(xmlFile); + Element root = document.getRootElement(); + Element node1 = root.getChild(child1); + Element node2 = node1.getChild(child2); + node2.setText(string); + XMLOutputter xmlOutputter = new XMLOutputter(); + xmlOutputter.setFormat(Format.getPrettyFormat()); + xmlOutputter.output(document, new FileWriter(url)); + } catch (JDOMException | IOException e) { + if (Globals.DBG) { + System.out.println("Utils.setText2: " + e.getMessage()); + } + } + } + + public static void setText(String url, String child1, String child2, String child3, String string) { + if (Globals.DBG) { + System.out.println("Utils.setText3: " + url + " " + child1 + " > " + child2 + " > " + child3 + " > " + string); + } + SAXBuilder builder = new SAXBuilder(); + File xmlFile = new File(url); + try { + Document document = (Document) builder.build(xmlFile); + Element root = document.getRootElement(); + Element node1 = root.getChild(child1); + Element node2 = node1.getChild(child2); + Element node3 = node2.getChild(child3); + node3.setText(string); + XMLOutputter xmlOutputter = new XMLOutputter(); + xmlOutputter.setFormat(Format.getPrettyFormat()); + xmlOutputter.output(document, new FileWriter(url)); + } catch (JDOMException | IOException e) { + if (Globals.DBG) { + System.out.println("Utils.setText3: " + e.getMessage()); + } + } + } + + public static void addText(String url, String node1, String node2, String string) throws JDOMException, IOException { + SAXBuilder builder = new SAXBuilder(); + File xmlFile = new File(url); + Document document = (Document) builder.build(xmlFile); + Element root = document.getRootElement(); + root.getChild(node1).getChild(node2).addContent(string); + XMLOutputter xmlOutputter = new XMLOutputter(); + xmlOutputter.setFormat(Format.getPrettyFormat()); + xmlOutputter.output(document, new FileWriter(url)); + } + + public static List getNodeList(String url, String element1, String element2, String label) throws JDOMException, IOException { + SAXBuilder builder = new SAXBuilder(); + File xml = new File(url); + Document doc = (Document) builder.build(xml); + Element root = doc.getRootElement().getChild(element1).getChild(element2); + return root.getChildren(label); + } + + public static void appendNode(String url, String node, String child, String label, String text) throws JDOMException, IOException { + + } + /* */ + + /* Misc utilities */ + public static String getTime() { + Calendar calen = Calendar.getInstance(); + DateFormat df = new SimpleDateFormat("HH:mm:ss"); + return df.format(calen.getTime()); + } + + public static String getTime(String format) { + Calendar calen = Calendar.getInstance(); + DateFormat df = new SimpleDateFormat(format); + return df.format(calen.getTime()); + } + + public static String getDate() { + Calendar calen = Calendar.getInstance(); + DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); + return df.format(calen.getTime()); + } + + public static Boolean isDateRecent(String date, int months, int days, int years) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); + Calendar calPrev = Calendar.getInstance(); + Date datePrev = sdf.parse(date); + calPrev.setTime(datePrev); + Calendar calCurr = Calendar.getInstance(); + Date dateCurr = sdf.parse(sdf.format(calCurr.getTime())); + calCurr.setTime(dateCurr); + calCurr.add(Calendar.MONTH, -months); + calCurr.add(Calendar.DAY_OF_MONTH, -days); + calCurr.add(Calendar.YEAR, -years); + /*System.out.println("calCurr: " + calCurr.getTime()); + System.out.println("calPrev: " + calPrev.getTime()); + System.out.println("calPrev after calCurr: " + calPrev.after(calCurr));/**/ + return calPrev.after(calCurr); + } + + public static Boolean isTimeRecent(String time, int hours, int minutes, int seconds) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); + Calendar calPrev = Calendar.getInstance(); + Date datePrev = sdf.parse(time); + calPrev.setTime(datePrev); + Calendar calCurr = Calendar.getInstance(); + Date dateCurr = sdf.parse(sdf.format(calCurr.getTime())); + calCurr.setTime(dateCurr); + calCurr.add(Calendar.HOUR, -hours); + calCurr.add(Calendar.MINUTE, -minutes); + calCurr.add(Calendar.SECOND, -seconds); + /*System.out.println("calCurr: " + sdf.format(calCurr.getTime())); + System.out.println("calPrev: " + sdf.format(calPrev.getTime())); + System.out.println("calPrev after calCurr: " + calPrev.after(calCurr));/**/ + return calPrev.after(calCurr); + } + + public static Boolean stringIsEmpty(String string) { + if (string == null) { + return true; + } else if (string.isEmpty()) { + return true; + } else if ("".equals(string)) { + return true; + } else if (string.trim().length() <= 0) { + return true; + } else { + return false; + } + } + + /* + * Description: Checks if a device is registered. + * Parameters : - The device id to be checked. + * Returns : - false/ture accordingly. + * Changelog : - . + */ + public static Boolean deviceExists(String id) { + Boolean exists = false; + try { + Class.forName("com.mysql.jdbc.Driver"); + try (Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement()) { + s.executeQuery("SELECT * FROM devices WHERE id='" + id + "'"); + try (ResultSet rs = s.getResultSet()) { + if (rs.next()) { + exists = true; + } + } + } + } catch (ClassNotFoundException | SQLException ex) { + Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); + } + return exists; + } + + public static String getDeviceInfo(String id, String request) { + String TAG = "Utils@getDeviceInfo: "; + + String info = "Oops!"; + String connectionURL = "jdbc:mysql://localhost:3306/server"; + try { + Class.forName("com.mysql.jdbc.Driver"); + } catch (ClassNotFoundException ex) { + Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); + } + Connection connection; + try { + connection = DriverManager.getConnection(connectionURL, Globals.db_username, Globals.db_password); + ResultSet rs; + Statement s = connection.createStatement(); + String sql = "SELECT " + request + " FROM devices WHERE id='" + id + "'"; + rs = s.executeQuery(sql); + if (rs.next()) { +// System.out.println(TAG + rs.toString()); + info = rs.getString(request); + } + rs.close(); + + s.close(); + connection.close(); + } catch (SQLException ex) { + System.out.println(TAG + ex.getMessage()); + } + return info; + } + + public static void updateDeviceActivity(String id) { + String TAG = "Utils@updateDeviceActivity: "; + String date = Utils.getDate(); + String time = Utils.getTime(); + String driver = "com.mysql.jdbc.Driver"; + try { + Class.forName(driver); + try ( + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement()) { + s.executeUpdate("UPDATE devices SET last_date='" + date + "', last_time='" + time + "' WHERE id='" + id + "'"); + } + } catch (ClassNotFoundException | SQLException ex) { + System.out.println(TAG + ex.getMessage()); + } + /**/ + + /**/ + } + + /* */ + + /* File utilities */ + /* + * Description: Saves a file item to a selected destination. + * Parameters : - The file item. + * - The url to save the file. + * Returns : - The size of the file. + * Changelog : 150523 - Commented out errors and added console output. + */ + public static String writeToFile(FileItem fi, String url) { + File file = new File(url); + try { + fi.write(file); + } catch (Exception ex) { + System.out.println(Utils.class.getName() + "@writeToFile:" + ex.getMessage()); + } + long size = file.length(); + return Long.toString(size); + } + + public static void writeToNewFile(InputStream input, String url) throws IOException { + OutputStream output = new FileOutputStream(new File(url)); + int read; + byte[] buffer = new byte[1024]; + while ((read = input.read(buffer)) > 0) { + output.write(buffer, 0, read); + } + close(output); + close(input); + } + + public static void writeToFile(InputStream input, String url) { + File file = new File(url); + long seek = file.length(); + RandomAccessFile output = null; + try { + output = new RandomAccessFile(file, "rw"); + output.seek(seek); + int read; + byte[] buffer = new byte[1024]; + while ((read = input.read(buffer)) > 0) { + output.write(buffer, 0, read); + } + } catch (Exception ex) { + //Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); + } + close(input); + close(output); + } + + public static File returnFileFrom(String url, String type) { + File folder = new File(url); + String fileName; + File file = null; + File[] listOfFiles = folder.listFiles(); + for (File listOfFile : listOfFiles) { + if (listOfFile.isFile()) { + fileName = listOfFile.getName(); + if (fileName.endsWith(type)) { + file = new File(url + "/" + fileName); + break; + } + } + } + return file; + } + + /* + * Description: Return the directory of the task id. + * Parameters : - sensing/privacy. + * - The file id. + * Returns : - The file url. + * Changelog : 150529 - Rename from getFileDir to getTaskDir and remove + * throws clauses. + * 150608 - Add privacy support. + */ + public static String getDir(String app, String id) { + String url = "Oops!"; + String table = ""; + if ("sensing".equals(app)) { + table = "tasks"; + } else if ("privacy".equals(app)) { + table = "pms"; + } else { + return "Oops!"; + } + try { + Class.forName("com.mysql.jdbc.Driver"); + try (Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password)) { + ResultSet rs; + try (Statement s = c.createStatement()) { + rs = s.executeQuery("SELECT * FROM " + table + " WHERE id='" + id + "'"); + if (rs.next()) { + url = Globals.db_dir + "/" + rs.getString("username") + "/" + app + "/" + id; + } + } + rs.close(); + } + } catch (ClassNotFoundException | SQLException e) { + System.out.println("Utils.getTaskDir: " + e.getMessage()); + } + if (Globals.DBG) { + System.out.println("Utils.getTaskDir: " + url); + } + return url; + } + + public static boolean seekFile(String url) { + File file = new File(url); + if (file.exists()) { + return true; + } else { + return false; + } + } + + public static long getFileSize(String url) { + File file = new File(url); + if (file.exists()) { + return file.length(); + } else { + return 0; + } + } + + public static String compareFiles(String url, Long size) { + String response = "Oops!"; + File file = new File(url); + if (size == file.length()) { + response = "equal"; + } else if (size < file.length()) { + response = "smaller"; + } else if (size > file.length()) { + response = "larger"; + } + return response; + } + + public static File returnPart(String deviceID, String url, long start) throws IOException { + File file = new File(url); + OutputStream output = new FileOutputStream(url + "@" + deviceID + ".tmp"); + int read; + byte[] buffer = new byte[1024]; + RandomAccessFile input; + input = new RandomAccessFile(file, "r"); + input.seek(start); + while ((read = input.read(buffer)) > 0) { + output.write(buffer, 0, read); + } + close(output); + close(input); + File part = new File(url + "@" + deviceID + ".tmp"); + return part; + } + + public static void copyFileOLD(RandomAccessFile input, OutputStream output, long start, long length) throws IOException { + byte[] buffer = new byte[1024]; + int read; + if (input.length() == length) { + while ((read = input.read(buffer)) > 0) { + output.write(buffer, 0, read); + } + } else { + input.seek(start); + long toRead = length; + while ((read = input.read(buffer)) > 0) { + if ((toRead -= read) > 0) { + output.write(buffer, 0, read); + } else { + output.write(buffer, 0, (int) toRead + read); + break; + } + } + } + } + + public static void returnPart(RandomAccessFile input, OutputStream output, long start) throws IOException { + int read; + byte[] buffer = new byte[1024]; + input.seek(start); + while ((read = input.read(buffer)) > 0) { + output.write(buffer, 0, read); + } + close(output); + close(input); + } + + public static void close(Closeable resource) { + if (resource != null) { + try { + resource.close(); + } catch (IOException ignore) { + } + } + } + /* */ + + /* Compilation utilities */ + public static String compileFile(String dir, String fileName) throws IOException, InterruptedException, JDOMException, ClassNotFoundException, SQLException { + String result = ""; + String javac_cmd = "\"" + Globals.javac_cmd + "\"" + " -cp " + dir + "/\\* " + dir + "/" + fileName; + System.out.println("Utils.compileFile: " + javac_cmd); + + Process p = Runtime.getRuntime().exec(Globals.console_cmd); + OutputStream os = p.getOutputStream(); + os.write((javac_cmd + "\n").getBytes()); + os.flush(); + os.close(); + p.waitFor(); + BufferedReader bf = new BufferedReader(new InputStreamReader(p.getErrorStream())); + String line = bf.readLine(); + while (line != null) { + result = result + line + "\n"; + line = bf.readLine(); + } + close(bf); + close(os); + + return result; + } + + public static boolean findMethod(String method, File file) { + Pattern p = Pattern.compile("\\b" + method + "\\b"); + BufferedReader bf = null; + try { + bf = new BufferedReader(new FileReader(file.getPath())); + String line = ""; + while ((line = bf.readLine()) != null) { + Matcher m = p.matcher(line); + if (m.find()) { + return true; + } + } + } catch (Exception ex) { + Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); + } + return false; + } + + /* + * Description: Compiles the source code of the sensing task. + * Parameters : - The source code file. + * Returns : - The compilation log. + * Changelog : 150523 - Paths with spaces and console output. + * 150607 - Remove throws clauses. + */ + public static String compileAndroidFile(String dir, String fileName) { + String result = ""; + try { + String javac_cmd = "\"" + Globals.javac_cmd + "\"" + " -cp " + "\"" + Globals.lib_url + "\"" + " " + "\"" + dir + "/" + fileName + "\""; + System.out.println("Utils.compileAndroidFile: " + javac_cmd); + + Process p = Runtime.getRuntime().exec(Globals.console_cmd); + OutputStream os = p.getOutputStream(); + os.write((javac_cmd + "\n").getBytes()); + close(os); + p.waitFor(); + BufferedReader bf = new BufferedReader(new InputStreamReader(p.getErrorStream())); + String line = bf.readLine(); + while (line != null) { + result = result + line + "\n"; + line = bf.readLine(); + } + close(bf); + if (!findMethod("public void onStart", new File(dir + "/" + fileName))) { + result += "'public void onStart(Context, ObjectInputStream)' method not found.\n"; + System.out.println("'public void onStart (Context, ObjectInputStream)' method not found."); + } + if (!findMethod("public void onStop", new File(dir + "/" + fileName))) { + result += "'public void onStop()' method not found.\n"; + System.out.println("'public void onStop()' method not found."); + } + + /* + if (!findMethod("public ArrayList getData()", new File(dir + "/" + fileName))) { + result += "'public ArrayList getData()' method not found.\n"; + System.out.println("'public ArrayList getData()' method not found."); + } + */ + /* + if (!findMethod("public boolean saveData", new File(dir + "/" + fileName))) { + result += "'public boolean saveData(ObjectOutputStream)' method not found.\n"; + System.out.println("'public boolean saveData(ObjectOutputStream)' method not found."); + } + */ + if (!findMethod("public List getData", new File(dir + "/" + fileName))) { + result += "'public List getData()' method not found.\n"; + System.out.println("'public List getData()' method not found."); + } + if (!findMethod("public boolean saveState", new File(dir + "/" + fileName))) { + result += "'public boolean saveState(ObjectOutputStream)' method not found.\n"; + System.out.println("'public boolean saveState(ObjectOutputStream)' method not found."); + } + + System.out.println("Utils.compileAndroidFile: " + result); + } catch (IOException | InterruptedException ex) { + System.out.println(Utils.class.getName() + "@compileAndroidFile: " + ex.getMessage()); + } + return result; + } + + /* + * Description: Compiles the source code of the PM. + * Parameters : - The source code file. + * Returns : - The compilation log. + * Changelog : - . + */ + public static String compilePM(String dir, String fileName) { + String TAG = Utils.class.getName() + "@compilePM: "; + String result = ""; + try { + String javac_cmd = "\"" + Globals.javac_cmd + "\"" + " -cp " + "\"" + Globals.lib_url + "\"" + " " + "\"" + dir + "/" + fileName + "\""; + System.out.println(TAG + javac_cmd); + + Process p = Runtime.getRuntime().exec(Globals.console_cmd); + try (OutputStream os = p.getOutputStream()) { + os.write((javac_cmd + "\n").getBytes()); + close(os); + } + p.waitFor(); + try (BufferedReader bf = new BufferedReader(new InputStreamReader(p.getErrorStream()))) { + String line = bf.readLine(); + while (line != null) { + result = result + line + "\n"; + line = bf.readLine(); + } + } + + if (!findMethod("public void onStart", new File(dir + "/" + fileName))) { + result += "'public void onStart (Context, int, ObjectInputStream)' method not found.\n"; + System.out.println("'public void onStart (Context, int, ObjectInputStream)' method not found."); + } + if (!findMethod("public void onStop", new File(dir + "/" + fileName))) { + result += "'public void onStop ()' method not found.\n"; + System.out.println("'public void onStop ()' method not found."); + } + if (!findMethod("public void onPreferenceChanged", new File(dir + "/" + fileName))) { + result += "'public void onPreferenceChanged (int)' method not found.\n"; + System.out.println("'public void onPreferenceChanged (int)' method not found."); + } + if (!findMethod("public boolean saveState", new File(dir + "/" + fileName))) { + result += "'public boolean saveState (ObjectOutputStream)' method not found.\n"; + System.out.println("'public boolean saveState (ObjectOutputStream)' method not found."); + } + if (!findMethod("public int processData", new File(dir + "/" + fileName))) { + result += "'public int processData (ObjectInputStream, ObjectOutputStream)' method not found.\n"; + System.out.println("'public int processData (ObjectInputStream, ObjectOutputStream)' method not found."); + } + /**/ + System.out.println(TAG + result); + } catch (IOException | InterruptedException ex) { + System.out.println(TAG + ex.getMessage()); + } + return result; + } + + /* + * Description: Compiles the java classes and creates the .dex file. + * Parameters : - The directory of the code file. + * - The URL of the code file. + * Returns : - The compilation log. + * Changelog : 150523 - Paths with spaces and console output. + * 150607 - Remove throws clauses. + */ + public static String compileDex(String dir, String fileName) { + String TAG = Utils.class.getName() + "@compileDex: "; + String result = ""; + try { + String name = FilenameUtils.removeExtension(fileName); + String dx_cmd; + dx_cmd = "\"" + Globals.dx_cmd + "\"" + " --dex --no-strict --output=" + "\"" + dir + "/classes.dex" + "\"" + " " + "\"" + dir + "/" + "\"" + "*" + ".class"; + System.out.println("Utils.compileDex: " + dx_cmd); + Process p = Runtime.getRuntime().exec(Globals.console_cmd); + try (OutputStream os = p.getOutputStream()) { + os.write((dx_cmd + "\n").getBytes()); +close(os); + } + try (BufferedReader bf = new BufferedReader(new InputStreamReader(p.getErrorStream()))) { + String line = bf.readLine(); + while (line != null) { + result = result + line + "\n"; + line = bf.readLine(); + } + } + System.out.println(TAG + result); + } catch (IOException ex) { + System.out.println(TAG + ex.getMessage()); + } + return result; + } + + public static void unZip(String dir, String fileName) throws IOException, InterruptedException { + Process p = Runtime.getRuntime().exec(Globals.console_cmd); + OutputStream os = p.getOutputStream(); + os.write(("cd " + dir + "\n").getBytes()); + os.write(("unzip " + dir + "/" + fileName + "\n").getBytes()); +close(os); + p.waitFor(); + } + + /* + * Description: Generates fileId.zip from classes.dex inside dir. + * Parameters : - The directory where the zip is saved. + * - The fileId. + * Returns : - The zip size. + * Changelog : 150523 - Paths with spaces and console output. + */ + public static String zipDex(String dir, String fileId) { + String TAG = Utils.class.getName() + "@zipDex: "; + String result = "0"; + try { + Process p = Runtime.getRuntime().exec(Globals.console_cmd); + try (OutputStream os = p.getOutputStream()) { + os.write(("cd " + "\"" + dir + "\"" + "\n").getBytes()); + os.write(("\"" + Globals.zip_cmd + "\"" + " " + Globals.zip_args + " " + fileId + ".zip " + "classes.dex" + "\n").getBytes()); +close(os); + } + p.waitFor(); + System.out.println(TAG + dir + "/" + fileId + ".zip"); + File file = new File(dir + "/" + fileId + ".zip"); + System.out.println(TAG + Long.toString(file.length())); + result = Long.toString(file.length()); + } catch (IOException | InterruptedException ex) { + System.out.println(TAG + ex.getMessage()); + } + return result; + } + + /* + * Description: Update the ready status. + * Parameters : - The table. + * - The fileId. + * Returns : - The new status. + * Changelog : 150607 - Added PM support. + */ + public static void updateReady(String table, String id, String status) { + try { + Class.forName("com.mysql.jdbc.Driver"); + try (Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement()) { + s.executeUpdate("UPDATE " + table + " SET ready='" + status + "' WHERE id='" + id + "'"); + } + } catch (ClassNotFoundException | SQLException ex) { + Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /* */ +} diff --git a/src/main/java/com/www/server/privacy/Edit.java b/src/main/java/com/www/server/privacy/Edit.java new file mode 100644 index 0000000..dc43ee0 --- /dev/null +++ b/src/main/java/com/www/server/privacy/Edit.java @@ -0,0 +1,145 @@ +package com.www.server.privacy; + +import com.www.server.Globals; +import com.www.server.Utils; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; + +public class Edit extends HttpServlet { + + String app = "privacy"; + + /* + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + } + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String TAG = Edit.class.getName() + "@doPost: "; + HttpSession session = request.getSession(true); + String userName = (String) session.getAttribute("username"); + String userDir = Globals.db_dir + "/" + userName; + String date = Utils.getDate(); + String time = Utils.getTime(); + System.out.println(TAG + "User\t\t: " + userName); + String pmId = "0"; + String pmName = ""; + String pmDesc = ""; + String sensing = ""; + String pmSource = ""; + + try { + /* + * Get PM details. + */ + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + for (FileItem item : items) { + String fieldName = item.getFieldName(); + if (item.isFormField()) { + /* + * Get title and description. + */ + if ("pm_id".equals(fieldName)) { + pmId = item.getString(); + System.out.println(TAG + "Id\t\t: " + pmId); + } + if ("name".equals(fieldName)) { + pmName = item.getString(); + System.out.println(TAG + "Name\t\t: " + pmName); + } + if ("description".equals(fieldName)) { + pmDesc = item.getString(); + System.out.println(TAG + "Description\t: " + pmDesc); + } + if ("sensing_task".equals(fieldName)) { + sensing = item.getString(); + System.out.println(TAG + "Sensing\t: " + sensing); + } + if ("code".equals(fieldName)) { + pmSource = item.getString(); + System.out.println(TAG + "Source\t\t: " + pmSource); + } + } + } + } catch (FileUploadException ex) { + System.out.println(TAG + ex.getMessage()); + } + String fileDir = userDir + "/" + app + "/" + pmId; + String xmlUrl = fileDir + "/" + pmId + ".xml"; + String fileName = Utils.getText(xmlUrl, "source", "name"); + String fileUrl = fileDir + "/" + fileName; + File file = new File(fileUrl); + FileWriter fw = new FileWriter(file.getAbsoluteFile()); + try (BufferedWriter bw = new BufferedWriter(fw)) { + bw.write(pmSource); + } + String fileSize = Long.toString((new File(fileUrl)).length()); + Utils.setText(xmlUrl, "source", "size", fileSize); + String compLog = Utils.compilePM(fileDir, fileName); + Utils.setText(xmlUrl, "source", "compile", "date", Utils.getDate()); + Utils.setText(xmlUrl, "source", "compile", "time", Utils.getTime()); + if (Utils.stringIsEmpty(compLog)) { + compLog += "\n" + Utils.compileDex(fileDir, fileName); + if (Utils.stringIsEmpty(compLog)) { + String binSize = Utils.zipDex(fileDir, pmId); + Utils.setText(xmlUrl, "size", binSize); + Utils.updateReady("pms", pmId, "YES"); + String v = Utils.getText(xmlUrl, "version"); + Utils.setText(xmlUrl, "version", Integer.toString(Integer.parseInt(v) + 1)); + Utils.setText(xmlUrl, "status", "start"); + Utils.setText(xmlUrl, "date", Utils.getDate()); + Utils.setText(xmlUrl, "time", Utils.getTime()); + } + } + Utils.setText(xmlUrl, "source", "compile", "log", compLog); + if (!Utils.stringIsEmpty(pmName)) { + Utils.setText(xmlUrl, "name", pmName); + } + if (!Utils.stringIsEmpty(pmDesc)) { + Utils.setText(xmlUrl, "description", pmDesc); + } + Utils.setText(xmlUrl, "sensing", sensing); + try { + Class.forName("com.mysql.jdbc.Driver"); + try (Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement()) { + s.executeUpdate("UPDATE " + "pms" + " SET sensing='" + sensing + "' WHERE id='" + pmId + "'"); + } + } catch (ClassNotFoundException | SQLException ex) { + System.out.println(TAG + ex.getMessage()); + } + +// request.getRequestDispatcher("/Server/" + app + "/home.jsp").forward(request, response); + response.sendRedirect(response.encodeRedirectURL("/Server/" + app + "/view.jsp?id=" + pmId)); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + } + +} diff --git a/src/main/java/com/www/server/privacy/EditStatus.java b/src/main/java/com/www/server/privacy/EditStatus.java new file mode 100644 index 0000000..2f4fb9c --- /dev/null +++ b/src/main/java/com/www/server/privacy/EditStatus.java @@ -0,0 +1,72 @@ +package com.www.server.privacy; + +import com.www.server.Utils; +import java.io.IOException; +import java.io.PrintWriter; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +@WebServlet(name = "EditStatusPM", urlPatterns = {"/privacy/editstatus"}) +public class EditStatus extends HttpServlet { + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + HttpSession session = request.getSession(true); + String jspName = (String) request.getParameter("jsp_name"); + String fileId = (String) request.getParameter("pm_id"); + String app = "privacy"; + String fileDir = ""; + fileDir = Utils.getDir(app, fileId); + String xmlUrl = fileDir + "/" + fileId + ".xml"; + String status = (String) request.getParameter("view_status_button"); + if ("START".equals(status)) { + Utils.setText(xmlUrl, "status", "start"); + } else if ("PAUSE".equals(status)) { + Utils.setText(xmlUrl, "status", "pause"); + } else { + Utils.setText(xmlUrl, "status", "stop"); + Utils.updateReady("pms", fileId, "NO"); + } + if ("edit".equals(jspName)) { + response.sendRedirect(response.encodeRedirectURL("/Server/" + app + "/edit.jsp?id=" + fileId)); + } else { + response.sendRedirect(response.encodeRedirectURL("/Server/" + app + "/view.jsp?id=" + fileId)); + } + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/main/java/com/www/server/privacy/PrivacyService.java b/src/main/java/com/www/server/privacy/PrivacyService.java new file mode 100644 index 0000000..c8981b0 --- /dev/null +++ b/src/main/java/com/www/server/privacy/PrivacyService.java @@ -0,0 +1,419 @@ +package com.www.server.privacy; + +import com.www.server.Globals; +import com.www.server.Utils; +import java.io.*; +import java.lang.*; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.ws.rs.*; +import javax.ws.rs.core.*; +import org.codehaus.jackson.map.*; +import org.codehaus.jettison.json.*; + +@Path("pms") +public class PrivacyService { + + String app = "privacy"; + + @Context + private UriInfo context; + + @GET + @Produces(MediaType.TEXT_PLAIN) + public String respondAsReady() { + String TAG = PrivacyService.class.getName() + "@respondAsReady: "; + return TAG + "OK!"; + } + + /* + * Description: Used for testing purposes only. + * Parameters : - . + * Returns : - . + * Changelog : - . + */ + @GET + @Path("demo_filter/{param}") + public String demoFilter( + @PathParam("param") String param + ) { + String TAG = getClass().getName() + "@test: "; + + int pref = Integer.valueOf(param); + + String url = Globals.db_dir + "/emkatsom/sensing/5/client/5.dat"; + + List list = getData(url); + + System.out.println("1111111111"); +// + printData(list); + +// edit each entry of the input + for (Object o : list) { + + Map data = (Map) o; + + data.put("device", data.get("device")); + data.put("task", data.get("task")); + data.put("sensor", data.get("sensor")); + data.put("timestamp", (Long) data.get("timestamp") + (pref / 10) * 3600000000000L); + data.put("values", data.get("values")); + + } + + System.out.println("2222222222"); + + printData(list); + + return "OK"; + } + + boolean checkDataKeys(List data) { + String TAG = getClass().getName() + "@checkDataKeys: "; + + for (Object o : data) { + Map m = (Map) o; + for (Object key : m.keySet()) { + try { + if ("sensor".equals((String) key) + || "timestamp".equals((String) key) + || "values".equals((String) key)) { + System.out.println(TAG + key + " key" + " OK"); + } else { + System.out.println(TAG + key + " key" + " ERROR"); + return false; + } + } catch (Exception e) { + System.out.println(TAG + key + " key " + e.getMessage()); + return false; + } + } + } + return true; + } + + boolean checkDataValues(List data) { + String TAG = getClass().getName() + "@checkDataValues: "; + + for (Object o : data) { + Map m = (Map) o; + for (Object key : m.keySet()) { + if ("sensor".equals(key)) { + try { + int i = (int) m.get(key); + System.out.println(TAG + key + " value " + "OK"); + } catch (Exception e) { + System.out.println(TAG + key + " value " + e.getMessage()); + return false; + } + } else if ("timestamp".equals(key)) { + try { + long l = (long) m.get(key); + System.out.println(TAG + key + " value " + "OK"); + } catch (Exception e) { + System.out.println(TAG + key + " value " + e.getMessage()); + return false; + } + } else if ("values".equals(key)) { + try { + double[] d = (double[]) m.get(key); + System.out.println(TAG + key + " value " + "OK"); + } catch (Exception e) { + System.out.println(TAG + key + " value " + e.getMessage()); + return false; + } + } + } + } + return true; + } + + boolean saveData(List data, String url) { + String TAG = getClass().getName() + "@saveData: "; + + FileOutputStream fos; + ObjectOutputStream oos; + + try { + System.out.println(TAG + "Saving data to " + url); + List oldData = getData(url); + if (!oldData.isEmpty()) { + oldData.addAll(data); + data = oldData; + } + fos = new FileOutputStream(url); + oos = new ObjectOutputStream(fos); + oos.writeObject(data); + close(oos); + close(fos); + } catch (Exception ex) { + System.out.println(TAG + ex.getMessage()); + return false; + } + System.out.println(TAG + "OK"); + return true; + } + + void printData(List data) { + String html = ""; + for (Object o : data) { + Map m = (Map) o; + html += "" + + new Date((Long) m.get("timestamp") / 1000000L).toString() + "" + + " task[" + m.get("task") + "]" + + "@" + m.get("device") + ":" + + " " + m.get("sensor") + "" + + "" + Arrays.toString((double[]) m.get("values")) + "" + + "\n"; + } + System.out.println(html); + } + + List getData(String url) { + String TAG = getClass().getName() + "@getData: "; + + FileInputStream fis; + ObjectInputStream ois; + + List data = new ArrayList<>(); + + try { + System.out.println(TAG + "Returning data from " + url); + if (new File(url).exists()) { + fis = new FileInputStream(url); + ois = new ObjectInputStream(fis); + data = (List) ois.readObject(); + close(ois); + close(fis); + } else { + System.out.println(TAG + "File does not exist"); + } + } catch (Exception ex) { + System.out.println(TAG + ex.getMessage()); + } + System.out.println(TAG + "OK"); + return data; + } + + /* + * Description: Return the list of available privacy mechanisms. + * Parameters : - The device id. + * Returns : - The list of pms. + * Changelog : - . + */ + @GET + @Path("getlist/{deviceID}") + @Produces(MediaType.APPLICATION_JSON) + public List getList(@PathParam("deviceID") String deviceID) { + String TAG = PrivacyService.class.getName() + "@get_list: "; + List l = new ArrayList<>(); + + if (Utils.deviceExists(deviceID)) { + try { + Class.forName("com.mysql.jdbc.Driver"); + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement(); + s.executeQuery("SELECT * FROM pms WHERE ready='YES'"); + ResultSet rs = s.getResultSet(); + while (rs.next()) { + l.add(getInfo(rs.getString("id"))); + } + rs.close(); + s.close(); + c.close(); + } catch (ClassNotFoundException | SQLException ex) { + System.out.println(TAG + ex.getMessage()); + } + } else { + try { + JSONObject o = new JSONObject(); + o.append("Error", "Device not found"); + l.add(o.toString()); + System.out.println(TAG + o.toString()); + } catch (JSONException ex) { + System.out.println(TAG + ex.getMessage()); + } + } + return l; + } + + /* + * Description: Return the list of available privacy mechanisms for a + * specific Sensing Task. + * Parameters : - The Sensing Task id. + * - The device id. + * Returns : - The list of pms. + * Changelog : - . + */ + @GET + @Path("getlist/{stID}/{deviceID}") + @Produces(MediaType.APPLICATION_JSON) + public List getList( + @PathParam("stID") String stID, + @PathParam("deviceID") String deviceID) { + String TAG = PrivacyService.class + .getName() + "@get_list: "; + List l = new ArrayList<>(); + + if (Utils.deviceExists(deviceID)) { + try { + Class.forName("com.mysql.jdbc.Driver"); + Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement(); + s.executeQuery("SELECT * FROM pms WHERE sensing='" + stID + "' AND ready='YES'"); + ResultSet rs = s.getResultSet(); + while (rs.next()) { + l.add(getInfo(rs.getString("id"))); + } + rs.close(); + s.close(); + c.close(); + } catch (ClassNotFoundException | SQLException ex) { + System.out.println(TAG + ex.getMessage()); + } + } else { + try { + JSONObject o = new JSONObject(); + o.append("Error", "Device not found"); + l.add(o.toString()); + System.out.println(TAG + o.toString()); + } catch (JSONException ex) { + System.out.println(TAG + ex.getMessage()); + } + } + + JSONArray json = new JSONArray(l); +// System.out.println(TAG + json.toString()); + + try { + JSONArray jsonArray = new JSONArray(json.toString()); + List list = new ArrayList(); + for (int i = 0; i < jsonArray.length(); i++) { + list.add(jsonArray.getString(i)); + } + JSONObject o = new JSONObject(list.get(0)); + System.out.println(TAG + o.getJSONArray("name").getString(0)); + } catch (Exception ex) { + System.out.println(TAG + ex.getMessage()); + } + + return l; + } + + /* + * Description: Returns information for a particular mechanism. + * Parameters : - The pm id. + * - The device id. + * Returns : - The info. + * Changelog : - . + */ + @GET + @Path("{pmID}/getinfo/{deviceID}") + @Produces(MediaType.APPLICATION_JSON) + public String getInfo( + @PathParam("pmID") String pmID, + @PathParam("deviceID") String deviceID) { + String TAG = PrivacyService.class + .getName() + "@get_info: "; + String info = "Oops!"; + + if (Utils.deviceExists(deviceID)) { + info = getInfo(pmID); + } else { + info = "Device not found."; + } + + System.out.println(TAG + + info); + return info; + } + + /* + * Description: Returns the binary file of a particular mechanism. + * Parameters : - The pm id. + * - The device id. + * Returns : - The pm binary file. + * Changelog : - . + */ + @GET + @Path("{pmID}/getbin/{deviceID}") + public Response getBin( + @PathParam("pmID") String pmID, + @PathParam("deviceID") String deviceID) { + String TAG = PrivacyService.class + .getName() + "@get_bin: "; + Response.ResponseBuilder response; + + if (Utils.deviceExists(deviceID)) { + String dir = Utils.getDir(app, pmID); + if (dir != null && !"Oops!".equals(dir)) { + File bin = Utils.returnFileFrom(dir, ".zip"); + response = Response.ok((Object) bin); + } else { + response = Response.ok("Invalid privacy mechanism ID."); + } + } else { + response = Response.ok("Device not found."); + } + + System.out.println(TAG + + response.toString()); + return response.build(); + } + + /* + * Description: Returns information for a particular mechanism. + * Parameters : - The device id. + * Returns : - The info. + * Changelog : - . + */ + private String + getInfo(String id) { + String TAG = PrivacyService.class + .getName() + "@getInfo: "; + String info = "Oops!"; + + try { + String dir = Utils.getDir(app, id); + if (!"Oops!".equals(dir)) { + String xmlUrl = dir + "/" + id + ".xml"; + JSONObject o = new JSONObject(); + o.append("id", Utils.getText(xmlUrl, "id")); + o.append("name", Utils.getText(xmlUrl, "name")); +// class name + o.append("class", Utils.getText(xmlUrl, "source", "class")); +// + o.append("version", Utils.getText(xmlUrl, "version")); + o.append("description", Utils.getText(xmlUrl, "description")); + o.append("user", Utils.getText(xmlUrl, "user")); + o.append("date", Utils.getText(xmlUrl, "date")); + o.append("time", Utils.getText(xmlUrl, "time")); + o.append("size", Utils.getText(xmlUrl, "size")); + + info = o.toString(); + } else { + info = "Invalid privacy mechanism ID."; + } + } catch (JSONException ex) { + System.out.println(TAG + ex.getMessage()); + } + return info; + } + + public static void close(Closeable resource) { + if (resource != null) { + try { + resource.close(); + } catch (IOException ignore) { + } + } + } + +} diff --git a/src/main/java/com/www/server/privacy/Upload.java b/src/main/java/com/www/server/privacy/Upload.java new file mode 100644 index 0000000..2ddd5d9 --- /dev/null +++ b/src/main/java/com/www/server/privacy/Upload.java @@ -0,0 +1,245 @@ +package com.www.server.privacy; + +import com.www.server.Globals; +import com.www.server.Utils; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.io.FilenameUtils; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; + +public class Upload extends HttpServlet { + + String app = "privacy", + userName, + userDir, + date, + time, + pmName, + pmDesc = "", + sensing, + fileName = "", + fileDir, + fileUrl, + fileSize, + className, + compLog = "", + errorMsg = "", + binSize = "0"; + FileItem pmFile = null; + Integer pmId; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.sendRedirect(response.encodeRedirectURL("/Server/privacy/upload.jsp")); + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String TAG = Upload.class.getName() + "@doPost: "; + HttpSession session = request.getSession(true); + userName = (String) session.getAttribute("username"); + userDir = Globals.db_dir + "/" + userName; + date = Utils.getDate(); + time = Utils.getTime(); + System.out.println(TAG + "User\t\t: " + userName); + + try { + /* + * Get PM details. + */ + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + for (FileItem item : items) { + String fieldName = item.getFieldName(); + if (item.isFormField()) { + /* + * Get the title. + */ + if ("name".equals(fieldName)) { + pmName = item.getString(); + if (!Utils.stringIsEmpty(pmName)) { + System.out.println(TAG + "Name\t\t: " + pmName); + } else { + errorMsg += "Please enter a name
"; + } + } + /* + * Get the description. + */ + if ("description".equals(fieldName)) { + pmDesc = item.getString(); + if (!Utils.stringIsEmpty(pmDesc)) { + System.out.println(TAG + "Dscription\t: " + pmDesc); + } else { + errorMsg += "Please enter a description
"; + } + } + /* + * Get the sensing task. + */ + if ("sensing_task".equals(fieldName)) { + sensing = item.getString(); + if (!Utils.stringIsEmpty(sensing)) { + System.out.println(TAG + "Sensing\t: " + sensing); + } else { + errorMsg += "Please select a target Sensing Task
"; + } + } + } else { + /* + * Get the code. + */ + fileName = FilenameUtils.getName(item.getName()); +// class name + className = FilenameUtils.removeExtension(fileName); +// + FileItem fileItem = item; + if ("code".equals(fieldName)) { + if (fileName.substring(fileName.lastIndexOf(".") + 1).equalsIgnoreCase("java")) { + pmFile = fileItem; + System.out.println(TAG + "Filename\t\t: " + fileName); + } else { + errorMsg += "Privacy mechanism must be a .java file
"; + } + } + } + } + } catch (FileUploadException ex) { + System.out.println(TAG + ex.getMessage()); + } + if (!Utils.stringIsEmpty(errorMsg)) { + /* + * Something's wrong, re-upload. + */ + System.out.println(Upload.class.getName() + "@doPost: " + errorMsg); + request.setAttribute("errorMessage", errorMsg); + request.getRequestDispatcher("/" + app + "/upload.jsp").forward(request, response); + } else { + /* + * Everything's OK, save the PM. + */ + pmId = addNew(fileName, userName, sensing); + fileDir = userDir + "/" + app + "/" + pmId; + new File(fileDir).mkdir(); + fileUrl = fileDir + "/" + fileName; + fileSize = Utils.writeToFile(pmFile, fileUrl); + compLog = Utils.compilePM(fileDir, fileName); + if (Utils.stringIsEmpty(compLog)) { + compLog += "\n" + Utils.compileDex(fileDir, fileName); + if (Utils.stringIsEmpty(compLog)) { + binSize = Utils.zipDex(fileDir, pmId.toString()); + Utils.updateReady("pms", pmId.toString(), "YES"); + } + } + composeXml(); +// request.getRequestDispatcher("/privacy/home.jsp").forward(request, response); + if (Utils.stringIsEmpty(compLog)) { + response.sendRedirect(response.encodeRedirectURL("/Server/" + app + "/view.jsp?id=" + pmId)); + } else { + response.sendRedirect(response.encodeRedirectURL("/Server/" + app + "/edit.jsp?id=" + pmId)); + } + } + } + + /* + * Description: Inserts a new PM to the table. + * Parameters : - The file name. + * - The user name. + * Returns : - The new PM id. + * ChangeLog : - . + */ + private int addNew(String fName, String uName, String sName) { + int id = 0; + try { + Class.forName("com.mysql.jdbc.Driver"); + try (Connection c = DriverManager.getConnection(Globals.db_server, Globals.db_username, Globals.db_password); + Statement s = c.createStatement()) { + s.executeQuery("SELECT COUNT(*) FROM pms"); + try (ResultSet rs = s.getResultSet()) { + rs.next(); + id = rs.getInt(1) + 1; + } + s.executeUpdate("INSERT INTO pms (`id`, `filename`, `username`, `sensing`, `ready`) VALUES ('" + + id + "', '" + fName + "', '" + uName + "', '" + sName + "', '" + "NO" + "')"); + } + } catch (ClassNotFoundException | SQLException ex) { + System.out.println(Upload.class.getName() + "@addNew: " + ex.getMessage()); + } + if (Globals.DBG) { + System.out.println(Upload.class.getName() + "@addNew: " + "Id\t\t: " + id); + } + return id; + } + + /* + * Description: Composes the XML file. + * Parameters : - . + * Returns : - . + * ChangeLog : - . + */ + private void composeXml() { + String TAG = Utils.class.getName() + "@composeXml: "; + try { + Element root = new Element("pm"); + Document doc = new Document(root); + doc.setRootElement(root); + root.addContent(new Element("user").setText(userName)); + root.addContent(new Element("name").setText(pmName)); + root.addContent(new Element("version").setText("0")); + root.addContent(new Element("status").setText("")); + root.addContent(new Element("id").setText(pmId.toString())); + root.addContent(new Element("size").setText(binSize)); + root.addContent(new Element("date").setText(date)); + root.addContent(new Element("time").setText(time)); + root.addContent(new Element("description").setText(pmDesc)); + root.addContent(new Element("sensing").setText(sensing)); + + Element file = new Element("source"); + root.addContent(file); + file.addContent(new Element("name").setText(fileName)); + file.addContent(new Element("size").setText(fileSize)); +// class name + file.addContent(new Element("class").setText(className)); +// + Element compile = new Element("compile"); + file.addContent(compile); + if (Utils.stringIsEmpty(compLog)) { + root.getChild("version").setText("1"); + root.getChild("status").setText("start"); + } + compile.addContent(new Element("date").setText(date)); + compile.addContent(new Element("time").setText(time)); + compile.addContent(new Element("log").setText(compLog)); + + XMLOutputter xmlOutputter = new XMLOutputter(); + xmlOutputter.setFormat(Format.getPrettyFormat()); + xmlOutputter.output(doc, new FileWriter(fileDir + "/" + pmId + ".xml")); + } catch (IOException ex) { + System.out.println(TAG + ex.getMessage()); + } + } + + @Override + public String getServletInfo() { + return "Upload a new privacy mechanism"; + } + +} diff --git a/src/main/webapp/META-INF/context.xml b/src/main/webapp/META-INF/context.xml new file mode 100644 index 0000000..06887cb --- /dev/null +++ b/src/main/webapp/META-INF/context.xml @@ -0,0 +1,2 @@ + + diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..7df1791 --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,102 @@ + + + + SigninFilter + com.www.server.SigninFilter + + + SigninFilter + /main/* + + + SigninFilter + /privacy/* + + + ServletAdaptor + com.sun.jersey.spi.container.servlet.ServletContainer + 1 + + + Signin + com.www.server.Signin + + + Signup + com.www.server.Signup + + + Signout + com.www.server.Signout + + + Upload + com.www.server.Upload + + + Edit + com.www.server.Edit + + + EditStatus + com.www.server.EditStatus + + + EditProp + com.www.server.EditProp + + + UploadPM + com.www.server.privacy.Upload + + + EditPM + com.www.server.privacy.Edit + + + ServletAdaptor + /webresources/* + + + Signin + /signin + + + Signup + /signup + + + Signout + /signout + + + Upload + /upload + + + Edit + /edit + + + EditStatus + /editstatus + + + EditProp + /editprop + + + UploadPM + /privacy/upload + + + EditPM + /privacy/edit + + + 1000 + + + main/home.jsp + + diff --git a/src/main/webapp/img/apps.png b/src/main/webapp/img/apps.png new file mode 100644 index 0000000000000000000000000000000000000000..a2a0c45330ed4fd7f51afeca5e4d476b3a51c7ac GIT binary patch literal 3624 zcmV+@4%hLCP)KLZ*U+IBfRsybQWXdwQbLP>6pAqfylh#{fb6;Z(vMMVS~$e@S=j*ftg6;Uhf59&ghTmgWD0l;*T zI709Y^p6lP1rIRMx#05C~cW=H_Aw*bJ-5DT&Z2n+x)QHX^p z00esgV8|mQcmRZ%02D^@S3L16t`O%c004NIvOKvYIYoh62rY33S640`D9%Y2D-rV&neh&#Q1i z007~1e$oCcFS8neI|hJl{-P!B1ZZ9hpmq0)X0i`JwE&>$+E?>%_LC6RbVIkUx0b+_+BaR3cnT7Zv!AJxW zizFb)h!jyGOOZ85F;a?DAXP{m@;!0_IfqH8(HlgRxt7s3}k3K`kFu>>-2Q$QMFfPW!La{h336o>X zu_CMttHv6zR;&ZNiS=X8v3CR#fknUxHUxJ0uoBa_M6WNWeqIg~6QE69c9o#eyhGvpiOA@W-aonk<7r1(?fC{oI5N*U!4 zfg=2N-7=cNnjjOr{yriy6mMFgG#l znCF=fnQv8CDz++o6_Lscl}eQ+l^ZHARH>?_s@|##Rr6KLRFA1%Q+=*RRWnoLsR`7U zt5vFIcfW3@?wFpwUVxrVZ>QdQz32KIeJ}k~{cZZE^+ya? z2D1z#2HOnI7(B%_ac?{wFUQ;QQA1tBKtrWrm0_3Rgps+?Jfqb{jYbcQX~taRB;#$y zZN{S}1|}gUOHJxc?wV3fxuz+mJ4`!F$IZ;mqRrNsHJd##*D~ju=bP7?-?v~|cv>vB zsJ6IeNwVZxrdjT`yl#bBIa#GxRa#xMMy;K#CDyyGyQdMSxlWT#tDe?p!?5wT$+oGt z8L;Kp2HUQ-ZMJ=3XJQv;x5ci*?vuTfeY$;({XGW_huIFR9a(?@3)XSs8O^N5RyOM=TTmp(3=8^+zpz2r)C z^>JO{deZfso3oq3?Wo(Y?l$ge?uXo;%ru`Vo>?<<(8I_>;8Eq#KMS9gFl*neeosSB zfoHYnBQIkwkyowPu(zdms`p{<7e4kra-ZWq<2*OsGTvEV%s0Td$hXT+!*8Bnh2KMe zBmZRodjHV?r+_5^X9J0WL4jKW`}lf%A-|44I@@LTvf1rHjG(ze6+w@Jt%Bvjts!X0 z?2xS?_ve_-kiKB_KiJlZ$9G`c^=E@oNG)mWWaNo-3TIW8)$Hg0Ub-~8?KhvJ>$ z3*&nim@mj(aCxE5!t{lw7O5^0EIO7zOo&c6l<+|iDySBWCGrz@C5{St!X3hAA}`T4 z(TLbXTq+(;@<=L8dXnssyft|w#WSTW<++3>sgS%(4NTpeI-VAqb|7ssJvzNHgOZVu zaYCvgO_R1~>SyL=cFU|~g|hy|Zi}}s9+d~lYqOB71z9Z$wnC=pR9Yz4DhIM>Wmjgu z&56o6maCpC&F##y%G;1PobR9i?GnNg;gYtchD%p19a!eQtZF&3JaKv33gZ<8D~47E ztUS1iwkmDaPpj=$m#%)jCVEY4fnLGNg2A-`YwHVD3gv};>)hAvT~AmqS>Lr``i7kw zJ{5_It`yrBmlc25DBO7E8;5VoznR>Ww5hAaxn$2~(q`%A-YuS64wkBy=9dm`4cXeX z4c}I@?e+FW+b@^RDBHV(wnMq2zdX3SWv9u`%{xC-q*U}&`cyXV(%rRT*Z6MH?i+i& z_B8C(+grT%{XWUQ+f@NoP1R=AW&26{v-dx)iK^-Nmiuj8txj!m?Z*Ss1N{dh4z}01 z)YTo*JycSU)+_5r4#yw9{+;i4Ee$peRgIj+;v;ZGdF1K$3E%e~4LaI(jC-u%2h$&R z9cLXcYC@Xwnns&bn)_Q~Te?roKGD|d-g^8;+aC{{G(1^(O7m37Y1-+6)01cN&y1aw zoqc{T`P^XJqPBbIW6s}d4{z_f5Om?vMgNQEJG?v2T=KYd^0M3I6IZxbny)%vZR&LD zJpPl@Psh8QyPB@KTx+@RdcC!KX7}kEo;S|j^u2lU7XQ}Oo;f|;z4Ll+_r>@1-xl3| zawq-H%e&ckC+@AhPrP6BKT#_XdT7&;F71j}Joy zkC~6lh7E@6o;W@^IpRNZ{ptLtL(gQ-CY~4mqW;US7Zxvm_|@yz&e53Bp_lTPlfP|z zrTyx_>lv@x#=^!PzR7qqF<$gm`|ZJZ+;<)Cqu&ot2z=0000WV@Og>004R=004l4008;_004mL004C`008P>0026e000+nl3&F} z00093P)t-s00000000640s{jB1Ox;H1qB8M1_uWR2nYxX2?+`c3JVJh3=9kn4Gj(s z4i66x5D*X%5fKs+5)%^>6ciK{6%`g178e&67#J8C85tTH8XFrM92^`S9UUGX9v>ec zARr(iAt53nA|oRsBqSsyB_$>%CMPE+C@3f?DJd!{Dl021EG#T7EiEoCE-x=HFfcGN zF)=bSGBYzXG&D3dH8nOiHa9mnI5;>tIXOByIy*Z%JUl!-Jv}}?K0iM{KtMo2K|w-7 zLPJACL_|bIMMXwNMn^|SNJvOYNl8jdN=r*iOiWBoO-)WtPESuyP*6}&QBhJ-Qd3h? zR8&+|RaI72R##V7SXfwDSy@_IT3cINTwGjTU0q&YUSD5dU|?WjVPRroVq;@tWMpJz zWo2e&W@l$-XlQ6@X=!R|YHMq2Y;0_8ZEbFDZf|dIaBy&OadC2Ta&vQYbaZreb#-=j zc6WDoczAeud3kzzdV70&e0+R;eSLm@et&;|fPjF3fq{a8f`fyDgoK2Jg@uNOhKGlT zh=_=ZiHVAeii?YjjEszpjg5|uj*pLzkdTm(k&%*;l9Q8@l$4Z}m6ev3mY0{8n3$NE znVFiJnwy)OoSdAUot>VZo}ZteprD|kp`oIpqNAguq@<*!rKP5(rl+T;sHmu^si~@} zs;jH3tgNi9t*x%EuCK4Ju&}VPv9YqUva_?Zw6wIfwY9dkwzs#pxVX5vxw*Q!y1To( zyu7@dCU$jHda$;ryf%FD~k%*@Qq z&CSlv&d<-!(9qD)(b3Y<($mw^)YR0~)z#M4*4Nk9*x1lt)=I7_<=;-L_>FMg~>g((4?Ck9A?d|UF?(gsK z@bK{Q@$vHV^7Hfa^z`)g_4W4l_V@Sq`1ttw`T6?#`uqF){QUg={r&#_{{R2~En=ZJ z00001bW%=J06^y0W&i*HI!Q!9RCwC#)v*l#Fbu;mJ)Hm79*{Ll0rCNDb^!pe%n<>B up926sSwO%i1DI<80RRB12LJ&7{{sN1nBU*Yg4gH(0000 +<%@page import="java.util.Calendar"%> +<%@page import="com.www.server.Utils"%> +<%@page import="org.apache.commons.io.FileUtils"%> +<%@page import="java.io.DataInputStream"%> +<%@page import="java.io.BufferedInputStream"%> +<%@page import="java.util.Date"%> +<%@page import="java.text.SimpleDateFormat"%> +<%@page import="java.text.DateFormat"%> +<%@page import="java.io.InputStream"%> +<%@page import="java.io.FileInputStream"%> +<%@page import="org.w3c.dom.*, javax.xml.parsers.*" %> +<%@page import="java.io.File"%> +<%@page import="java.util.ArrayList"%> +<%@page import="java.util.List"%> +<%@page language="java" %> +<%@page import="org.jdom.Document" %> +<%@page import="org.jdom.Element" %> +<%@page import="org.jdom.JDOMException" %> +<%@page import="org.jdom.input.SAXBuilder" %> +<%@page import="java.io.IOException" %> +<%@page import="java.lang.*" %> + +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + <% + String serverUrl = Globals.server_url; + String dbDir = Globals.db_dir; + String username = (String) session.getAttribute("username"); + String app = "sensing"; + + String fileId = request.getParameter("id"); + String fileNameClient = "", fileCodeClient = "", clientLog = ""; + String fileNameServer = "", fileCodeServer = "", libNameServer = ""; + Boolean isCompiled = false; + Boolean isCompiledClient = false; + Boolean isCompiledServer = false; + Boolean hasMap = false; + Boolean hasLog = false; + Boolean hasLibServer = false; + double sw_lat = 0, sw_lng = 0, ne_lat = 0, ne_lng = 0; + Boolean hasServer = false; + String compileDate = ""; + String xmlUrl = dbDir + "/" + username + "/sensing/" + fileId + "/" + fileId + ".xml"; + Utils.setText(xmlUrl, "new", "no"); + File xmlFile = new File(xmlUrl); + fileNameClient = Utils.getText(xmlUrl, "client", "name"); + if ("on".equals(Utils.getText(xmlUrl, "client", "map", "status"))) { + hasMap = true; + sw_lat = Double.parseDouble(Utils.getText(xmlUrl, "client", "map", "sw_lat")); + sw_lng = Double.parseDouble(Utils.getText(xmlUrl, "client", "map", "sw_lng")); + ne_lat = Double.parseDouble(Utils.getText(xmlUrl, "client", "map", "ne_lat")); + ne_lng = Double.parseDouble(Utils.getText(xmlUrl, "client", "map", "ne_lng")); + } + File fileUrlClient = new File(dbDir + "/" + username + "/sensing/" + fileId + "/client/" + fileNameClient); + File fileDirServer = new File(dbDir + "/" + username + "/sensing/" + fileId + "/server"); + File fileUrlServer; + FileInputStream fis = null; + BufferedInputStream bis = null; + DataInputStream dis = null; + if (fileDirServer.exists()) { + hasServer = true; + fileNameServer = Utils.getText(xmlUrl, "server", "name"); + fileUrlServer = new File(dbDir + "/" + username + "/sensing/" + fileId + "/server/" + fileNameServer); + fis = new FileInputStream(fileUrlServer); + bis = new BufferedInputStream(fis); + dis = new DataInputStream(bis); + while (dis.available() != 0) { + fileCodeServer += (dis.readLine()) + "\n"; + } + } else { + hasServer = false; + } + fis = new FileInputStream(fileUrlClient); + bis = new BufferedInputStream(fis); + dis = new DataInputStream(bis); + while (dis.available() != 0) { + fileCodeClient += (dis.readLine()) + "\n"; + } + Utils.close(dis); + Utils.close(bis); + Utils.close(fis); + File dir = new File(dbDir + "/" + username + "/sensing/" + fileId); + File[] listOfFiles = dir.listFiles(); + if ("true".equals(Utils.getText(xmlUrl, "client", "compile", "status"))) { + isCompiledClient = true; + isCompiled = true; + } else { + isCompiledClient = false; + isCompiled = false; + } + if (hasServer) { + if ("true".equals(Utils.getText(xmlUrl, "server", "compile", "status"))) { + isCompiledServer = true; + } else { + isCompiledServer = false; + isCompiled = false; + } + } + %> + + " /> + " /> + + <%=fileNameClient%> - <%=session.getAttribute("username")%> - <%=Globals.logo + ": " + app%> + + + + + +
+
Sensing
+ <% if (isCompiled) {%> +
" method="post"> + + > + <% if ("pause".equals(Utils.getText(xmlUrl, "status"))) {%> + + + <% } else if ("start".equals(Utils.getText(xmlUrl, "status"))) {%> + + + <% } else if ("stop".equals(Utils.getText(xmlUrl, "status"))) {%> +

Stopped.

+ <% } else {%> +

Pending... + + Cancel. +

+ <% }%> +
+ <% }%> + +
+
+
"> + +
+
+
+
+
+ + <%=Utils.getText(xmlUrl, "name")%> + + <%=Utils.getText(xmlUrl, "comment")%> + + <%=Utils.getText(xmlUrl, "size")%> +
+
+ + <%=Utils.getText(xmlUrl, "date")%> + + <%=Utils.getText(xmlUrl, "time")%> +
+
+
+
+ > + > + > + > + > + > +
+
+ + +

Source

+ + + +
+ <% if ("on".equals(Utils.getText(xmlUrl, "client", "time", "status"))) {%> +
+ + +

Time

+
+ + - + +
+
+ <% }%> + <% if ("on".equals(Utils.getText(xmlUrl, "client", "map", "status"))) {%> +
+ + +

Location

+
+ + + + + + + + + +
+ <% }%> + <%if (isCompiled) { %> +
+ + +
+
+ <%if (!Utils.getText(xmlUrl, "client", "log").isEmpty()) {%> + + <% + List list = Utils.getNodeList(xmlUrl, "client", "log", "data"); + for (int i = 0; i < list.size(); i++) { + Element element = (Element) list.get(i); + %> +
+
+ <%="[" + element.getChildText("date") + " " + element.getChildText("time") + "]" + " @ "%> + + <%=element.getChildText("device")%> + +
+
+ <% } %> + + <% } else { %> +
Empty.
+ <% } %> +
+
+
+ <% } %> +
+ <% if (hasServer) {%> +
+ <% if (isCompiledServer) {%> +
+ + +

Source

+ + <% if (hasLibServer) {%> +
+ + <%=libNameServer%> +
+ <% }%> + +
+
+ <% }%> + +
+ <% }%> + +
+ +
+
+ + \ No newline at end of file diff --git a/src/main/webapp/main/home.jsp b/src/main/webapp/main/home.jsp new file mode 100644 index 0000000..de7fb52 --- /dev/null +++ b/src/main/webapp/main/home.jsp @@ -0,0 +1,150 @@ +<%@page contentType="text/html" pageEncoding="UTF-8"%> +<%@page import="com.www.server.Globals"%> +<%@page import="com.www.server.Utils"%> +<%@page import="java.util.Date"%> +<%@page import="java.text.SimpleDateFormat"%> +<%@page import="java.text.DateFormat"%> +<%@page import="org.jdom.input.SAXBuilder"%> +<%@page import="org.jdom.Element"%> +<%@page import="org.jdom.Document"%> +<%@page import="java.util.Comparator"%> +<%@page import="java.util.Arrays"%> +<%@page import="java.io.File"%> + + + + <% + String serverUrl = Globals.server_url; + String dbDir = Globals.db_dir; + String username = (String) session.getAttribute("username"); + String app = "sensing"; + /* + * Get the sorted list of sensing tasks. + */ + File appDir = new File(dbDir + "/" + username + "/" + app); + File[] listOfFiles = null; + if (appDir.exists()) { + listOfFiles = appDir.listFiles(); + Arrays.sort(listOfFiles, new Comparator() { + public int compare(File f1, File f2) { + return Integer.valueOf(f1.getName()).compareTo(Integer.valueOf(f2.getName())); + } + }); + } + %> + + " /> + " /> + <%="Home - " + username + " - " + Globals.logo + ": " + app%> + + <% if (!Globals.DBG) {%> + + + <% }%> + + + +
+
Sensing
+
+
+
"> + +
+
+
+
+ <% + if (listOfFiles != null && listOfFiles.length > 0) { + for (File file : listOfFiles) { + if (file.isDirectory()) { + String id = file.getName(); + String xmlFile = appDir + "/" + id + "/" + id + ".xml"; + String name = Utils.getText(xmlFile, "name"); + String hasNew = Utils.getText(xmlFile, "new"); + String counter = Utils.getText(xmlFile, "counter"); + String comment = Utils.getText(xmlFile, "comment"); + String date; + DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); + if ((Utils.getText(xmlFile, "date")).equals(dateFormat.format(new Date()))) { + date = Utils.getText(xmlFile, "time"); + } else { + date = Utils.getText(xmlFile, "date"); + } + %> + <% if ("yes".equals(hasNew)) {%> + +
+ <% + if (Integer.valueOf(counter) > 0) { + out.print(name + "(" + counter + ")"); + } else { + out.print(name); + } + %> +
+
<%=comment%>
+
<%=date%>
+
+ <% } else {%> + +
+ <% + if (Integer.valueOf(counter) > 0) { + out.print(name + "(" + counter + ")"); + } else { + out.print(name); + } + %> +
+
<%=comment%>
+
<%=date%>
+
+ <%} + } + } + } else {%> +
No tasks to view. Click on ">NEW to begin...
+ <%}%> + +
+
+ + diff --git a/src/main/webapp/main/upload.jsp b/src/main/webapp/main/upload.jsp new file mode 100644 index 0000000..f970361 --- /dev/null +++ b/src/main/webapp/main/upload.jsp @@ -0,0 +1,195 @@ +<%@page import="com.www.server.Globals"%> +<%@page import="java.util.Calendar"%> +<%@page import="java.text.SimpleDateFormat"%> +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + <% + String serverUrl = Globals.server_url; + String app = "sensing"; + %> + + " /> + " /> + Upload - <%=session.getAttribute("username")%> - <%=Globals.logo + ": " + app%> + + <% + Boolean error = false; + String errorMessage = (String) request.getAttribute("errorMessage"); + if (errorMessage == null) { + error = false; + } else { + error = true; + } + %> + + + +
+
Sensing
+
+
+
"> + +
+
+
+
" method="post" enctype="multipart/form-data"> + <% if (error) {%> +
+ <%=errorMessage%> +
+ <% }%> +
+ + +
+
+
+
+ + +
+ + +

Time

+
+ + - + +
+
+
+ + +

Location

+
+
+
+ + + + + + + + + + + + + + +
+
+
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
"> + +
+
+ + diff --git a/src/main/webapp/main/view.jsp b/src/main/webapp/main/view.jsp new file mode 100644 index 0000000..5603dc6 --- /dev/null +++ b/src/main/webapp/main/view.jsp @@ -0,0 +1,423 @@ +<%@page language="java" %> +<%@page import="com.www.server.Globals"%> +<%@page import="com.www.server.Utils"%> +<%@page import="org.apache.commons.io.FileUtils"%> +<%@page import="java.io.DataInputStream"%> +<%@page import="java.io.BufferedInputStream"%> +<%@page import="java.util.Date"%> +<%@page import="java.text.SimpleDateFormat"%> +<%@page import="java.text.DateFormat"%> +<%@page import="java.io.InputStream"%> +<%@page import="java.io.FileInputStream"%> +<%@page import="org.w3c.dom.*, javax.xml.parsers.*" %> +<%@page import="java.io.File"%> +<%@page import="java.util.ArrayList"%> +<%@page import="java.util.List"%> +<%@page import="org.jdom.Document" %> +<%@page import="org.jdom.Element" %> +<%@page import="org.jdom.JDOMException" %> +<%@page import="org.jdom.input.SAXBuilder" %> +<%@page import="java.io.IOException" %> +<%@page import="java.lang.*" %> + +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + <% + String serverUrl = Globals.server_url; + String dbDir = Globals.db_dir; + String username = (String) session.getAttribute("username"); + String app = "sensing"; + + String fileId = request.getParameter("id"); + String fileNameClient = "", fileCodeClient = "", clientLog = ""; + String fileNameServer = "", fileCodeServer = "", libNameServer = ""; + Boolean isCompiled = false; + Boolean isCompiledClient = false; + Boolean isCompiledServer = false; + Boolean hasMap = false; + Boolean hasLog = false; + Boolean hasLibServer = false; + double sw_lat = 0, sw_lng = 0, ne_lat = 0, ne_lng = 0; + Boolean hasServer = false; + String compileDate = ""; + String xmlUrl = dbDir + "/" + username + "/sensing/" + fileId + "/" + fileId + ".xml"; + Utils.setText(xmlUrl, "new", "no"); + File xmlFile = new File(xmlUrl); + fileNameClient = Utils.getText(xmlUrl, "client", "name"); + if ("on".equals(Utils.getText(xmlUrl, "client", "map", "status"))) { + hasMap = true; + sw_lat = Double.parseDouble(Utils.getText(xmlUrl, "client", "map", "sw_lat")); + sw_lng = Double.parseDouble(Utils.getText(xmlUrl, "client", "map", "sw_lng")); + ne_lat = Double.parseDouble(Utils.getText(xmlUrl, "client", "map", "ne_lat")); + ne_lng = Double.parseDouble(Utils.getText(xmlUrl, "client", "map", "ne_lng")); + } + File fileUrlClient = new File(dbDir + "/" + username + "/sensing/" + fileId + "/client/" + fileNameClient); + File fileDirServer = new File(dbDir + "/" + username + "/sensing/" + fileId + "/server"); + File fileUrlServer; + FileInputStream fis = null; + BufferedInputStream bis = null; + DataInputStream dis = null; + + try { + + if (fileDirServer.exists()) { + hasServer = true; + fileNameServer = Utils.getText(xmlUrl, "server", "name"); + fileUrlServer = new File(dbDir + "/" + username + "/sensing/" + fileId + "/server/" + fileNameServer); + fis = new FileInputStream(fileUrlServer); + bis = new BufferedInputStream(fis); + dis = new DataInputStream(bis); +// dis = new DataInputStream(new BufferedInputStream(new FileInputStream(fileUrlServer))); + while (dis.available() != 0) { + fileCodeServer += (dis.readLine()) + "\n"; + } + Utils.close(dis); + Utils.close(bis); + Utils.close(fis); + } else { + hasServer = false; + } + } catch (IOException e) { + + } + + try { + + fis = new FileInputStream(fileUrlClient); + bis = new BufferedInputStream(fis); + dis = new DataInputStream(bis); +// dis = new DataInputStream(new BufferedInputStream(new FileInputStream(fileUrlClient))); + while (dis.available() != 0) { + fileCodeClient += (dis.readLine()) + "\n"; + } + Utils.close(dis); + Utils.close(bis); + Utils.close(fis); + } catch (IOException e) { + + } + + File dir = new File(dbDir + "/" + username + "/sensing/" + fileId); + File[] listOfFiles = dir.listFiles(); + if ("true".equals(Utils.getText(xmlUrl, "client", "compile", "status"))) { + isCompiledClient = true; + isCompiled = true; + } else { + isCompiledClient = false; + isCompiled = false; + } + if (hasServer) { + if ("true".equals(Utils.getText(xmlUrl, "server", "compile", "status"))) { + isCompiledServer = true; + } else { + isCompiledServer = false; + isCompiled = false; + } + } + %> + + " /> + " /> + + <%=fileNameClient%> - <%=session.getAttribute("username")%> - <%=Globals.logo + ": " + app%> + + <% if (!Globals.DBG) {%> + + <% }%> + + + +
+
Sensing
+ <% if (isCompiled) {%> +
" method="post"> + + > + <% if ("pause".equals(Utils.getText(xmlUrl, "status"))) {%> + + + <% } else if ("start".equals(Utils.getText(xmlUrl, "status"))) {%> + + + <% } else if ("stop".equals(Utils.getText(xmlUrl, "status"))) {%> +

Stopped.

+ <% } else {%> +

Sending to device(s)... + + Cancel. +

+ <% }%> +
+ <%if (!"stop".equals(Utils.getText(xmlUrl, "status"))) {%> + + <% }%> + <% }%> +
+
+
"> + <% if (isCompiled) {%> + + <% }%> + +
+
+
+
+
+ + " title="Get task source code"> + + <%=Utils.getText(xmlUrl, "name")%> + + + + <%=Utils.getText(xmlUrl, "comment")%> + + <%=Utils.getText(xmlUrl, "client", "size")%> +
+
+ + <%=Utils.getText(xmlUrl, "date")%> + + <%=Utils.getText(xmlUrl, "time")%> +
+
+
+
+ > + > + > + > + > +
+ <% if (isCompiledClient) {%> +
+ + +

Source

+ + + +
+ <% if ("on".equals(Utils.getText(xmlUrl, "client", "time", "status"))) {%> +
+ + +

Time

+
<%=Utils.getText(xmlUrl, "client", "time", "from")%> - <%=Utils.getText(xmlUrl, "client", "time", "to")%>
+
+ <% }%> + <% if (hasMap) {%> +
+ + +

Location

+
+ +
+ <% }%> + <% } else {%> +
+ + + + + +
+
+ + + + +
+ <% }%> + <%if (isCompiled) { %> +
+ + +
+
+ <%if (!Utils.getText(xmlUrl, "client", "log").isEmpty()) {%> + + <% + try { + List list = Utils.getNodeList(xmlUrl, "client", "log", "data"); + for (int i = 0; i < list.size(); i++) { + Element element = (Element) list.get(i); + %> +
+
+ <%="[" + element.getChildText("date") + " " + element.getChildText("time") + "]" + " @ "%> + + <%=element.getChildText("device")%> + +
+
+ <% + } + } catch (Exception e) { + } + %> + + <% } else { %> +
Empty.
+ <% } %> +
+
+
+ <% } %> +
+
+ <% if (hasServer) {%> +
+ <% if (isCompiledServer) {%> +
+ + +

Source

+ + <% if (hasLibServer) {%> +
+ + <%=libNameServer%> +
+ <% }%> + +
+
+ <% } else {%> +
+ + + <% if (hasLibServer) {%> +
+ + <%=libNameServer%> +
+ <% }%> + + + +
+
+ + + + +
+ <% }%> +
+ <% }%> + <% if (!isCompiled) {%> + + <% }%> + + <% if (!isCompiled) {%> +
"> + +
+ <% }%> + +
+ + + \ No newline at end of file diff --git a/src/main/webapp/ppc.ico b/src/main/webapp/ppc.ico new file mode 100644 index 0000000000000000000000000000000000000000..7b43a38c86481356ae0330b38b6d8e8c653caf83 GIT binary patch literal 1150 zcmc(dK`X>z5XNUi(x$c)Ik6`$P7cm;c64&u6Wg9093%%xPLdop2ki&&0VK&$K7h1s z+T^& z#|{m+gG!fu*3p{q0B0}*>CS_kTkr)PC_~hz$Ui}~;DtP&v4Eytd1?^-E3Qee!xCuE zO9)TIJv8|)lG>VUA4KgU?--nV9=(bq@C) b*aXcwgq@6S&Rehx-JYLxpI&oD{r&X~R>@MC literal 0 HcmV?d00001 diff --git a/src/main/webapp/privacy/edit.jsp b/src/main/webapp/privacy/edit.jsp new file mode 100644 index 0000000..f82d05d --- /dev/null +++ b/src/main/webapp/privacy/edit.jsp @@ -0,0 +1,197 @@ +<%@page import="java.sql.SQLException"%> +<%@page import="java.sql.Statement"%> +<%@page import="java.sql.ResultSet"%> +<%@page import="java.sql.DriverManager"%> +<%@page import="java.sql.Connection"%> +<%@page language="java" %> +<%@page import="com.www.server.Globals"%> +<%@page import="com.www.server.Utils"%> +<%@page import="org.apache.commons.io.FileUtils"%> +<%@page import="java.io.DataInputStream"%> +<%@page import="java.io.BufferedInputStream"%> +<%@page import="java.util.Date"%> +<%@page import="java.text.SimpleDateFormat"%> +<%@page import="java.text.DateFormat"%> +<%@page import="java.io.InputStream"%> +<%@page import="java.io.FileInputStream"%> +<%@page import="org.w3c.dom.*, javax.xml.parsers.*" %> +<%@page import="java.io.File"%> +<%@page import="java.util.ArrayList"%> +<%@page import="java.util.List"%> +<%@page import="org.jdom.Document" %> +<%@page import="org.jdom.Element" %> +<%@page import="org.jdom.JDOMException" %> +<%@page import="org.jdom.input.SAXBuilder" %> +<%@page import="java.io.IOException" %> +<%@page import="java.lang.*" %> + +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + <% + String serverUrl = Globals.server_url; + String dbDir = Globals.db_dir; + String app = "privacy"; + String username = (String) session.getAttribute("username"); + + Boolean error = false; + String errorMessage = (String) request.getAttribute("errorMessage"); + if (errorMessage == null) { + error = false; + } else { + error = true; + } + + String pmId = request.getParameter("id"); + String xmlUrl = dbDir + "/" + username + "/" + app + "/" + pmId + "/" + pmId + ".xml"; + String pmName = Utils.getText(xmlUrl, "name"); + String pmVersion = Utils.getText(xmlUrl, "version"); + String pmDate = Utils.getText(xmlUrl, "date"); + String pmTime = Utils.getText(xmlUrl, "time"); + String pmDesc = Utils.getText(xmlUrl, "description"); + String stId = Utils.getText(xmlUrl, "sensing"); + String stName = Utils.getText(Utils.getDir("sensing", stId) + "/" + stId + ".xml", "name"); + String pmStatus = Utils.getText(xmlUrl, "status"); + String srcName = Utils.getText(xmlUrl, "source", "name"); + String compDate = Utils.getText(xmlUrl, "source", "compile", "date"); + String compTime = Utils.getText(xmlUrl, "source", "compile", "time"); + String compLog = Utils.getText(xmlUrl, "source", "compile", "log"); + /* + * Get the source code. + */ + File srcUrl = new File(dbDir + "/" + username + "/" + app + "/" + pmId + "/" + srcName); + FileInputStream fis = new FileInputStream(srcUrl); + BufferedInputStream bis = new BufferedInputStream(fis); + DataInputStream dis = new DataInputStream(bis); + String srcCode = ""; + while (dis.available() != 0) { + srcCode += (dis.readLine()) + "\n"; + } + Utils.close(dis); + Utils.close(bis); + Utils.close(fis); + %> + + " /> + " /> + <%=pmName%> - <%=username%> - <%=Globals.logo + ": " + app%> + + + +
+
<%=app%>
+ <%if (Utils.stringIsEmpty(compLog)) {%> +
" method="post"> + + > + <%if ("pause".equals(pmStatus)) {%> + + + <%} else if ("start".equals(pmStatus)) {%> + + + <%} else if ("stop".equals(pmStatus)) {%> +

Stopped.

+ <%} else {%> +

Something went wrong...

+ <%}%> +
+ <%if (!"stop".equals(pmStatus)) {%> + + <%}%> + <%} else {%> +

Something went wrong...

+ <%}%> + +
+
+
"> + <%if (Utils.stringIsEmpty(compLog)) {%> + + <%}%> + +
+
+
+
" method="post" enctype="multipart/form-data"> + > + + <% if (error) {%> +
+ <%=errorMessage%> +
+ <% }%> + + +
+ + + " title="View more information about the Sensing Tasks">More info +
+
+ + <%if (!Utils.stringIsEmpty(compLog)) {%> + + <%}%> +
+ +
+ +
+ + + \ No newline at end of file diff --git a/src/main/webapp/privacy/home.jsp b/src/main/webapp/privacy/home.jsp new file mode 100644 index 0000000..12db15a --- /dev/null +++ b/src/main/webapp/privacy/home.jsp @@ -0,0 +1,106 @@ +<%@page contentType="text/html" pageEncoding="UTF-8"%> +<%@page import="com.www.server.Globals"%> +<%@page import="com.www.server.Utils"%> +<%@page import="java.util.Date"%> +<%@page import="java.text.SimpleDateFormat"%> +<%@page import="java.text.DateFormat"%> +<%@page import="org.jdom.input.SAXBuilder"%> +<%@page import="org.jdom.Element"%> +<%@page import="org.jdom.Document"%> +<%@page import="java.util.Comparator"%> +<%@page import="java.util.Arrays"%> +<%@page import="java.io.File"%> + + + + <% + String serverUrl = Globals.server_url; + String dbDir = Globals.db_dir; + String username = (String) session.getAttribute("username"); + String app = "privacy"; + /* + * Get the sorted list of privacy mechanisms. + */ + File appDir = new File(dbDir + "/" + username + "/" + app); + File[] listOfFiles = null; + if (appDir.exists()) { + listOfFiles = appDir.listFiles(); + Arrays.sort(listOfFiles, new Comparator() { + public int compare(File f1, File f2) { + return Integer.valueOf(f1.getName()).compareTo(Integer.valueOf(f2.getName())); + } + }); + } + %> + + " /> + " /> + <%="Home - " + username + " - " + Globals.logo + ": " + app%> + + + +
+
Privacy
+
+
+
"> + +
+
+
+
+ <% +// listOfFiles = null; + if (listOfFiles != null && listOfFiles.length > 0) { + for (File file : listOfFiles) { + if (file.isDirectory()) { + String id = file.getName(); + String xmlFile = appDir + "/" + id + "/" + id + ".xml"; + String pmName = Utils.getText(xmlFile, "name"); + String version = Utils.getText(xmlFile, "version"); + String description = Utils.getText(xmlFile, "description"); +// int n = 40; +// if (description.length() > n) { +// description = description.substring(0, n) + "..."; +// } + String date; + DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); + if ((Utils.getText(xmlFile, "date")).equals(dateFormat.format(new Date()))) { + date = Utils.getText(xmlFile, "time"); + } else { + date = Utils.getText(xmlFile, "date"); + } + String stId = Utils.getText(xmlFile, "sensing"); + String stName = Utils.getText(Utils.getDir("sensing", stId) + "/" + stId + ".xml", "name"); + String name = pmName + " v" + version + ".0" + " for " + stName + " (" + stId + ")"; + %> + +
<%=name%>
+
<%=description%>
+
<%=date%>
+
+ <%}%> + <%}%> + <%} else {%> +
No mechanisms to view. Click on ">NEW to begin...
+ <%}%> + +
+
+ + diff --git a/src/main/webapp/privacy/upload.jsp b/src/main/webapp/privacy/upload.jsp new file mode 100644 index 0000000..61d99f9 --- /dev/null +++ b/src/main/webapp/privacy/upload.jsp @@ -0,0 +1,114 @@ +<%@page import="java.sql.SQLException"%> +<%@page import="java.sql.Statement"%> +<%@page import="java.sql.Statement"%> +<%@page import="java.sql.ResultSet"%> +<%@page import="java.sql.DriverManager"%> +<%@page import="java.sql.Connection"%> +<%@page import="com.www.server.Globals"%> +<%@page import="com.www.server.Utils"%> +<%@page import="java.util.Calendar"%> +<%@page import="java.text.SimpleDateFormat"%> +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + <% + String serverUrl = Globals.server_url; + String app = "privacy"; + Boolean error = false; + String errorMessage = (String) request.getAttribute("errorMessage"); + if (errorMessage == null) { + error = false; + } else { + error = true; + } + %> + + " /> + " /> + Upload - <%=session.getAttribute("username")%> - <%=Globals.logo + ": " + app%> + + + +
+
Privacy
+
+
+
"> + +
+
+
+
" method="post" enctype="multipart/form-data"> + <% if (error) {%> +
+ <%=errorMessage%> +
+ <% }%> + + +
+ + + " title="View more information about the Sensing Tasks">More info +
+ + +
+ +
"> + +
+
+ + diff --git a/src/main/webapp/privacy/view.jsp b/src/main/webapp/privacy/view.jsp new file mode 100644 index 0000000..95b4019 --- /dev/null +++ b/src/main/webapp/privacy/view.jsp @@ -0,0 +1,156 @@ +<%@page language="java" %> +<%@page import="com.www.server.Globals"%> +<%@page import="com.www.server.Utils"%> +<%@page import="org.apache.commons.io.FileUtils"%> +<%@page import="java.io.DataInputStream"%> +<%@page import="java.io.BufferedInputStream"%> +<%@page import="java.util.Date"%> +<%@page import="java.text.SimpleDateFormat"%> +<%@page import="java.text.DateFormat"%> +<%@page import="java.io.InputStream"%> +<%@page import="java.io.FileInputStream"%> +<%@page import="org.w3c.dom.*, javax.xml.parsers.*" %> +<%@page import="java.io.File"%> +<%@page import="java.util.ArrayList"%> +<%@page import="java.util.List"%> +<%@page import="org.jdom.Document" %> +<%@page import="org.jdom.Element" %> +<%@page import="org.jdom.JDOMException" %> +<%@page import="org.jdom.input.SAXBuilder" %> +<%@page import="java.io.IOException" %> +<%@page import="java.lang.*" %> + +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + <% + String serverUrl = Globals.server_url; + String dbDir = Globals.db_dir; + String app = "privacy"; + String username = (String) session.getAttribute("username"); + String pmId = request.getParameter("id"); + String xmlUrl = dbDir + "/" + username + "/" + app + "/" + pmId + "/" + pmId + ".xml"; + String pmName = Utils.getText(xmlUrl, "name"); + String pmVersion = Utils.getText(xmlUrl, "version"); + String pmDate = Utils.getText(xmlUrl, "date"); + String pmTime = Utils.getText(xmlUrl, "time"); + String pmDesc = Utils.getText(xmlUrl, "description"); + String stId = Utils.getText(xmlUrl, "sensing"); + String stName = Utils.getText(Utils.getDir("sensing", stId) + "/" + stId + ".xml", "name"); + String pmStatus = Utils.getText(xmlUrl, "status"); + String srcName = Utils.getText(xmlUrl, "source", "name"); + String compDate = Utils.getText(xmlUrl, "source", "compile", "date"); + String compTime = Utils.getText(xmlUrl, "source", "compile", "time"); + String compLog = Utils.getText(xmlUrl, "source", "compile", "log"); +// if (!Utils.stringIsEmpty(compLog)) { +// response.sendRedirect(response.encodeRedirectURL("/Server/" + app + "/edit.jsp?id=" + pmId)); +// } + /* + * Get the source code. + */ + File srcUrl = new File(dbDir + "/" + username + "/" + app + "/" + pmId + "/" + srcName); + FileInputStream fis = new FileInputStream(srcUrl); + BufferedInputStream bis = new BufferedInputStream(fis); + DataInputStream dis = new DataInputStream(bis); + String srcCode = ""; + while (dis.available() != 0) { + srcCode += (dis.readLine()) + "\n"; + } + Utils.close(dis); + Utils.close(bis); + Utils.close(fis); + %> + + " /> + " /> + <%=pmName%> - <%=username%> - <%=Globals.logo + ": " + app%> + + + +
+
<%=app%>
+ <%if (Utils.stringIsEmpty(compLog)) {%> +
" method="post"> + + > + <%if ("pause".equals(pmStatus)) {%> + + + <%} else if ("start".equals(pmStatus)) {%> + + + <%} else if ("stop".equals(pmStatus)) {%> +

Stopped.

+ <%} else {%> +

Something went wrong...

+ <%}%> +
+ <%} else {%> +

Something went wrong...

+ <%}%> + <%if (!"stop".equals(pmStatus)) {%> + + <%}%> +
+
+
"> + <%if (Utils.stringIsEmpty(compLog)) {%> + + <%}%> + +
+
+
+
" method="post" enctype="multipart/form-data"> + > +
+
+
+ <%=pmName%> + + <%if (Integer.parseInt(pmVersion) == 0) {%> +
+ <%} else {%> + version <%=pmVersion%>.0 + <%}%> +
+
+ <%=pmDate%> + <%=pmTime%> +
+
+
+ <%=pmDesc%> +
+
+
+ + <%if (!Utils.stringIsEmpty(compLog)) {%> + + <%}%> +
+
+ +
+ + + \ No newline at end of file diff --git a/src/main/webapp/signin.jsp b/src/main/webapp/signin.jsp new file mode 100644 index 0000000..144a3eb --- /dev/null +++ b/src/main/webapp/signin.jsp @@ -0,0 +1,38 @@ +<%@page import="com.www.server.Globals"%> +<%@page contentType="text/html" pageEncoding="UTF-8"%> +<%String serverUrl = Globals.server_url;%> + + + + + + <%=Globals.logo%>: Welcome! + + + +
+
+

<%=Globals.h1%>

+

<%=Globals.p%>

+
+
" autocomplete="on" method="post"> + + + + + + <% if ((String) request.getAttribute("errorMessage") != null) {%> + ${errorMessage} + <% }%> + +
+
+ + + \ No newline at end of file diff --git a/src/main/webapp/signup.jsp b/src/main/webapp/signup.jsp new file mode 100644 index 0000000..0d7d83e --- /dev/null +++ b/src/main/webapp/signup.jsp @@ -0,0 +1,68 @@ +<%@page import="com.www.server.Globals"%> +<%@page contentType="text/html" pageEncoding="UTF-8"%> +<%String serverUrl = Globals.server_url;%> + + + + + + <%=Globals.logo%>: Create an account + + + + +
+
+

<%=Globals.h1%>

+

<%=Globals.p%>

+
+
" method="post" autocomplete="off"> +
+ + + <% if ((String) request.getAttribute("errorMessageUsername") != null) {%> + ${errorMessageUsername} + <% }%> + + + <% if ((String) request.getAttribute("errorMessageEmail") != null) {%> + ${errorMessageEmail} + <% }%> + +
+ + + + + +
+
+ + + \ No newline at end of file diff --git a/src/main/webapp/style.css b/src/main/webapp/style.css new file mode 100644 index 0000000..6fb6dc4 --- /dev/null +++ b/src/main/webapp/style.css @@ -0,0 +1,1268 @@ +*{ + font-size: small; + padding: 0px; + margin: 0px; + font-family: Arial; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} +body, html { + height: 100%; +} +/********** HEADER **********/ +#header { + top: 0px; + position: fixed; + background: #f1f1f1; + height: 70px; + min-width: 800px; + width: 100%; + border-bottom: 1px solid #e5e5e5; + z-index: 3; + +} + +#logo { + float: left; + text-decoration: none; + //margin-left: 70px; + //margin-top: 5px; + margin-top: 15px; + margin-left: 50px; + //height: 35px; + color: #000000; + font-size: 35px; + //text-shadow: 1px 1px 1px grey; +} +/*#logo:first-letter { + font-family: Times New Roman; + font-weight: lighter; + font-size: 40px; +}/**/ + +#signin_signup, #signup_signin { + float: right; + margin-top: 20px; + margin-right: 50px; +} +#signin_signup_label { + display: inline-block; + margin-right: 10px; +} +#signin_signup_button { + background: #d84a38; + border: none; + color: white; + width: auto; + padding: 7px; + font-weight: bold; + text-shadow: 0 1px rgba(0,0,0,0.3); + border-radius: 2px; +} +#signin_signup_button:hover { + background: #d24132; +} +#signup_signin_button { + background: #f1f1f1; + border: 1px solid #dcdcdc; + color: black; + padding: 7px; + width: auto; + border-radius: 2px; +} +#signup_signin_button:hover { + background: #ececec; +} + +#user_apps { + float: right; + margin-top: 20px; + margin-right: 10px; + display: block; + cursor: pointer; +} +#user_apps img { + width: 30px; + height: 30px; + padding: 1px; +} +#user_apps a { + text-decoration: none; /* Remove the underline from the links. */ + display: block; + padding: 5px 10px; + width: 100px; + height: 30px; + color: black; + background: white; + border: 1px solid #e5e5e5; + text-align: center; + vertical-align: middle; +} +#user_apps a:visited { + color: black; +} +#user_apps ul { + list-style-type: none; /* Remove the bullets from the list */ +} +#user_apps .top { + //width: 100px; + height: 30px; + text-align: right; + cursor: default; +} +#user_apps ul li.item { + display: none; /* By default, do not display the items (which contains the links) */ + +} +#user_apps ul:hover .item { /* When the user hovers over the button (or any of the links) */ + display: block; +} +#user_apps li.item:hover a { /* When the user hovers over the button (or any of the links) */ + background: #f1f1f1; + color: black; +} + +#user_menu { + float: right; + margin-top: 20px; + margin-right: 50px; + text-align: center; + display: block; + cursor: pointer; +} +#user_menu a { + text-decoration: none; /* Remove the underline from the links. */ + display: block; + padding: 5px 10px; + width: 100px; + height: 30px; + color: black; + background: white; + border: 1px solid #e5e5e5; + text-align: center; + vertical-align: middle; +} +#user_menu a:visited { + color: black; +} +#user_menu ul { + list-style-type: none; /* Remove the bullets from the list */ +} +#user_menu .top { + width: 100px; + height: 30px; + padding: 5px 10px; + border: 1px solid #f1f1f1; + text-align: center; + cursor: default; +} +#user_menu ul li.item { + display: none; /* By default, do not display the items (which contains the links) */ + +} +#user_menu ul:hover .item { /* When the user hovers over the button (or any of the links) */ + display: block; +} +#user_menu ul:hover .top { /* When the user hovers over the button (or any of the links) */ + background: white; + border: 1px solid #e5e5e5; +} +#user_menu li.item:hover a { /* When the user hovers over the button (or any of the links) */ + background: #f1f1f1; +} + +/* +#user_menu { + float: right; + margin-top: 20px; + margin-right: 50px; + text-align: center; + cursor: pointer; + list-style: none; + display: block; + color: grey; +} +#user_menu div { + width: 100px; + height: 30px; + overflow: hidden; + background: #f1f1f1; + border: 1px solid #e5e5e5; +} +#user_menu div a { + color: grey; + text-decoration: none; +} +#user_menu div a:visited { + color: black; +} +#user_menu div:hover { + background: white; + color: black; + border: 1px solid black; +} +#user_menu div value { + display: block; + padding: 5px 10px; + overflow: hidden; +} +#user_menu_signout { + display: none; +} +#user_menu_username:hover ~ #user_menu_signout { + display: block; +} +#user_menu_signout:hover { + display: block; +} +*/ + +/********** TOP **********/ +#app { + float: left; + text-decoration: none; + margin-top: 15px; + margin-left: 50px; + color: #d84a38; + font-size: 18px; + cursor: default; +} +#app:first-letter { + text-transform: uppercase; +} + +#top { + position: fixed; + top: 70px; + width: 100%; + min-width: 800px; + height: 50px; + background: white; + border-bottom: 1px solid #e5e5e5; + z-index: 2; +} +#top_status { + margin-top: 18px; + margin-left: 210px; +} +#top_status a { + cursor: pointer; + color: black; +} +#top_status a:visited { + color: black; +} +#top_status a:hover { + text-decoration: underline; +} +#view_start_button, #view_pause_button, #view_stop_button { + position: absolute; + top: 80px; + width: 70px; + height: 30px; + background: #f1f1f1; + border: 1px solid #e5e5e5; + color: grey; + text-decoration: none; + font-weight: bold; + left: 200px; + z-index: 2; + border-radius: 2px; +} +#view_start_button, #view_pause_button { + top: 10px; + left: 200px; +} +#view_stop_button { + top: 10px; + left: 278px; +} +#view_start_button:hover, #view_pause_button:hover, #view_stop_button:hover, #view_edit_button:hover { + background: #ececec; + color: black; +} +#view_edit_button { + position: absolute; + top: 10px; + right: 50px; + width: 70px; + height: 30px; + background: #f1f1f1; + border: 1px solid #e5e5e5; + color: grey; + text-decoration: none; + font-weight: bold; + z-index: 2; + border-radius: 2px; +} +#edit_ok_button { + position: fixed; + top: 80px; + right: 128px; + background: #d84a38; + border: none; + color: white; + font-weight: bold; + text-shadow: 0 1px rgba(0,0,0,0.3); + border-radius: 2px; + width: 70px; + height: 30px; + z-index: 2; +} +#edit_ok_button:hover { + background: #d24132; +} +#edit_cancel_button { + position: fixed; + top: 80px; + right: 50px; + width: 70px; + height: 30px; + background: #f1f1f1; + border: 1px solid #e5e5e5; + color: grey; + text-decoration: none; + font-weight: bold; + z-index: 2; + border-radius: 2px; +} +#edit_cancel_button:hover { + background: #ececec; + color: black; +} + +/********** LEFT **********/ +#left { + position: fixed; + background: white; + text-align: center; + top: 120px; + height: 100%; + width: 200px; + z-index: 1; +} + +/********** FOOTER **********/ +#footer { + background-color: white; + position: relative; + padding: 10px; + width: 100%; + text-align: center; + border-top: 1px solid #e5e5e5; + border: none; + margin: 0px; +} +#footer a { + text-decoration: none; + color: black; +} +#footer a:visited { + color: black; +} +#footer a:hover { + text-decoration: underline; +} + +/********** SIGN IN **********/ +#signin { + height: 100%; + min-width: 800px; + max-width: 1024px; + min-height: 600px; + margin: 0 auto; + padding-top: 90px; + padding-left: 50px; + padding-right: 50px; +} +#signin_welcome_message { + width: 300px; + float: left; +} +#signin_welcome_message h1 { + font-size: large; + font-weight: normal; + margin-bottom: 10px; +} +#signin_form { + padding: 20px; + width: 300px; + float: right; + border: 1px solid #e5e5e5; + background: #f1f1f1; +} +#signin_form_label { + font-size: larger; +} +#signin_username_label , #signin_password_label { + display: block; + font-weight: bold; + margin-top: 20px; +} +#signin_error { + margin-top: 5px; + display: block; + color: #d84a38; +} +#signin_username_value, #signin_password_value { + margin-top: 5px; + width: 100%; + padding: 7px; + border: 1px solid #e5e5e5; +} +#signin_button { + margin-top: 20px; + padding: 7px; + width: auto; + background-color: #4d90fe; + font-weight: bold; + color: white; + border: 1px solid #3079ed; + text-shadow: 0 1px rgba(0,0,0,0.3); + border-radius: 2px; +} +#signin_button:hover { + background-color: #4185f3; + border: 1px solid #2f5bb7; +} + +/********** SIGN UP **********/ +#signup { + height: 100%; + min-width: 800px; + max-width: 1024px; + min-height: 600px; + margin: 0 auto; + padding-top: 90px; + padding-left: 50px; + padding-right: 50px; +} +#signup_welcome_message { + width: 300px; + float: left; +} +#signup_welcome_message h1 { + font-size: large; + font-weight: normal; + margin-bottom: 10px; +} +#signup_form { + padding: 20px; + width: 300px; + float: right; + border: 1px solid #e5e5e5; + background: #f1f1f1; +} +#signup_form_label { + font-size: larger; +} +#signup_username_label, #signup_email_label, #signup_password_label, #signup_password_confirm_label, #signup_recaptcha_label { + display: block; + font-weight: bold; + margin-top: 20px; +} +#signup_username_value, #signup_email_value, #signup_password_value, #signup_password_confirm_value { + margin-top: 5px; + width: 100%; + padding: 7px; + border: 1px solid #e5e5e5; +} +#signup_button { + margin-top: 20px; + padding: 7px; + width: auto; + background-color: #4d90fe; + font-weight: bold; + color: white; + border: 1px solid #3079ed; + text-shadow: 0 1px rgba(0,0,0,0.3); + border-radius: 2px; +} +#signup_button:hover { + background-color: #4185f3; + border: 1px solid #2f5bb7; +} +#signup_error_username, #signup_error_email { + margin-top: 5px; + display: block; + color: #d84a38; +} + +/********** HOME **********/ +#home_new_button { + background: #d84a38; + border: none; + color: white; + width: 100px; + height: 30px; + padding: 7px; + margin-top: 10px; + font-weight: bold; + text-shadow: 0 1px rgba(0,0,0,0.3); + border-radius: 2px; +} +#home_new_button:hover { + background: #d24132; +} +#home_content { + padding-left: 200px; + padding-top: 120px; + background-color: white; + min-width: 800px; + width: 100%; + height: 100%; + padding-right: 50px; +} +#home_empty { + width: 100%; + padding: 10px; + min-width: 550px; + border-bottom: 1px solid #e5e5e5; + color: black; + text-align: center; +} +#home_empty a { + color: #d84a38; + text-decoration: none; +} +#home_empty a:visited { + color: #d84a38; + text-decoration: none; +} +#home_empty a:hover { + text-decoration: underline; +} +#home_task { + text-decoration: none; + width: 100%; + min-width: 550px; + padding: 10px; + background: #f1f1f1; + border-bottom: 1px solid #e5e5e5; + color: black; + display: block; +} +#home_task_name, #home_task_comment, #home_task_date { + display: inline-block; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +#home_task_name { + width: 25%; + padding-left: 10px; +} +#home_task_comment { + width: 60%; + padding-left: 10px; +} +#home_task_date { + width: 14%; + padding-left: 10px; + padding-right: 10px; + float: right; + text-align: right; +} + +/********** VIEW **********/ +#view_new_button { + margin-top: 10px; + width: 100px; + height: 30px; + background: #f1f1f1; + border: 1px solid #dcdcdc; + color: grey; + text-decoration: none; + font-weight: bold; + border-radius: 2px; +} +#view_new_button:hover { + background: #ececec; + color: black; +} +#view_file_on:checked ~ #view_new_button { + background: #d84a38; + border: none; + color: white; + width: 100px; + padding: 7px; + margin-top: 10px; + font-weight: bold; + text-shadow: 0 1px rgba(0,0,0,0.3); + border-radius: 2px; +} +#view_file_on:checked ~ #view_new_button:hover { + background: #d24132; +} +#view_ok_button { + position: fixed; + top: 80px; + width: 70px; + height: 30px; + border: 1px solid #e5e5e5; + color: grey; + left: 200px; + z-index: 2; + background: #d84a38; + border: none; + color: white; + font-weight: bold; + text-shadow: 0 1px rgba(0,0,0,0.3); + border-radius: 2px; +} +#view_ok_button:hover { + background: #d24132; +} +#view_cancel_button { + position: fixed; + top: 80px; + width: 70px; + height: 30px; + background: #f1f1f1; + border: 1px solid #e5e5e5; + color: grey; + text-decoration: none; + font-weight: bold; + left: 278px; + z-index: 2; + border-radius: 2px; +} +#view_cancel_button:hover { + background: #ececec; + color: black; +} +#view_file { + height: 100%; + padding-left: 200px; + padding-right: 50px; + padding-top: 120px; + background: white; + min-width: 800px; +} + +#view_file_attributes { + width: 100%; + padding: 10px; + border-bottom: 1px solid #e5e5e5; + overflow: auto; +} +#view_file_details label, #view_file_date label { + display: none; + width: 100px; + color: grey; +} +#view_file_details a { + text-decoration: none; +} +#view_file_details a:visited { + color: black; +} +#view_file_details a:hover { + text-decoration: underline; + color: black; +} +#view_file_details { + float: left; + display: block; +} +#view_file_details value{ + display: block; +} +#view_size_value { + display: none !important; +} +#view_file_date { + display: block; + text-align: right; +} +#view_file_date value{ + display: block; + padding-bottom: 5px; +} +#view_filename_value { + font-size: x-large; + margin-bottom: 5px; + color: black; +} +#view_comment_value { + color: grey; +} +#view_file_client, #view_file_server { + padding: 10px; + border-bottom: 1px solid #e5e5e5; +} +#view_file_server {} +#view_client_label, #view_server_label { + display: block; + width: 100%; + font-weight: bold; +} +#view_client_devices { + font-weight: normal; +} +#view_client_value, #view_server_value { + display: none; +} +#view_client_log { + display: none; +} +#view_client_log_data { + display: inline; +} +#view_client_log_options { + margin-left: -4px; + display: inline; +} +#view_client_log_element { + display: block; + margin-bottom: 10px; + cursor: default; +} +#view_client_log_element a{ + text-decoration: none; + color: black; +} +#view_client_log a:visited { + color: black; +} +#view_client_log_delete a { + color: #d84a38; +} +#view_client_log_value, #view_client_log_delete { + display: inline; +} +#view_client_log_download, #view_client_log_delete, #view_client_log_downdel { + color: black; + text-decoration: none; + margin-bottom: 10px; +} +#view_client_log_download:visited, #view_client_log_delete:visited, #view_client_log_downdel:visited { + color: black; +} +#view_client_log_download:hover, #view_client_log_delete:hover, #view_client_log_downdel:hover { + text-decoration: underline; +} +#view_server_lib { + margin-top: 10px; +} +#view_client_value textarea, #view_server_value textarea { + width: 100%; + resize: vertical; + min-height: 200px; + margin: 10px 0; + border-color: transparent; + font-family: "Courier New"; +} +#view_client_checkbox, #view_time_checkbox, #view_map_checkbox, #view_client_log_checkbox, #view_server_checkbox { + margin: 10px 0; + position: relative; + top: 2px; +} +#view_client_checkbox_label, #view_time_checkbox_label, #view_map_checkbox_label, #view_client_log_label, #view_server_checkbox_label { + display: inline; + bottom: 10px; +} +#view_client_checkbox:checked ~ #view_client_value { + display: block; +} +#view_time_checkbox:checked ~ #view_time_selection { + display: block; +} +#view_time_selection { + display: none; + text-align: center; + margin: 0 auto; +} +#view_map {} +#view_map_checkbox:checked ~ #view_map_canvas { + height: 200px; + margin-bottom: 10px; + border: 1px solid #e5e5e5; +} +#view_client_log_checkbox:checked ~ #view_client_log { + display: inline; +} +#view_server_checkbox:checked ~ #view_server_value { + display: block; +} +#view_map_canvas { + margin: 0 auto; + height: 0px; + width: 360px; +} +#view_client_compile_label, #view_server_compile_label { + color: #d84a38; +} +#view_client_compile_value textarea, #view_server_compile_value textarea { + width: 100%; + resize: vertical; + min-height: 200px; + display: block; + margin-top: 10px; + border-color: transparent; + font-family: "Courier New"; +} + +/********** EDIT **********/ + + +/********** UPLOAD **********/ +#upload_ok_button { + position: fixed; + background: #d84a38; + border: none; + color: white; + font-weight: bold; + text-shadow: 0 1px rgba(0,0,0,0.3); + border-radius: 2px; + top: 80px; + left: 200px; + width: 70px; + height: 30px; + z-index: 2; +} +#upload_ok_button:hover { + background: #d24132; +} +#upload_cancel_button { + position: fixed; + top: 80px; + width: 70px; + height: 30px; + background: #f1f1f1; + border: 1px solid #e5e5e5; + color: grey; + text-decoration: none; + font-weight: bold; + left: 278px; + z-index: 2; + border-radius: 2px; +} +#upload_cancel_button:hover { + background: #ececec; + color: black; +} +#upload_new_button { + margin-top: 10px; + width: 100px; + height: 30px; + background: #f1f1f1; + border: 1px solid #dcdcdc; + color: grey; + text-decoration: none; + font-weight: bold; + border-radius: 2px; +} +#upload_new_button:hover { + background: #ececec; + color: black; +} +#upload_message { + margin-bottom: 10px; + color: #d84a38; +} + +#upload_file { + padding-left: 200px; + padding-top: 120px; + padding-right: 50px; + padding-bottom: 37px; + min-width: 800px; + min-height: 600px; + height: 100%; +} +#upload_file_form { + padding-top: 10px; + padding-left: 10px; + padding-right: 10px; + border: 1px solid #e5e5e5; + height: 100%; + background: #f1f1f1; +} +#upload_comment_label { + display: none; + width: 100px; + color: grey; +} +#upload_comment_value { + width: 100%; + height: 30px; + float: top; + padding-left: 10px; + padding-right: 10px; + border: none; +} +#upload_code { + width: 100%; + height: 100%; + margin-top: -30px; + padding-top: 40px; + padding-bottom: 10px; +} +#upload_client { + float: left; + width: 50%; + height: 100%; + padding-right: 5px; +} +#upload_server { + float: right; + width: 50%; + height: 100%; + padding-left: 5px; +} +#upload_code_client, #upload_code_server { + border: 1px dashed #e5e5e5; + padding: 10px; + width: 100%; + height: 100%; + overflow: hidden; +} +#upload_code_client_label, #upload_code_server_label { + width: 100%; + display: block; + text-align: center; + float: top; + padding-bottom: 10px; + font-weight: bolder; +} +#upload_code_client_value, #upload_code_server_value { + display: block; + text-align: center; + margin-bottom: 10px; +} +#upload_time_checkbox, #upload_map_checkbox { + margin: 10px 0; + position: relative; + top: 2px; +} +#upload_time_checkbox_label, #upload_map_checkbox_label { + display: inline; +} +#upload_time_selection { + display: none; + text-align: center; + margin: 0 auto; +} +#upload_time_checkbox:checked ~ #upload_time_selection { + display: block; + z-index: 1; +} +#upload_map_canvas { + /*height: 0px;*/ + /* + 150523: Changing height does not work for some reason. + Initializing as instead. + */ + height: 200px; + width: 360px; + display: none; + margin: 0 auto; +} +#upload_map_details { + display: none; +} +#upload_map_details input{ + width: 40%; +} +/* + * The user wants to define a map region. Show the map. + */ +#upload_map_checkbox:checked ~ #upload_map_canvas { + /*height: 200px;*/ + display: block; + border: 1px solid #e5e5e5; + z-index: 1; +} +#upload_map_checkbox:checked ~ #upload_map_details { + display: block; +} + +#upload_lib_server_checkbox { + margin-bottom: 10px; + position: relative; + top: 1px; +} +#upload_lib_server_checkbox_label { + display: inline; +} +#upload_lib_server_value { + display: none; +} +#upload_lib_server_checkbox:checked ~ #upload_lib_server_value { + display: block; +} + +/********** UPLOAD PM **********/ +#upload_pm { + padding-left: 200px; + padding-top: 120px; + padding-right: 50px; + padding-bottom: 37px; + min-width: 800px; + min-height: 600px; + height: 100%; +} +#upload_pm .form { + padding-top: 10px; + padding-left: 10px; + padding-right: 10px; + border: 1px solid #e5e5e5; + height: 100%; + background: #f1f1f1; +} +#upload_pm .name { + width: 100%; + + float: top; + padding: 10px; + border: none; +} +#upload_pm .description { + width: 100%; + height: 200px; + float: top; + margin-top: 10px; + padding: 10px; + resize: vertical; + border: none; +} +#upload_pm .sensing_task { + width: 100%; + float: top; + margin: 10px 10px 10px 0px; + border: none; +} +#upload_pm .sensing_task .id { + width: 85%; + float: left; + padding: 10px; + border: none; +} +#upload_pm .sensing_task a { + width: 15%; + float: right; + text-align: center; + padding: 10px; + text-decoration: none; + color: black; +} +#upload_pm .sensing_task a:hover { + text-decoration: underline; +} +#upload_pm .sensing_task a:visited { + color: black; +} +#upload_pm .code { + width: 100%; + float: top; + margin: 10px 10px 10px 0px; + border: none; +} + +/********** VIEW PM **********/ +#view_pm .pm { + height: 100%; + padding-left: 200px; + padding-right: 50px; + padding-top: 120px; + background: white; + min-width: 800px; +} +#view_pm .pm .details { + width: 100%; + padding: 10px; + border-bottom: 1px solid #e5e5e5; + overflow: auto; +} +#view_pm .pm .info { + width: 100%; + overflow: auto; + display: block; +} +#view_pm .pm .details .left { + float: left; + display: block; + width: 50%; +} +#view_pm .pm .details .left .name { + font-size: x-large; + display: inline-block; +} +#view_pm .pm .details .left .st { + display: inline-block; +} +#view_pm .pm .details .left .st a { + text-decoration: none; + color: black; +} +#view_pm .pm .details .left .st a:visited { + color: black; +} +#view_pm .pm .details .left .st a:hover { + text-decoration: underline; + color: black; +} +#view_pm .pm .details .left .version { + color: grey; + display: block; + margin-top: 5px; +} +#view_pm .pm .details .right { + float: right; + display: block; + text-align: right; + width: 50%; +} +#view_pm .pm .details .right .date { + display: block; +} +#view_pm .pm .details .right .time { + display: block; + margin-top: 5px; +} +#view_pm .pm .details .description { + display: block; + text-align: justify; + margin-top: 15px; + width: 100%; +} +#view_pm .pm .source { + border-bottom: 1px solid #e5e5e5; +} +#view_pm .pm .source .code { + width: 100%; + resize: vertical; + min-height: 200px; + padding: 10px; + border-color: transparent; + font-family: "Courier New"; +} +#view_pm .pm .source .error { + width: 100%; + resize: vertical; + min-height: 200px; + padding: 10px; + border-color: transparent; + font-family: "Courier New"; + color: #d84a38; +} + +/********** EDIT PM **********/ +#edit_pm { + height: 100%; + padding-left: 200px; + padding-right: 50px; + padding-top: 120px; + background: white; + min-width: 800px; +} +#edit_pm .name { + width: 100%; + height: 30px; + float: top; + padding: 10px; + margin-top: 10px; + border: 1px solid #e5e5e5; +} +#edit_pm .description { + width: 100%; + resize: vertical; + min-height: 200px; + padding: 10px; + margin-top: 10px; + text-align: justify; + border: 1px solid #e5e5e5; +} +#edit_pm .sensing_task { + width: 100%; + float: top; + margin: 10px 10px 10px 0px; + border: none; +} +#edit_pm .sensing_task .id { + width: 85%; + float: left; + padding: 10px; + border: 1px solid #e5e5e5; +} +#edit_pm .sensing_task a { + width: 15%; + float: right; + text-align: center; + padding: 10px; + text-decoration: none; + color: black; +} +#edit_pm .sensing_task a:hover { + text-decoration: underline; +} +#edit_pm .sensing_task a:visited { + color: black; +} +#edit_pm .source .code { + width: 100%; + resize: vertical; + min-height: 200px; + padding: 10px; + margin-top: 10px; + border: 1px solid #e5e5e5; + font-family: "Courier New"; +} +#edit_pm .source .error { + width: 100%; + resize: vertical; + min-height: 200px; + padding: 10px; + margin-top: 10px; + border: 1px solid #e5e5e5; + font-family: "Courier New"; + color: #d84a38; +} + +/********** HOME PM **********/ +#home_pm { + +} +#home_pm .content { + padding-left: 200px; + padding-top: 120px; + background-color: white; + min-width: 800px; + width: 100%; + height: 100%; + padding-right: 50px; +} +#home_pm .item { + text-decoration: none; + width: 100%; + min-width: 550px; + padding: 10px; + background: #f1f1f1; + border-bottom: 1px solid #e5e5e5; + color: black; + display: block; +} +#home_pm .item *{ + display: inline-block; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + +} +#home_pm .name { + width: 25%; + padding-left: 10px; +} +#home_pm .description { + width: 60%; + padding-left: 10px; +} +#home_pm .date { + width: 14%; + padding-left: 10px; + padding-right: 10px; + float: right; + text-align: right; +} \ No newline at end of file