Initial commit

This commit is contained in:
Manos
2015-10-29 01:06:42 +02:00
commit 2d5dbe00f7
36 changed files with 7139 additions and 0 deletions

View File

@ -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<String, String> 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<String, String> 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();
}
}

View File

@ -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);
}
}

View File

@ -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<FileItem> 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;
}
}

View File

@ -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));
}
}

View File

@ -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));
}
}
}

View File

@ -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 = "&pi;pc";
public static String h1 = "&pi;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 = "";
/**/
}

View File

@ -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"));
}
}

View File

@ -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() {}
}

View File

@ -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");
}
}

View File

@ -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("<h2 align=\"center\">Validation code is wrong.</h2>");
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"));
}
}

View File

@ -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);
}
}
}

View File

@ -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<Object> 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<Object> 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 = "<h1>List of submitted Sensing Tasks</h1>";
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 += "<ol type=\"1\">";
while (rs.next()) {
String id = rs.getString("id");
String dir = Utils.getDir(app, id);
String xml = dir + "/" + id + ".xml";
html += "<li value =\"" + Utils.getText(xml, "id") + "\"><a href=" + Globals.server_url + "/webresources/tasks/" + id + "/getsrc>"
+ Utils.getText(xml, "name") + ""
+ ": " + Utils.getText(xml, "comment") + ""
+ " submitted by " + Utils.getText(xml, "username") + ""
+ " on " + Utils.getText(xml, "date") + " at " + Utils.getText(xml, "time")
+ "</a></li>";
}
html += "</ol>";
}
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<Object> 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<Object> 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) {
}
}
}
}

View File

@ -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<FileItem> 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<br/>";
} else {
if (fileName.substring(fileName.lastIndexOf(".") + 1).equalsIgnoreCase("java")) {
hasFileClient = true;
fileNameClient = fileName;
fileContentClient = file;
} else {
errorMessage += "Client part must be a .java file<br/>";
}
}
} 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<br/>";
}
}
//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<br/>";
//}
//}
}
}
} 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);
}
}
}

View File

@ -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();
}
}

View File

@ -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<String> getData()", new File(dir + "/" + fileName))) {
result += "'public ArrayList<String> getData()' method not found.\n";
System.out.println("'public ArrayList<String> 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<Object> getData", new File(dir + "/" + fileName))) {
result += "'public List<Object> getData()' method not found.\n";
System.out.println("'public List<Object> 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);
}
}
/* */
}

View File

@ -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<FileItem> 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";
}
}

View File

@ -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 {
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> 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 <code>POST</code> 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";
}// </editor-fold>
}

View File

@ -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<Object> 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<Object> 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<Object> 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<String> getList(@PathParam("deviceID") String deviceID) {
String TAG = PrivacyService.class.getName() + "@get_list: ";
List<String> 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<String> getList(
@PathParam("stID") String stID,
@PathParam("deviceID") String deviceID) {
String TAG = PrivacyService.class
.getName() + "@get_list: ";
List<String> 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<String> list = new ArrayList<String>();
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) {
}
}
}
}

View File

@ -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<FileItem> 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<br/>";
}
}
/*
* 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<br/>";
}
}
/*
* 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<br/>";
}
}
} 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<br/>";
}
}
}
}
} 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";
}
}