浏览代码

First upload

Deben Oldert 10 年之前
当前提交
f297dd626f
共有 8 个文件被更改,包括 940 次插入0 次删除
  1. 187 0
      Java/APS.java
  2. 59 0
      Java/ErrorCode.java
  3. 151 0
      Java/Function.java
  4. 13 0
      Java/JSON.java
  5. 124 0
      Java/LDAP.java
  6. 69 0
      Java/MAIL.java
  7. 294 0
      Java/SAS.java
  8. 43 0
      Java/SQL.java

+ 187 - 0
Java/APS.java

@@ -0,0 +1,187 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.naming.NamingException;
+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 org.json.simple.JSONObject;
+import org.json.simple.parser.ParseException;
+
+/**
+ *
+ * @author Deben
+ */
+@WebServlet(urlPatterns = {"/APS"})
+public class APS extends HttpServlet {
+    
+    ErrorCode code = new ErrorCode();
+    Function function = new Function();
+    int ErrCode;
+    int ldapError;
+    String req;
+    String reqBody;
+
+    /**
+     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
+     * methods.
+     *
+     * @param request servlet request
+     * @param response servlet response
+     * @throws ServletException if a servlet-specific error occurs
+     * @throws IOException if an I/O error occurs
+     */
+    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
+            throws ServletException, IOException {
+        response.setContentType("application/json;charset=UTF-8");
+    }
+
+    // <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 {
+        processRequest(request, response);
+        outputResult(response, 900, null, null);
+    }
+
+    /**
+     * 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 {
+        processRequest(request, response);
+        
+        try {
+            
+            reqBody = function.getBody(request.getReader());
+            HashMap json = function.defragJSON(reqBody);
+            LDAP ldap = new LDAP((String) json.get("username"), (String) json.get("password"));
+            String requestId = (String) json.get("requestId");
+            req = requestId;
+            
+            System.out.println("============= "+req+" ============= << APS");
+        System.out.print(json);
+        System.out.println("********************************************************");
+            
+            switch((String) json.get("function")) {
+                case "authenticate":
+                    System.out.println("##### APS >> AUTHENTICATE");
+                    if((ldapError = ldap.userCheck()) == 0) {
+                        String[] keys = {"serviceType",
+                                         "serviceNumber",
+                                         "apiKey",
+                                         "deviceId",
+                                         "mail"};
+                        HashMap info = ldap.getUserInfo(keys);
+                        if(info.get("serviceType") != null) {
+                            info.put("serverURL", function.getURL("SAS"));
+                            info.put("appURL", function.getURL("APP"));
+                            info.put("storeURL", function.getURL("STORE"));
+                            outputResult(response, 0, requestId, info);
+                        } else {
+                            outputResult(response, 0, requestId, null);
+                        }
+                    }
+                    else {
+                        outputResult(response, ldapError, requestId, null);
+                    }
+                    break;
+                case "sendmail":
+                    System.out.println("##### APS >> SENDMAIL");
+                    if((ldapError = ldap.userCheck()) == 0) {
+                        String[] keys = {"mail"};
+                        MAIL mail = new MAIL();
+                        HashMap info = ldap.getUserInfo(keys);
+                        /*if(!info.get("mail").equals(json.get("email"))) {
+                            outputResult(response, 51, requestId, null);
+                            return;
+                        }*/
+                        if(!mail.check((String) info.get("mail"))) {
+                            outputResult(response, 51, requestId, null);
+                            return;
+                        }
+                        
+                        if(mail.send((String) info.get("mail"), (String) json.get("subject"), (String) json.get("text"))) {
+                            outputResult(response, 0, requestId, null);
+                        }
+                        else {
+                            outputResult(response, 50, requestId, null);
+                        }
+                    }
+                    else {
+                        outputResult(response, ldapError, requestId, null);
+                    }
+                    break;
+                case "register":
+                    System.out.println("##### APS >> REGISTER");
+                    if((ldapError = ldap.userCheck()) == 0) {
+                        String[] keys = {"serviceType",
+                                         "serviceNumber",
+                                         "notificationId",
+                                         "deviceId"};
+                        boolean state;
+                        for(String key : keys) {
+                            state = ldap.writeInfo(key, (String) json.get(key));
+                            if(!state) {
+                                outputResult(response, 82, requestId, null);
+                                return;
+                            }
+                        }
+                        outputResult(response, 0, requestId, null);
+                    }
+                    else {
+                        outputResult(response, ldapError, requestId, null);
+                    }
+                    break;
+            }
+        } catch (ParseException | NamingException ex) {
+            Logger.getLogger(APS.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    }
+private void outputResult(HttpServletResponse response, int errorCode, String requestId, HashMap extra) throws IOException {
+        JSONObject array = new JSONObject();
+        
+        array.put("result", errorCode);
+        array.put("resultText", code.getCodeText(errorCode));
+        array.put("requestId", requestId);
+        
+
+        //extra.forEach((k, v) -> System.out.println("key: "+k+" value:"+v));
+        if(extra != null) {
+            JSONObject userinfo = new JSONObject();
+            extra.forEach((k, v) -> userinfo.put(k, v));
+            array.put("userInfo", userinfo);
+        }
+        System.out.println("============= "+req+" ============= >> APS");
+        System.out.print(array);
+        System.out.println("********************************************************");
+         try (PrintWriter out = response.getWriter()) {
+            /* TODO output your page here. You may use following sample code. */
+            out.println(array);
+        } 
+    }
+}

