List of usage examples for org.json.simple JSONObject toString
@Override
public String toString()
From source file:com.ba.forms.serviceBillForm.BAServiceBillAction.java
public ActionForward baView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject json = new JSONObject(); BAServiceBillDTO vo = new BAServiceBillDTO(); try {/*from w w w .j a v a 2 s. c o m*/ logger.info(" view method starts here"); vo.setServiceId((request.getParameter("serviceId"))); vo.setDateField(request.getParameter("dateField")); vo.setRoomId(request.getParameter("roomId")); vo.setCustomerName(request.getParameter("customerName")); vo.setOrderType((request.getParameter("orderType"))); vo.setAmount((request.getParameter("amount"))); vo.setServiceCharge((request.getParameter("serviceCharge"))); vo.setDiscount((request.getParameter("discount"))); vo.setServiceTax((request.getParameter("serviceTax"))); vo.setVat((request.getParameter("vat"))); vo.setNetAmount((request.getParameter("netAmount"))); vo.setPaymentMode((request.getParameter("paymentMode"))); vo.setBookingId((request.getParameter("bookingId"))); List hashMpServiceBillItemDet = BAServiceBillFactory.getInstanceOfBAServiceBillFactory() .getServiceBillDtls(1, vo); objPageCount = BAServiceBillFactory.getInstanceOfBAServiceBillFactory().getPageCount(vo); json.put("exception", ""); json.put("ServiceBillDets", hashMpServiceBillItemDet); json.put("ServiceBillExit", hashMpServiceBillItemDet.size()); json.put("objPageCount", objPageCount); // logger.warn("strCurrent PageNo ------------->"+objPageCount); } catch (Exception ex) { logger.error("The Exception is :" + ex); ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } response.getWriter().write(json.toString()); return null; }
From source file:gwap.rest.PastTerminaSessionBean.java
@GET @Produces(MediaType.APPLICATION_JSON)/*from w w w .j a va 2 s . c om*/ @Path("userResults") /** * * @param termName The name of the term in question. * @param owr if wrong tags of the player should be appended to the response. * @param fwr if wrong tags of other players should be appended to the response. * @param mon the maximal number of player tags in the response. * @param mfn the maximal number of tags of other players in the response. * @return the tags that the current player gave to the current term, the tags of the other players, etc. */ public Response getTaggingData(@QueryParam("term") String termName, @QueryParam("owr") String owr, @QueryParam("fwr") String fwr, @QueryParam("mon") String mon, @QueryParam("mfn") String mfn) { JSONObject jsonObject = new JSONObject(); setTermName(termName); setWrongRequests(fwr, owr); setMaxNodes(mfn, mon); if (term != null) { jsonObject.put("term", term.getTag().getName()); //own tags JSONArray owns = new JSONArray(); Query t = entityManager.createNamedQuery("tagging.answersByPersonAndResource"); t.setParameter("resourceId", term.getId()); t.setParameter("person", this.person); // t.setMaxResults(10); List<Tag> ownTags = t.getResultList(); ArrayList<String> ownTagNames = new ArrayList<String>(); for (Tag tag : ownTags) { ownTagNames.add(tag.getName()); } //foreign tags JSONArray foreigns = new JSONArray(); int[] minMaxAppearences = new int[2]; addToJSONArray(owns, foreigns, ownTagNames, minMaxAppearences, "tagging.topCorrectAnswersGeneral", "directMatch"); addToJSONArray(owns, foreigns, ownTagNames, minMaxAppearences, "tagging.topUnknownAnswersGeneral", "indirectMatch"); addToJSONArray(owns, foreigns, ownTagNames, minMaxAppearences, "tagging.topWrongAnswersGeneral", "WRONG"); JSONArray topics = getTopicOfTerm(); jsonObject.put("foreigns", foreigns); jsonObject.put("owns", owns); jsonObject.put("maxApp", minMaxAppearences[1]); jsonObject.put("minApp", minMaxAppearences[0]); jsonObject.put("topics", topics); } else { return Response.status(Status.BAD_REQUEST).build(); } return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).build(); }
From source file:edu.vt.vbi.patric.portlets.ProteomicsListPortlet.java
@SuppressWarnings("unchecked") public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { String sraction = request.getParameter("sraction"); if (sraction != null && sraction.equals("save_params")) { Map<String, String> key = new HashMap<>(); String taxonId = ""; String cType = request.getParameter("context_type"); String cId = request.getParameter("context_id"); if (cType != null && cId != null && cType.equals("taxon") && !cId.equals("")) { taxonId = cId;// w w w . jav a 2 s . co m } String keyword = request.getParameter("keyword"); String state = request.getParameter("state"); if (!taxonId.equalsIgnoreCase("")) { key.put("taxonId", taxonId); } if (keyword != null) { key.put("keyword", keyword.trim()); } if (state != null) { key.put("state", state); } long pk = (new Random()).nextLong(); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); PrintWriter writer = response.getWriter(); writer.write("" + pk); writer.close(); } else { String need = request.getParameter("need"); switch (need) { case "0": { String pk = request.getParameter("pk"); // Map data = processExperimentTab(request); Map<String, String> key = (Map) data.get("key"); int numFound = (Integer) data.get("numFound"); List<Map> sdl = (List<Map>) data.get("experiments"); JSONArray docs = new JSONArray(); for (Map doc : sdl) { JSONObject item = new JSONObject(); item.putAll(doc); docs.add(item); } if (data.containsKey("facets")) { JSONObject facets = FacetHelper.formatFacetTree((Map) data.get("facets")); key.put("facets", facets.toJSONString()); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); } JSONObject jsonResult = new JSONObject(); jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); jsonResult.writeJSONString(writer); writer.close(); break; } case "1": { String pk = request.getParameter("pk"); // Map data = processProteinTab(request); Map<String, String> key = (Map) data.get("key"); int numFound = (Integer) data.get("numFound"); List<Map> sdl = (List<Map>) data.get("proteins"); JSONArray docs = new JSONArray(); for (Map doc : sdl) { JSONObject item = new JSONObject(doc); docs.add(item); } if (data.containsKey("facets")) { JSONObject facets = FacetHelper.formatFacetTree((Map) data.get("facets")); key.put("facets", facets.toJSONString()); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); } JSONObject jsonResult = new JSONObject(); jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.write(jsonResult.toString()); writer.close(); break; } case "tree": { String pk = request.getParameter("pk"); String state; Map<String, String> key = jsonReader .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk)); if (key.containsKey("state")) state = key.get("state"); else state = request.getParameter("state"); key.put("state", state); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); JSONArray tree = new JSONArray(); try { if (!key.containsKey("facets") && !key.get("facets").isEmpty()) { JSONObject facet_fields = (JSONObject) new JSONParser().parse(key.get("facets")); DataApiHandler dataApi = new DataApiHandler(request); tree = FacetHelper.processStateAndTree(dataApi, SolrCore.PROTEOMICS_EXPERIMENT, key, need, facet_fields, key.get("facet"), state, null, 4); } } catch (ParseException e) { LOGGER.error(e.getMessage(), e); } response.setContentType("application/json"); PrintWriter writer = response.getWriter(); tree.writeJSONString(writer); writer.close(); break; } case "getFeatureIds": { String keyword = request.getParameter("keyword"); Map<String, String> key = new HashMap<>(); key.put("keyword", keyword); DataApiHandler dataApi = new DataApiHandler(request); SolrQuery query = dataApi.buildSolrQuery(key, null, null, 0, -1, false); String apiResponse = dataApi.solrQuery(SolrCore.PROTEOMICS_PROTEIN, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); JSONObject object = new JSONObject(respBody); // solr.setCurrentInstance(SolrCore.PROTEOMICS_PROTEIN); // JSONObject object = null; //solr.getData(key, null, facet, 0, -1, false, false, false); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); object.writeJSONString(writer); // writer.write(object.get("response").toString()); writer.close(); break; } case "getPeptides": { String experiment_id = request.getParameter("experiment_id"); String na_feature_id = request.getParameter("na_feature_id"); Map<String, String> key = new HashMap<>(); key.put("keyword", "na_feature_id:" + na_feature_id + " AND experiment_id:" + experiment_id); key.put("fields", "peptide_sequence"); DataApiHandler dataApi = new DataApiHandler(request); SolrQuery query = dataApi.buildSolrQuery(key, null, null, 0, -1, false); String apiResponse = dataApi.solrQuery(SolrCore.PROTEOMICS_PEPTIDE, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); JSONObject object = new JSONObject(); object.putAll(respBody); // solr.setCurrentInstance(SolrCore.PROTEOMICS_PEPTIDE); // JSONObject object = solr.getData(key, null, facet, 0, -1, false, false, false); // object = (JSONObject) object.get("response"); object.put("aa", FASTAHelper.getFASTASequence(request, Arrays.asList(na_feature_id), "protein")); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); object.writeJSONString(writer); writer.close(); break; } } } }
From source file:com.splunk.logging.HttpEventCollectorSender.java
@SuppressWarnings("unchecked") private String serializeEventInfo(HttpEventCollectorEventInfo eventInfo) { // create event json content ///*from www. j av a 2 s .co m*/ // cf: http://dev.splunk.com/view/event-collector/SP-CAAAE6P // JSONObject event = new JSONObject(); // event timestamp and metadata putIfPresent(event, MetadataTimeTag, String.format(Locale.US, "%.3f", eventInfo.getTime())); putIfPresent(event, MetadataHostTag, metadata.get(MetadataHostTag)); putIfPresent(event, MetadataIndexTag, metadata.get(MetadataIndexTag)); putIfPresent(event, MetadataSourceTag, metadata.get(MetadataSourceTag)); putIfPresent(event, MetadataSourceTypeTag, metadata.get(MetadataSourceTypeTag)); // event body JSONObject body = new JSONObject(); putIfPresent(body, "severity", eventInfo.getSeverity()); putIfPresent(body, "message", eventInfo.getMessage()); putIfPresent(body, "logger", eventInfo.getLoggerName()); putIfPresent(body, "thread", eventInfo.getThreadName()); // add an exception record if and only if there is one // in practice, the message also has the exception information attached if (eventInfo.getExceptionMessage() != null) { putIfPresent(body, "exception", eventInfo.getExceptionMessage()); } final JSONObject throwableJson = writeThrowableInfoToJson(eventInfo.getThrowableInfo()); if (throwableJson != null) { body.put("throwable", throwableJson); } // add properties if and only if there are any final Map<String, String> props = eventInfo.getProperties(); if (props != null && !props.isEmpty()) { body.put("properties", props); } // add marker if and only if there is one final Serializable marker = eventInfo.getMarker(); if (marker != null) { putIfPresent(body, "marker", marker.toString()); } // join event and body event.put("event", body); return event.toString(); }
From source file:control.ProcesoVertimientosServlets.InsertarProgramacionMonitoreo.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w. j a v a2s. co m * @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 { JSONObject respError = new JSONObject(); try { //Obtenemos el numero de contrato String consultorMonitoreo = request.getParameter("consultorMonitoreo"); String fechaMonitoreo = request.getParameter("fechaMonitoreo"); String horaInicioMonitoreo = request.getParameter("horaInicioMonitoreo"); String horaFinMonitoreo = request.getParameter("horaFinMonitoreo"); int laboratorioMonitoreo = Integer.parseInt(request.getParameter("laboratorioMonitoreo")); int codigoProceso = Integer.parseInt(request.getParameter("codigoProceso")); String observacion = request.getParameter("observacionesReprogramacion"); String duracionMonitoreo = request.getParameter("duracionMonitoreo"); //Insertamos el programacion del monitoreo y obtenemos el codigo ProgramarMonitoreo manager = new ProgramarMonitoreo(); int codigoMonitoreo = manager.insertar(consultorMonitoreo, fechaMonitoreo, horaInicioMonitoreo, horaFinMonitoreo, laboratorioMonitoreo, codigoProceso, observacion, duracionMonitoreo); //Obtenemos la cadena con la informacion y la convertimos en un //JSONArray String puntos = request.getParameter("puntosVertimiento"); Object obj = JSONValue.parse(puntos); JSONArray jsonArray = new JSONArray(); jsonArray = (JSONArray) obj; //Recorremos el JSONArray y obtenemos la informacion. for (int i = 0; i < jsonArray.size(); i++) { //Obtenemos la info de los puntos JSONObject jsonObject = (JSONObject) jsonArray.get(i); int codigoPunto = Integer.parseInt((String) jsonObject.get("codigo")); int codigoActividad = Integer.parseInt((String) jsonObject.get("actividad")); //Creamos el manager y guardamos la informacion. manager.insertarPuntoMonitoreo(codigoPunto, codigoActividad, codigoMonitoreo); } respError.put("error", "1"); response.getWriter().write(respError.toString()); } catch (Exception ex) { respError.put("error", "0"); response.getWriter().write(respError.toString()); } }
From source file:com.ba.forms.receipt.BAReceiptAction.java
public ActionForward getPageRecords(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject json = new JSONObject(); BAReceiptDTO vo = new BAReceiptDTO(); try {//from w ww . j a v a2s.co m logger.info(" getpageRecords method starts here"); vo.setTransNo((request.getParameter("transNo"))); vo.setDate(request.getParameter("date")); vo.setType(request.getParameter("type")); vo.setBookingId(request.getParameter("bookingId")); vo.setCustomerName((request.getParameter("customerName"))); vo.setRoomId(request.getParameter("roomId")); vo.setReceipt((request.getParameter("receipt"))); vo.setMode(request.getParameter("mode")); String strNavigation = request.getParameter("navigation"); int strCurrentPageNo = Integer.parseInt(request.getParameter("currentPageNo")); if (strNavigation != null && !strNavigation.equals("")) { if (strNavigation.equals("pre")) { strCurrentPageNo = strCurrentPageNo - 1; if (strCurrentPageNo <= 0) strCurrentPageNo = 1; } else if (strNavigation.equals("next")) { strCurrentPageNo = strCurrentPageNo + 1; if (strCurrentPageNo > objPageCount) strCurrentPageNo = objPageCount; } } logger.info("strCurrent PageNo ------------->" + strCurrentPageNo); List hashMpReceiptDet = BAReceiptFactory.getInstanceOfBAReceiptFactory() .getReceiptDtls(strCurrentPageNo, vo); json.put("exception", ""); json.put("ReceiptDets", hashMpReceiptDet); json.put("ReceiptExit", hashMpReceiptDet.size()); } catch (Exception ex) { logger.error("The Exception is :" + ex); ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } response.getWriter().write(json.toString()); return null; }
From source file:com.caspida.plugins.graph.EntityGraphNeo4jPlugin.java
/** * request =//w w w .j a v a 2 s .c om * sourceType: User * sourceId: 123 * targetTypes: ["Anomaly", "Device", "Application"] * depth: 1, 2 etc * * response = * nodes [] * nodeId: unique node id * type: Anomaly , User, etc * objectId: Anomaly, User, Device or Application id (the Mysql one) * label: user name, etc * score * properties: depending on the type. * Device type should have a "deviceType" property (Laptop, Handset etc); * Anomaly type should have "anomalyType" property. * annotation * hasChildren: boolean, indicates whether the node is expandable * * links [] * linkId: unique link id * sourceId: source node id * targetId: target node id * weight: a value from 1 to 10, indicates how strong the relation is (most used machines vs occasional etc) * annotation * * @param graphDb * @param sourceType * @param depthIn * @param sourceId * @return */ @Name("getneighborhood") @Description("Get a node's neighborhood") @PluginTarget(GraphDatabaseService.class) public String getUserNeighborhood(@Source GraphDatabaseService graphDb, @Description("Array of users as a JSON string ") @Parameter(name = "sourceType") String sourceType, @Parameter(name = "depth") Integer depthIn, @Parameter(name = "minScore", optional = true) Integer minScoreIn, @Parameter(name = "sourceId") String sourceId ) { JSONArray nodes = new JSONArray(); JSONArray edges = new JSONArray(); JSONObject response = new JSONObject(); Integer minScore = (minScoreIn != null) ? minScoreIn.intValue() : 0; Integer depth = (depthIn != null) ? depthIn.intValue() : 0; String namespace = EntityGraphConstants.UBER_ENTITY_GRAPH_NAMESPACE; logger.info("Got arguments: sourceType {} depth {} sourceId {} namespace {}", sourceType, depth, sourceId, namespace); try (Transaction txn = graphDb.beginTx()) { Index<Node> nodeIndex = graphDb.index().forNodes(EntityGraphConstants.EVENT_CLASS); Node node = nodeIndex.get(EntityGraphConstants.NODE_ID, Long.parseLong(sourceId)).getSingle(); if (node != null && depth != 0) { walkNbrGraph(node, null, depth, nodes, edges, minScore); } } response.put("nodes", nodes); response.put("links", edges); logger.debug("Reponse : {}", response.toJSONString()); return response.toString(); }
From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java
/** * Build a value from a mapping array and a data record * @param mappingArrayJson/*from www .j ava2s. c o m*/ * @param record * @return result or Null if any column is empty * @throws Exception */ private String buildMappingString(JSONArray mappingArrayJson, ArrayList<String> record) throws Exception { String ret = ""; // loop through the mapping array Iterator<JSONObject> it = mappingArrayJson.iterator(); for (int i = 0; i < mappingArrayJson.size(); i++) { JSONObject mapItem = (JSONObject) mappingArrayJson.get(i); if (mapItem.containsKey("textId")) { String text = null; // get text id String id = mapItem.get("textId").toString(); // look up text try { text = this.textsAvailable.get(id); } catch (Exception e) { throw new Exception("Failed to look up textId: " + id); } // if all is well, append the value if (!StringUtils.isEmpty(text)) { ret += text; } } else if (mapItem.containsKey("colId")) { String colText = null; Integer pos = null; String id = mapItem.get("colId").toString(); try { String textColLabel = this.colsAvailable.get(id); pos = this.headerPositioningInfo.get(textColLabel); colText = record.get(pos); // set the text equal to the correct column. } catch (Exception e) { colText = ""; if (pos == null) { throw new Exception("Cannot find column in header list."); } } if (!StringUtils.isBlank(colText)) { ret += this.applyTransforms(colText, mapItem); } else { // found an empty column return null; } } else { throw new Exception("importSpec mapping item has no known type: " + mapItem.toString()); } } return ret; }
From source file:com.ba.masters.configuration.BAConfigurationAction.java
public ActionForward getPageRecords(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject json = new JSONObject(); BAConfigurationDTO vo = new BAConfigurationDTO(); try {/*from ww w . j a v a 2 s .c o m*/ logger.info("get page records starts"); vo.setOrder((request.getParameter("order"))); vo.setCheckOutTime(request.getParameter("checkOutTime")); vo.setCompany(request.getParameter("company")); vo.setAddress(request.getParameter("address").toString().trim()); vo.setSmsId((request.getParameter("smsId"))); vo.setPassword(request.getParameter("password")); vo.setEmail((request.getParameter("email"))); vo.setPop(request.getParameter("pop")); vo.setSmtp(request.getParameter("smtp")); String strNavigation = request.getParameter("navigation"); int strCurrentPageNo = Integer.parseInt(request.getParameter("currentPageNo")); if (strNavigation != null && !strNavigation.equals("")) { if (strNavigation.equals("pre")) { strCurrentPageNo = strCurrentPageNo - 1; if (strCurrentPageNo <= 0) strCurrentPageNo = 1; } else if (strNavigation.equals("next")) { strCurrentPageNo = strCurrentPageNo + 1; if (strCurrentPageNo > objPageCount) strCurrentPageNo = objPageCount; } } logger.info("strCurrent PageNo ------------->" + strCurrentPageNo); List hashMpConfigurationDet = BAConfigurationFactory.getInstanceOfBAConfigurationFactory() .getConfigurationDtls(strCurrentPageNo, vo); json.put("exception", ""); json.put("ConfigurationDets", hashMpConfigurationDet); json.put("ConfigurationExit", hashMpConfigurationDet.size()); } catch (Exception ex) { logger.error("The Exception is :" + ex); ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } response.getWriter().write(json.toString()); return null; }
From source file:com.mythesis.userbehaviouranalysis.ProfileAnalysis.java
/** * finds the profiles that match user's interests given his web history * @param userID the user's id/*from w w w . java 2 s. co m*/ * @param history the user's web history * @param input a txt file that contains the necessary parameters */ public void perform(String userID, String[] history, File input) { System.out.println("total urls = " + history.length); //default parameters //number of random queries for each profile int numQueriesSuggestion = 5; //number of random webpages per query to suggest - total number of suggestions = // numQueriesSuggestion*pagesPerQuerySuggestion int pagesPerQuerySuggestion = 1; //number of random queries to return as examples for alternatives profiles int numQueriesExample = 2; //we get the current date/time DateTime current = new DateTime(); DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm"); String timestamp = fmt.print(current); //update user info - i'll store the results when i'll perform the last analysis Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("profileAnalysis"); DBCollection userinfo = db.getCollection("userinfo"); BasicDBObject newDocument = new BasicDBObject(); newDocument.put("$set", new BasicDBObject().append("timestamp", timestamp)); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("userID", userID); userinfo.update(searchQuery, newDocument, true, false); //read the neccessary parameters Utils utils = new Utils(); utils.readInput(input); HashMap<String, ArrayList<String>> wordvectors = utils.wordvectors; HashMap<String, String> crawlerOutputPaths = utils.crawlerOutputPaths; //get the urls' content ArrayList<String> webpages = new ArrayList<>(); ArrayList<String> urls = new ArrayList<>(); for (int i = 0; i < history.length; i++) { WebParser pageParser = new WebParser(history[i]); pageParser.parse(); String content = pageParser.getContent(); if ("".equals(content) || content == null) continue; webpages.add(content); urls.add(history[i]); } //calculate the urls' scores HashMap<String, double[]> historyScores = new HashMap<>(); String[] webpagesArr = new String[webpages.size()]; webpagesArr = webpages.toArray(webpagesArr); String[] urlsArr = new String[urls.size()]; urlsArr = urls.toArray(urlsArr); for (String profile : wordvectors.keySet()) { Scorer scorer = new Scorer(webpagesArr, urlsArr, wordvectors.get(profile)); double[] semanticScores = scorer.getSemanticScores(); double[] relevanceScores = scorer.getRelevanceScores(); double[] confidenceScores = scorer.getConfidenceScores(); double[] scores = scoreFormula(semanticScores, relevanceScores, confidenceScores); historyScores.put(profile, scores); } //find the maximum score of every url and get summation of the scores for each profile HashMap<String, Double> userProfilesScore = new HashMap<>(); for (int i = 0; i < webpages.size(); i++) { double max = 0.0; String info = "undefined"; for (String profile : historyScores.keySet()) { if (historyScores.get(profile)[i] > max) { max = historyScores.get(profile)[i]; info = profile; } } if (!"undefined".equals(info)) { Double prevscore = userProfilesScore.get(info); userProfilesScore.put(info, (prevscore == null) ? max : prevscore + max); } } //find which profile level has maximum score e.g. if football/level=0 score is greater //than football/level=1 score then the user is better described as a football/level=0 user HashMap<String, Double> userProfileScores = new HashMap<>(); HashMap<String, String> userProfileLevels = new HashMap<>(); for (String s : userProfilesScore.keySet()) { String[] info = s.split("/"); Double prevscore = userProfileScores.get(info[0] + "/" + info[1] + "/"); if (prevscore == null) { userProfileScores.put(info[0] + "/" + info[1] + "/", userProfilesScore.get(s)); userProfileLevels.put(info[0] + "/" + info[1] + "/", info[2]); } else if (userProfilesScore.get(s) > prevscore) { userProfileScores.put(info[0] + "/" + info[1] + "/", userProfilesScore.get(s)); userProfileLevels.put(info[0] + "/" + info[1] + "/", info[2]); } } //put the final profiles together in this simple form: domain/profile/level of expertise and rank them Double totalScore = 0.0; for (String s : userProfileScores.keySet()) totalScore += userProfileScores.get(s); Map<String, Double> userProfiles = new HashMap<>(); for (String s : userProfileLevels.keySet()) userProfiles.put(s + userProfileLevels.get(s), round(userProfileScores.get(s) * 100 / totalScore, 2)); userProfiles = sortByValue(userProfiles); //find page suggestions for every profile HashMap<String, ArrayList<String>> pageSuggestions = new HashMap<>(); for (String profile : userProfiles.keySet()) { String path = crawlerOutputPaths.get(profile); ArrayList<String> suggestions = getSuggestions(path, numQueriesSuggestion, pagesPerQuerySuggestion, history); pageSuggestions.put(profile, suggestions); } //find alternative profiles for every profile and representative queries HashMap<String, HashMap<String, ArrayList<String>>> alternativeProfiles = new HashMap<>(); for (String userProfile : userProfiles.keySet()) { String[] userProfileInfo = userProfile.split("/"); HashMap<String, ArrayList<String>> profileQueries = new HashMap<>(); for (String profile : wordvectors.keySet()) { String[] profileInfo = profile.split("/"); if (profileInfo[0].equals(userProfileInfo[0]) && profileInfo[1].equals(userProfileInfo[1]) && !profileInfo[2].equals(userProfileInfo[2])) { String path = crawlerOutputPaths.get(profile); ArrayList<String> queries = getQueries(path, numQueriesExample); for (int i = 0; i < queries.size(); i++) { String query = queries.get(i); queries.set(i, query.substring(query.lastIndexOf("\\") + 1).replace("-query", "") .replace("+", " ")); } profileQueries.put(profile, queries); } } alternativeProfiles.put(userProfile, profileQueries); } //prepare JSON response JSONObject response = new JSONObject(); response.put("userID", userID); response.put("timestamp", timestamp); JSONArray list = new JSONArray(); for (String profile : userProfiles.keySet()) { JSONObject profileInfo = new JSONObject(); profileInfo.put("profile", profile); profileInfo.put("score", userProfiles.get(profile)); JSONArray temp = new JSONArray(); ArrayList<String> suggestions = pageSuggestions.get(profile); for (String s : suggestions) temp.add(s); profileInfo.put("suggestions", temp); JSONArray alternativesArray = new JSONArray(); for (String s : alternativeProfiles.get(profile).keySet()) { JSONObject alternativeInfo = new JSONObject(); alternativeInfo.put("alternative", s); ArrayList<String> queries = alternativeProfiles.get(profile).get(s); JSONArray queriesArray = new JSONArray(); for (String str : queries) { queriesArray.add(str); } alternativeInfo.put("queries", queriesArray); alternativesArray.add(alternativeInfo); } profileInfo.put("alternatives", alternativesArray); list.add(profileInfo); } response.put("profiles", list); System.out.println("JSON response is ready: " + response); //delete previous analysis and store results DBCollection collection = db.getCollection("history"); BasicDBObject previous = new BasicDBObject(); previous.put("userID", userID); collection.remove(previous); DBObject dbObject = (DBObject) JSON.parse(response.toString()); collection.insert(dbObject); System.out.println("I saved the analysis..."); }