com.mythesis.userbehaviouranalysis.RequestServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.mythesis.userbehaviouranalysis.RequestServlet.java

Source

/* 
 * Copyright 2015 Konstantinos Papangelou.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mythesis.userbehaviouranalysis;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
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 org.joda.time.DateTime;
import org.joda.time.Duration;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * a class that responds to requests from client
 * @author Konstantinos Papangelou
 */
public class RequestServlet extends HttpServlet {
    /**
     * 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 {

        String userPath = request.getServletPath();
        String params = request.getQueryString().split("=")[1];
        System.out.println("I'm going to send the analysis to " + request.getQueryString());

        if (userPath.equals("/analysis")) {
            Mongo mongo = new Mongo("localhost", 27017);
            DB db = mongo.getDB("profileAnalysis");
            DBCollection userinfo = db.getCollection("history");
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("userID", params);
            DBCursor cursor = userinfo.find(searchQuery);
            if (cursor.hasNext()) {
                String entry = cursor.next().toString();
                System.out.println(entry);
                response.setHeader("Access-Control-Request-Method", "GET");
                response.setContentType("application/json");
                response.getWriter().write(entry);
            }
        }

    }

    /**
     * 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 {
        String userPath = request.getServletPath();
        File input = new File("D://UserBehaviourAnalysisInput.txt");
        ProfileAnalysis analysis = new ProfileAnalysis();
        switch (userPath) {
        // if history is sent
        case "/history":
            String id = request.getParameter("userID");
            String[] urls = request.getParameter("urls").split(",");

            Mongo mongo = new Mongo("localhost", 27017);
            DB db = mongo.getDB("profileAnalysis");
            DBCollection userinfo = db.getCollection("userinfo");
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("userID", id);
            DBCursor cursor = userinfo.find(searchQuery);
            if (cursor.hasNext()) {
                DateTime current = new DateTime();
                SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
                DBObject entry = cursor.next();
                String check = (String) entry.get("timestamp");
                Date temp = null;
                try {
                    temp = format.parse(check);
                } catch (ParseException ex) {
                    Logger.getLogger(RequestServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                DateTime previous = new DateTime(temp);
                System.out.println("last history analysis on: " + previous);
                System.out.println("current date/time: " + current);
                Duration duration = new Duration(previous, current);
                if (duration.getStandardHours() < 24)
                    break;
            }
            analysis.perform(id, urls, input);
            break;
        // if query is sent    
        case "/query":
            try {
                JSONObject data = new JSONObject(request.getParameter("data"));
                Iterator it = data.keys();

                ArrayList<String> profiles = new ArrayList<>();
                ArrayList<String> queries = new ArrayList<>();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    profiles.add(key);
                    queries.add((String) data.get(key));
                }
                analysis.storeQueries(profiles, queries, input);
            } catch (JSONException ex) {
                Logger.getLogger(RequestServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            break;
        }
    }

}