+ 59 - 0
Java/ErrorCode.java

@@ -0,0 +1,59 @@
+
+import java.util.HashMap;
+
+
+
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+/**
+ *
+ * @author Deben
+ */
+public class ErrorCode {
+    public String getCodeText(int id) {
+        HashMap<Integer, String> list = new HashMap<>();
+        /* Runtime errors */
+        list.put(-1, "Unknown error code");
+        list.put(0, "OK");
+        list.put(1, "Refused");
+        list.put(50, "Failed to send mail");
+        list.put(51, "Incorrect mail adress");
+        list.put(52, "Mail not equal");
+        list.put(80, "Failed to connect to LDAP server");
+        list.put(81, "Error reading attribute");
+        list.put(82, "Error writing attribute");
+        
+        // Data errors
+        
+        list.put(500, "No data given");
+        list.put(555, "Unsupported function");
+        list.put(560, "Missing variables");
+        
+        //DB errors
+        list.put(600, "DB connection coun\'t be established");
+        list.put(601, "Failed to write to DB");
+        list.put(602, "Failed to read from DB");
+        
+        //LDAP errors
+        
+        list.put(700, "OK");
+        list.put(749, "Username / password incorrect");
+        
+        
+        /* User generated errors */
+        list.put(900, "GET request not Allowed");
+        list.put(901, "POST request not Allowed");
+        list.put(950, "Process timed out");
+        
+        if(list.get(id) != null) {
+            return list.get(id);
+        }
+        else {
+            return list.get(-1);
+        }
+    }
+}

+ 151 - 0
Java/Function.java

@@ -0,0 +1,151 @@
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashMap;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+/**
+ *
+ * @author Deben
+ */
+public class Function {
+    
+    
+    public HashMap defragJSON(String json) throws ParseException {
+        
+        String[] checkList = {"function",
+                              "requestId",
+                              "username",
+                              "password",
+                              "userInfo",
+                              "serviceType",
+                              "serviceNumber",
+                              "apiKey",
+                              "deviceId",
+                              "notificationId",
+                              "serverURL",
+                              "appURL",
+                              "storeURL",
+                              "confirmation",
+                              "result",
+                              "resultText",
+                              "email",
+                              "mail",
+                              "subject",
+                              "text"};
+        
+        HashMap<String, String> array = new HashMap();
+        
+        JSONParser parser = new JSONParser();
+        Object obj = parser.parse(json);
+        JSONObject jsonObject = (JSONObject) obj;
+        
+        boolean userInfo = jsonObject.containsKey("userInfo");
+        System.out.println(obj);
+        for(String key : checkList) {
+            if(key.equals("confirmation") && jsonObject.containsKey("confirmation")) {
+                if(!jsonObject.get(key).equals("approved")) {
+                    jsonObject.remove(key);
+                    jsonObject.put(key, "cancelled");
+                }
+            }
+            if(jsonObject.get(key) != null && !jsonObject.get(key).getClass().getName().equals("org.json.simple.JSONObject")) {
+                array.put(key, (String) jsonObject.get(key).toString());
+                //System.out.println(key+", "+jsonObject.get(key));
+            }
+            if(userInfo) {
+                JSONObject userObject = (JSONObject) jsonObject.get("userInfo");
+                if(userObject.get(key) != null) {
+                    if(key.equals("mail")) {
+                        array.put("email", (String) userObject.get(key));
+                        System.out.println("MAIL RENAME");
+                        continue;
+                    }
+                    array.put(key, (String) userObject.get(key).toString());
+                    //System.out.println("userInfo: "+key+", "+userObject.get(key));
+                }
+            }
+        }
+        return array;
+    }
+    public String getBody(BufferedReader br) throws IOException {
+        String tmp, body = "";
+        
+        while(null != (tmp = br.readLine())) {
+            body += tmp;
+        }
+        return body;
+    }
+    
+    public String getURL(String server) {
+        switch(server) {
+            case "ARS":
+                return "http://localhost:8080/Implementation/ARS";
+            case "SAS":
+                return "http://localhost:8080/Implementation/SAS";
+            case "APS":
+                return "http://localhost:8080/Implementation/APS";
+            case "APP":
+                return "http://test.com";
+            case "STORE":
+                return "http://google.com";
+            case "GCM":
+                return "https://android.googleapis.com/gcm/send";
+            case "APNS":
+                return "http://apple.com";
+            default:
+                return null;
+        }
+    }
+    public String makeRequest(String type, String url, String body) throws MalformedURLException, IOException {
+        URL obj = new URL(url);
+        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+        
+        
+        switch(type) {
+            case "GET":
+                return "";
+            case "POST":
+                con.setRequestMethod("POST");
+		con.setRequestProperty("content-type", "application/json");
+                
+                con.setDoOutput(true);
+		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
+                wr.writeBytes(body);
+		wr.flush();
+		wr.close();
+                
+                BufferedReader in = new BufferedReader(
+		        new InputStreamReader(con.getInputStream()));
+		String inputLine;
+		StringBuilder response = new StringBuilder();
+
+		while ((inputLine = in.readLine()) != null) {
+			response.append(inputLine);
+		}
+		in.close();
+                
+                System.out.println("============= makeRequest =============>> FUNCTION");
+        System.out.print(response.toString());
+        System.out.println("********************************************************");
+                
+                return response.toString();
+            default:
+                return null;
+        }
+    }
+    
+}

+ 13 - 0
Java/JSON.java

@@ -0,0 +1,13 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+/**
+ *
+ * @author Deben
+ */
+public class JSON {
+    
+}

+ 124 - 0
Java/LDAP.java

@@ -0,0 +1,124 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+import java.util.HashMap;
+import javax.naming.Context;
+import javax.naming.directory.DirContext;
+import javax.naming.ldap.LdapContext;
+import java.util.Hashtable;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.BasicAttribute;
+import javax.naming.directory.InitialDirContext;
+import javax.naming.directory.ModificationItem;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+
+
+/**
+ *
+ * @author Deben
+ */
+public class LDAP {
+    private static DirContext ctx;
+    private static String userName;
+    private static String passWord;
+
+    LDAP(String username, String password) throws NamingException {
+        Hashtable<String, String> env = new Hashtable();
+        
+        env.put(LdapContext.CONTROL_FACTORIES, "com.sun.jndi.ldap.ControlFactory");
+        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
+        env.put(Context.PROVIDER_URL, "ldap://192.168.2.240:389");
+        env.put(Context.SECURITY_AUTHENTICATION, "simple");
+        env.put(Context.SECURITY_PRINCIPAL, "VPN\\Administrator");
+        env.put(Context.SECURITY_CREDENTIALS, "Magnesium12");
+        
+        try {
+            ctx = new InitialDirContext(env);
+        }
+        catch(NamingException e) {
+            int errCode= getErrorCode(e.getMessage());
+            System.out.println("*** Conection with LDAP failed ("+username+", "+password+") Error: "+errCode+" ***");
+        }
+        userName = username;
+        passWord = password;
+    }
+    
+    public int userCheck() throws NamingException {
+        Hashtable tmpEnv = (Hashtable) ctx.getEnvironment().clone();
+        
+        tmpEnv.put(Context.SECURITY_PRINCIPAL, userName);
+        tmpEnv.put(Context.SECURITY_CREDENTIALS, passWord);
+        
+        try {
+            new InitialDirContext(tmpEnv);
+            return 0;
+        }
+        catch(NamingException e) {
+            return getErrorCode(e.toString()) + 700;
+        }
+    }
+    
+    public HashMap getUserInfo(String[] keys) throws NamingException {
+        SearchControls cons = new SearchControls();
+        cons.setSearchScope(SearchControls.SUBTREE_SCOPE);
+        cons.setReturningAttributes(keys);
+        
+        HashMap<String, String> array = new HashMap();
+        NamingEnumeration<SearchResult> answer = ctx.search("dc=vpn,dc=local", "sAMAccountName=" + userName, cons);
+        
+        if(answer.hasMore()) {
+            Attributes attrs = answer.next().getAttributes();
+            //System.out.println(attrs.get("serviceType").toString());
+            //array.put("serviceType", attrs.get("serviceType").toString());
+            
+            String tmp;
+            for(String key : keys) {
+                if(attrs.get(key) != null) {
+                    tmp = attrs.get(key).toString();
+                    array.put(key, tmp.substring(tmp.indexOf(":") + 2));
+                }
+                else {
+                    array.put(key, null);
+                }
+            }
+            return array;
+        }
+        return null;
+        
+    }
+    public boolean writeInfo(String key, String value) {
+        ModificationItem[] mods = new ModificationItem[1];
+        String name = "cn="+userName+",cn=Users,dc=vpn,dc=local";
+        
+        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
+          new BasicAttribute(key, value));
+        try {
+            ctx.modifyAttributes(name, mods);
+        }
+        catch(NamingException e){
+            System.out.println(e);
+            return false;
+        }
+        return true;
+    }
+    
+    private int getErrorCode(final String exceptionMsg)
+    {
+        String pattern="-?\\d+";
+        Pattern p=Pattern.compile(pattern);
+        Matcher  m=p.matcher(exceptionMsg);
+        if (m.find()) {
+            return Integer.valueOf(m.group(0));
+        }
+        return -1;
+    }
+
+}

+ 69 - 0
Java/MAIL.java

@@ -0,0 +1,69 @@
+
+import java.util.Properties;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.AddressException;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+/**
+ *
+ * @author Deben
+ */
+public class MAIL {
+    public boolean send(String mail, String subject, String body){
+        String to = mail;
+        String from = "deben1997@gmail.com";
+        Properties properties = System.getProperties();
+        properties.put("mail.smtp.port", "587");
+        properties.put("mail.smtp.auth", "true");
+        properties.put("mail.smtp.starttls.enable", "true");
+        
+        Session session = Session.getDefaultInstance(properties, null);
+        try{
+         // Create a default MimeMessage object.
+         MimeMessage message = new MimeMessage(session);
+
+         // Set From: header field of the header.
+         message.setFrom(new InternetAddress(from));
+
+         // Set To: header field of the header.
+         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
+
+         // Set Subject: header field
+         message.setSubject(subject);
+
+         // Send the actual HTML message, as big as you like
+         message.setContent(body, "text/html" );
+
+         // Send message
+         Transport transport = session.getTransport("smtp");
+         
+         transport.connect("smtp.gmail.com", "deben1997@gmail.com", "Beer1997");
+         transport.sendMessage(message, message.getAllRecipients());
+	 transport.close();
+         
+         return true;
+      }catch (MessagingException mex) {
+         return false;
+      }        
+    }
+   public boolean check(String mail) {
+       boolean result = true;
+       try {
+        InternetAddress emailAddr = new InternetAddress(mail);
+        emailAddr.validate();
+        } catch (AddressException ex) {
+            result = false;
+        }
+        return result;
+    }
+}

+ 294 - 0
Java/SAS.java

@@ -0,0 +1,294 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.naming.NamingException;
+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 org.json.simple.JSONObject;
+import org.json.simple.parser.ParseException;
+
+/**
+ *
+ * @author Deben
+ */
+@WebServlet(urlPatterns = {"/SAS"})
+public class SAS extends HttpServlet {
+
+    Function function = new Function();
+    ErrorCode code = new ErrorCode();
+    int ldapError;
+    SQL sql;
+    ResultSet result;
+    final Object T3 = new Object();
+    final Object T2 = new Object();
+    final Object T1 = new Object();
+    String req;
+    String reqBody;
+    int i;
+    int timeout = 60;
+    boolean finished = false;
+
+    public SAS() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
+        this.sql = (new SQL());
+    }
+    
+    
+    /**
+     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
+     * methods.
+     *
+     * @param request servlet request
+     * @param response servlet response
+     * @throws ServletException if a servlet-specific error occurs
+     * @throws IOException if an I/O error occurs
+     * @throws java.sql.SQLException
+     * @throws java.lang.InstantiationException
+     * @throws java.lang.IllegalAccessException
+     * @throws java.lang.ClassNotFoundException
+     */
+    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
+            throws ServletException, IOException, SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
+        response.setContentType("application/json;charset=UTF-8");
+        
+        
+    }
+
+    // <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 {
+            response.setContentType("application/json;charset=UTF-8");
+            
+            JSONObject json = new JSONObject();
+            json.put("result", 900);
+            json.put("resultText", code.getCodeText(900));
+            try (PrintWriter out = response.getWriter()) {
+                out.println(json);
+            } 
+            
+    }
+    @Override
+    protected void doPost(HttpServletRequest request, HttpServletResponse response)
+            throws ServletException, IOException {
+            response.setContentType("application/json;charset=UTF-8");
+            
+            
+            
+        try {
+            reqBody = function.getBody(request.getReader());
+            HashMap json = function.defragJSON(reqBody);
+            LDAP ldap = new LDAP((String) json.get("username"), (String) json.get("password"));
+            String requestId = (String) json.get("requestId");
+            String answer;
+            req = requestId;
+            
+            
+            
+            
+            System.out.println("============= "+req+" ============= << SAS");
+        System.out.print(json);
+        System.out.println("********************************************************");
+            
+            switch((String) json.get("function")) {
+                case "authenticate":
+                    sql.threadUpdate(requestId, "birth", null);
+                    System.out.println("##### SAS >> AUTHENTICATE");
+                    String tmpBody;
+                    JSONObject tmpJSON = new JSONObject();
+                        tmpJSON.put("function", "authenticate");
+                        tmpJSON.put("requestId", requestId);
+                        tmpJSON.put("username", (String) json.get("username"));
+                        tmpJSON.put("password", (String) json.get("password"));
+                    tmpBody = tmpJSON.toJSONString();
+
+                    HashMap jsonAnswer = function.defragJSON(function.makeRequest("POST", function.getURL("APS"), tmpBody));
+                    //System.out.print(jsonAnswer);
+                    if(jsonAnswer.get("result").equals("0")) {
+                        if(jsonAnswer.containsKey("serviceType")) {
+                            System.out.println("SENDING PUSH NOTIFICATION");
+                            tmpJSON = new JSONObject();
+                                tmpJSON.put("function", "notify");
+                                tmpJSON.put("requestId", requestId);
+                                tmpJSON.put("serviceType", (String) jsonAnswer.get("serviceType"));
+                                tmpJSON.put("serviceNumber", (String) jsonAnswer.get("serviceNumber"));
+                                tmpJSON.put("apiKey", (String) jsonAnswer.get("apiKey"));
+                                tmpJSON.put("deviceId", (String) jsonAnswer.get("deviceId"));
+                            tmpBody = tmpJSON.toJSONString();
+                            System.out.println("%%%%%%%%%%%%%%%");
+                            System.out.println((String) jsonAnswer.get("serviceType"));
+                            //function.defragJSON(function.makeRequest("POST", function.getURL((String) jsonAnswer.get("serviceType")), tmpBody));
+                            sql.threadUpdate(requestId, "request", null);
+                            for(i = 1; i<=timeout && !finished; i++) {
+                                result = sql.stmt.executeQuery("SELECT `state`, `data` FROM `thread` WHERE `threadId`='"+requestId+"'");
+                                //System.out.println("GOT RESULT");
+                                if(result.first()) {
+                                    //System.out.println("GOT VALID RESULT state: "+result.getString("state")+" || data: "+result.getString("data"));
+                                    if(result.getString("state").equals("repley")) {
+                                        //System.out.println("GOT REPLEY");
+                                        
+                                        if(result.getString("data") == null || result.getString("data").equals("") || result.getString("data").equals("null")) {
+                                            outputResult(response, 601, requestId, null, true);
+                                            finished = true;
+                                        } else {
+                                            outputResult(response, Integer.parseInt((String) jsonAnswer.get("result")), requestId, function.defragJSON(result.getString("data")), true);
+                                            finished = true;
+                                            break;
+                                        }
+                                    }
+                                    else {
+                                        System.out.println("WAITING "+i+" SECONDS");
+                                        Thread.sleep(1000);
+                                    }
+                                }
+                                else {
+                                    //System.out.println("GOT INVALID RESULT");
+                                    outputResult(response, 602, requestId, null, true);
+                                    finished = true;
+                                    break;
+                                }
+                                result = null;
+                            }
+                            System.out.println("WAITED "+i+" SECONDS");
+                            if(i > timeout) {
+                                outputResult(response, 950, requestId, null, true);
+                            }
+                            
+                        } else {
+                            System.out.println("SENDING EMAIL");
+                            tmpJSON = new JSONObject();
+                                tmpJSON.put("function", "sendmail");
+                                tmpJSON.put("requestId", requestId);
+                                tmpJSON.put("username", (String) json.get("username"));
+                                tmpJSON.put("password", (String) json.get("password"));
+                                tmpJSON.put("subject", "Enrollment for TFA");
+                                tmpJSON.put("text", "Dear Employee,<br><br>"
+                                    + "In order to login to our VPN server you need to download our app to verify your connection request.<br><br>"
+                                    + "For Android:<br><ol>"
+                                    + "<li>Download and install our app at: "+function.getURL("STORE")+"</li>"
+                                    + "<li>Start it: "+function.getURL("APP")+"</li></ol>"
+                                    + "We currently don't support iPhone. Sorry for the inconvience.<br><br>"
+                                    + "Regards,<br>"
+                                    + "The IT Security department");
+                            tmpBody = tmpJSON.toJSONString();
+                            jsonAnswer = function.defragJSON(function.makeRequest("POST", function.getURL("APS"), tmpBody));
+                            if(jsonAnswer.get("result").equals("0")) {
+                                    String state;
+                                    String data;
+                                    
+                                    for(i=1; i<=timeout && !finished; i++) {
+                                        result = sql.stmt.executeQuery("SELECT state,data FROM thread WHERE threadId='"+requestId+"'");
+                                        if(result.first()) {
+                                            state = result.getString("state");
+                                            data = result.getString("data");
+                                            if(state.equals("repley")) {
+                                                answer = function.makeRequest("POST", function.getURL("APS"), data);
+                                                outputResult(response, 0, requestId, null, true);
+                                                finished = true;
+                                            } else {
+                                                System.out.println("WAITING "+i+" SECONDS");
+                                                Thread.sleep(1000);
+                                            }
+                                            
+                                        } else {
+                                            outputResult(response, 602, requestId, null, true);
+                                            finished = true;
+                                        }
+                                    }
+                                    System.out.println("WAITED "+i+" SECONDS");
+                                    if(i > timeout) {
+                                        outputResult(response, 950, requestId, null, true);
+                                    }
+                            } else {
+                                outputResult(response, (int) jsonAnswer.get("result"), requestId, null, true);
+                                
+                            }
+                        }
+                    } else {
+                        outputResult(response, 1, requestId, null, true);
+                    }
+                    
+                    break;
+                case "register":
+                    System.out.println("##### SAS >> REGISTER");
+                    if((ldapError = ldap.userCheck()) == 0) {
+                        sql.threadUpdate(requestId, "repley", reqBody);
+                        outputResult(response, 0, requestId, null, false);
+                        /*result = sql.stmt.executeQuery("SELECT state,data FROM thread WHERE threadId='"+requestId+"'");
+                            if(result.first()) {
+                                int resultCode = result.getInt("result");
+                                outputResult(response, resultCode, requestId, null, false); 
+                            }
+                            else {
+                                outputResult(response, 602, requestId, null, true);
+                            }*/
+                    } else {
+                        outputResult(response, ldapError, requestId, null, true);
+                    }
+                    break;
+                case "confirm":
+                    System.out.println("##### SAS >> CONFIRM");
+                    //System.out.println("Body: "+reqBody);
+                    sql.threadUpdate(requestId, "repley", reqBody);
+                    //sql.stmt.execute("UPDATE thread set `state`='repley',`data`="+function.getBody(request.getReader())+" WHERE `threadId`='"+requestId+"'");
+                    outputResult(response, 0, requestId, null, false);
+                    break;
+            }
+        
+            
+            
+        } catch (ParseException | NamingException | SQLException | ClassNotFoundException | InterruptedException ex) {
+            Logger.getLogger(SAS.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        
+    }
+    private void outputResult(HttpServletResponse response, int errorCode, String requestId, HashMap extra, boolean terminate) throws IOException, SQLException, ClassNotFoundException {
+        JSONObject array = new JSONObject();
+        
+        array.put("result", errorCode);
+        array.put("resultText", code.getCodeText(errorCode));
+        array.put("requestId", requestId);
+        
+
+        //extra.forEach((k, v) -> System.out.println("key: "+k+" value:"+v));
+        if(extra != null) {
+            if(extra.containsKey("confirmation")) {
+                array.put("confirmation", extra.get("confirmation"));
+            } else {
+                JSONObject userinfo = new JSONObject();
+                extra.forEach((k, v) -> userinfo.put(k, v));
+                array.put("userInfo", userinfo);  
+            }
+        }
+        System.out.println("============= "+req+" ============= >> SAS");
+        System.out.print(array);
+        System.out.println("********************************************************");
+        if(terminate) {
+            sql.threadUpdate(requestId, "terminate", null);
+        }
+         try (PrintWriter out = response.getWriter()) {
+            /* TODO output your page here. You may use following sample code. */
+            out.println(array);
+        } 
+    }
+}

+ 43 - 0
Java/SQL.java

@@ -0,0 +1,43 @@
+import java.sql.*;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+public class SQL
+{
+  Connection conn = null;
+  Statement stmt = null;
+  SQL() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException
+  {
+      try {
+          // load the sqlite-JDBC driver using the current class loader
+          Class.forName("com.mysql.jdbc.Driver");
+          conn = DriverManager.getConnection("jdbc:mysql://192.168.2.240:3306/sas?user=Implementation&password=Test123456");
+          stmt = conn.createStatement();
+      } catch (ClassNotFoundException ex) {
+          Logger.getLogger(SQL.class.getName()).log(Level.SEVERE, null, ex);
+      }
+    }
+  public Statement Connect() {
+      return stmt;
+  }
+  public void threadUpdate(String threadId, String state, String data) throws SQLException, ClassNotFoundException {
+      switch (state) {
+          case "terminate":
+              
+              stmt.execute("DELETE FROM thread WHERE threadId='"+threadId+"'");
+              System.out.println("SQL ==> TERMINATE");
+              break;
+          case "birth":
+              
+              stmt.execute("INSERT INTO thread (threadId,state,`data`) VALUES ('"+threadId+"','"+state+"','"+data+"')");
+              System.out.println("SQL ==> BIRTH");
+              break;
+          default:
+              
+              stmt.execute("UPDATE thread set `state`='"+state+"',`data`='"+data+"' WHERE `threadId`='"+threadId+"'");
+              System.out.println("SQL ==> UPDATE");
+              break;
+      }
+  }
+}