List of usage examples for org.json.simple JSONObject writeJSONString
public void writeJSONString(Writer out) throws IOException
From source file:edu.vt.vbi.patric.portlets.PathwayTable.java
@SuppressWarnings("unchecked") public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { response.setContentType("application/json"); HashMap<String, String> key = new HashMap<>(); if (request.getParameter("id") != null) { key.put("feature_id", request.getParameter("id")); }// ww w .ja va2s . co m DataApiHandler dataApi = new DataApiHandler(request); int count_total = 0; JSONArray results = new JSONArray(); List<String> pathwayKeys = new ArrayList<>(); Map<String, Integer> mapOccurrence = new HashMap<>(); try { SolrQuery query = new SolrQuery("feature_id:" + request.getParameter("id")); query.setRows(dataApi.MAX_ROWS); String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); count_total = (Integer) respBody.get("numFound"); List<Map> sdl = (List<Map>) respBody.get("docs"); for (Map doc : sdl) { String pathwayKey = "(pathway_id:" + doc.get("pathway_id").toString() + " AND ec_number:" + doc.get("ec_number").toString() + ")"; pathwayKeys.add(pathwayKey); } SolrQuery queryRef = new SolrQuery(StringUtils.join(pathwayKeys, " OR ")); queryRef.setFields("pathway_id,ec_number,occurrence"); queryRef.setRows(pathwayKeys.size()); apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, queryRef); resp = jsonReader.readValue(apiResponse); respBody = (Map) resp.get("response"); List<Map> refList = (List<Map>) respBody.get("docs"); for (Map doc : refList) { mapOccurrence.put(doc.get("pathway_id") + "_" + doc.get("ec_number"), (Integer) doc.get("occurrence")); } for (Map doc : sdl) { JSONObject item = new JSONObject(); item.put("pathway_id", doc.get("pathway_id")); item.put("feature_id", doc.get("feature_id")); item.put("pathway_name", doc.get("pathway_name")); item.put("pathway_class", doc.get("pathway_class")); item.put("algorithm", doc.get("annotation")); item.put("ec_number", doc.get("ec_number")); item.put("ec_name", doc.get("ec_description")); item.put("taxon_id", doc.get("taxon_id")); item.put("genome_id", doc.get("genome_id")); item.put("occurrence", mapOccurrence.get(doc.get("pathway_id") + "_" + doc.get("ec_number"))); results.add(item); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } JSONObject jsonResult = new JSONObject(); try { jsonResult.put("total", count_total); jsonResult.put("results", results); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } PrintWriter writer = response.getWriter(); jsonResult.writeJSONString(writer); writer.close(); }
From source file:gwap.game.quiz.PlayNHighscoreCommunicationResource.java
private void sendJSONObject(JSONObject jsonObject) { OutputStream outstream = null; try {/* w w w .jav a2 s . co m*/ response.setContentType("text/plain"); outstream = response.getOutputStream(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outstream)); jsonObject.writeJSONString(out); out.flush(); outstream.flush(); outstream.close(); } catch (IOException e) { System.out.println("Exception!"); } }
From source file:br.unicamp.cotuca.dpd.pd12.acinet.vagalmail.servlet.Configuracoes.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); if (request.getRequestURI().contains("/pasta")) { String acao = request.getParameter("acao"), url = request.getParameter("url"), novo = request.getParameter("novo"); JSONObject obj = new JSONObject(); if (acao == null || url == null) { obj.put("erro", "Solicitao invlida"); obj.writeJSONString(response.getWriter()); return; }//from ww w . ja v a 2s . co m if ((acao.equals("renomear") || acao.equals("nova")) && novo == null) { obj.put("erro", "Solicitao invlida"); obj.writeJSONString(response.getWriter()); return; } try { Conta conta = (Conta) request.getSession().getAttribute("conta"); Store store = Logar.getImapStore(conta); Folder pasta = null; if (!acao.equals("nova")) { URLName urln = new URLName(url); pasta = store.getFolder(urln); if (pasta.isOpen()) pasta.close(false); } switch (acao) { case "renomear": if (pasta.renameTo(store.getFolder(novo))) { obj.put("sucesso", "Renomeado com sucesso"); } else { obj.put("erro", "Erro ao renomear a pasta"); } break; case "esvaziar": pasta.open(Folder.READ_WRITE); pasta.setFlags(1, pasta.getMessageCount(), new Flags(Flags.Flag.DELETED), true); pasta.expunge(); obj.put("sucesso", "Esvaziado com sucesso"); break; case "excluir": if (pasta.delete(true)) { obj.put("sucesso", "Excludo com sucesso"); } else { obj.put("erro", "Erro ao excluir a pasta"); } break; case "nova": pasta = store.getFolder(novo); if (!pasta.exists()) { if (pasta.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)) { obj.put("sucesso", "Criado com sucesso"); } else { obj.put("erro", "Erro ao criar a pasta"); } } else { obj.put("erro", "Erro ao criar a pasta"); } break; } } catch (MessagingException ex) { obj.put("erro", "Erro ao processar solicitao"); } obj.writeJSONString(response.getWriter()); return; } String metodo = request.getParameter("acao"); if (metodo == null) { return; } else if (metodo.equals("nova")) { EntityManager em = BD.getEntityManager(); try { em.getTransaction().begin(); Login usuario = Logar.getLogin(request.getSession()); Conta conta = new Conta(); conta.setEmail(request.getParameter("email")); conta.setImapHost(request.getParameter("imapHost")); conta.setImapPort(Integer.parseInt(request.getParameter("imapPort"))); conta.setImapPassword(request.getParameter("imapPassword")); conta.setImapUser(request.getParameter("imapLogin")); conta.setSmtpHost(request.getParameter("smtpHost")); conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort"))); conta.setSmtpPassword(request.getParameter("smtpPassword")); conta.setSmtpUser(request.getParameter("smtpLogin")); conta.setIdLogin(usuario); em.persist(conta); em.merge(usuario); em.getTransaction().commit(); em.refresh(conta); em.refresh(usuario); request.setAttribute("mensagem", "sucesso"); } catch (Logar.NaoAutenticadoException | PersistenceException ex) { em.getTransaction().rollback(); request.setAttribute("mensagem", "erro"); } request.getRequestDispatcher("/conf.jsp?metodo=nova").forward(request, response); } else if (metodo.equals("conta")) { EntityManager em = BD.getEntityManager(); try { em.getTransaction().begin(); Conta conta = (Conta) request.getSession().getAttribute("conta"); em.refresh(conta); conta.setEmail(request.getParameter("email")); conta.setImapHost(request.getParameter("imapHost")); conta.setImapPort(Integer.parseInt(request.getParameter("imapPort"))); conta.setImapPassword(request.getParameter("imapPassword")); conta.setImapUser(request.getParameter("imapLogin")); conta.setSmtpHost(request.getParameter("smtpHost")); conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort"))); conta.setSmtpPassword(request.getParameter("smtpPassword")); conta.setSmtpUser(request.getParameter("smtpLogin")); em.getTransaction().commit(); request.setAttribute("mensagem", "sucesso"); } catch (PersistenceException ex) { em.getTransaction().rollback(); request.setAttribute("mensagem", "erro"); } request.getRequestDispatcher("/conf.jsp?metodo=conta").forward(request, response); } else if (metodo.equals("senha")) { EntityManager em = BD.getEntityManager(); try { Login usuario = Logar.getLogin(request.getSession()); em.refresh(usuario); String senatu = request.getParameter("senAtu"), novasen = request.getParameter("senNova"), novasen2 = request.getParameter("senNova2"); if (novasen.equals(novasen2) && senatu.equals(usuario.getSenha())) { em.getTransaction().begin(); usuario.setSenha(novasen); em.getTransaction().commit(); request.setAttribute("mensagem", "sucesso"); } else { if (!novasen.equals(novasen2)) request.setAttribute("mensagem", "senneq"); else request.setAttribute("mensagem", "antsen"); } } catch (Logar.NaoAutenticadoException | PersistenceException ex) { em.getTransaction().rollback(); request.setAttribute("mensagem", "erro"); } request.getRequestDispatcher("/conf.jsp?metodo=senha").forward(request, response); } }
From source file:edu.vt.vbi.patric.portlets.SingleFIGfam.java
@SuppressWarnings("unchecked") public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { String callType = request.getParameter("callType"); if (callType != null) { Map<String, String> key = new HashMap<>(); if (callType.equals("saveState")) { String genomeIds = request.getParameter("genomeIds"); String familyIds = request.getParameter("familyIds"); String familyType = request.getParameter("familyType"); key.put("genomeIds", genomeIds); key.put("familyIds", familyIds); key.put("familyType", familyType); Random g = new Random(); long pk = g.nextLong(); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); PrintWriter writer = response.getWriter(); writer.write("" + pk); writer.close();/*from w w w . j a v a2 s .c om*/ } else if (callType.equals("getData")) { Map data = processFeatureTab(request); int numFound = (Integer) data.get("numFound"); List<GenomeFeature> features = (List<GenomeFeature>) data.get("features"); JSONArray docs = new JSONArray(); for (GenomeFeature feature : features) { docs.add(feature.toJSONObject()); } 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(); } else if (callType.equals("download")) { List<String> tableHeader = new ArrayList<>(); List<String> tableField = new ArrayList<>(); JSONArray tableSource = new JSONArray(); String fileName = "FeatureTable"; String fileFormat = request.getParameter("fileformat"); // features Map data = processFeatureTab(request); List<GenomeFeature> features = (List<GenomeFeature>) data.get("features"); for (GenomeFeature feature : features) { tableSource.add(feature.toJSONObject()); } tableHeader.addAll(DownloadHelper.getHeaderForFeatures()); tableField.addAll(DownloadHelper.getFieldsForFeatures()); ExcelHelper excel = new ExcelHelper("xssf", tableHeader, tableField, tableSource); excel.buildSpreadsheet(); if (fileFormat.equalsIgnoreCase("xlsx")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); excel.writeSpreadsheettoBrowser(response.getPortletOutputStream()); } else if (fileFormat.equalsIgnoreCase("txt")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); response.getPortletOutputStream().write(excel.writeToTextFile().getBytes()); } } } }
From source file:eumetsat.pn.common.ISO2JSON.java
private JSONObject convert(Document xmlDocument) throws XPathExpressionException, IOException { String expression = null;//w ww .j a va 2 s.co m String result = null; XPath xPath = XPathFactory.newInstance().newXPath(); JSONObject jsonObject = new JSONObject(); String xpathFileID = "//*[local-name()='fileIdentifier']/*[local-name()='CharacterString']"; String fileID = xPath.compile(xpathFileID).evaluate(xmlDocument); log.trace("{} >>> {}", xpathFileID, fileID); if (fileID != null) { jsonObject.put(FILE_IDENTIFIER_PROPERTY, fileID); } expression = "//*[local-name()='hierarchyLevelName']/*[local-name()='CharacterString']"; JSONArray list = new JSONArray(); NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { list.add(nodeList.item(i).getFirstChild().getNodeValue()); } if (list.size() > 0) { JSONObject hierarchies = parseThemeHierarchy((String) jsonObject.get(FILE_IDENTIFIER_PROPERTY), list); hierarchies.writeJSONString(writer); jsonObject.put("hierarchyNames", hierarchies); log.trace("{} >>> {}", expression, jsonObject.get("hierarchyNames")); } // Get Contact info String deliveryPoint = "//*[local-name()='address']//*[local-name()='deliveryPoint']/*[local-name()='CharacterString']"; String city = "//*[local-name()='address']//*[local-name()='city']/*[local-name()='CharacterString']"; String administrativeArea = "//*[local-name()='address']//*[local-name()='administrativeArea']/*[local-name()='CharacterString']"; String postalCode = "//*[local-name()='address']//*[local-name()='postalCode']/*[local-name()='CharacterString']"; String country = "//*[local-name()='address']//*[local-name()='country']/*[local-name()='CharacterString']"; String email = "//*[local-name()='address']//*[local-name()='electronicMailAddress']/*[local-name()='CharacterString']"; StringBuilder addressString = new StringBuilder(); StringBuilder emailString = new StringBuilder(); appendIfResultNotNull(xPath, xmlDocument, addressString, deliveryPoint); result = xPath.compile(postalCode).evaluate(xmlDocument); if (result != null) { addressString.append("\n").append(result.trim()); } result = xPath.compile(city).evaluate(xmlDocument); if (result != null) { addressString.append(" ").append(result.trim()); } result = xPath.compile(administrativeArea).evaluate(xmlDocument); if (result != null) { addressString.append("\n").append(result.trim()); } result = xPath.compile(country).evaluate(xmlDocument); if (result != null) { addressString.append("\n").append(result.trim()); } result = xPath.compile(email).evaluate(xmlDocument); if (result != null) { emailString.append(result.trim()); } HashMap<String, String> map = new HashMap<>(); map.put("address", addressString.toString()); map.put("email", emailString.toString()); jsonObject.put("contact", map); log.trace("contact: {}", Arrays.toString(map.entrySet().toArray())); // add identification info String abstractStr = "//*[local-name()='identificationInfo']//*[local-name()='abstract']/*[local-name()='CharacterString']"; String titleStr = "//*[local-name()='identificationInfo']//*[local-name()='title']/*[local-name()='CharacterString']"; String statusStr = "//*[local-name()='identificationInfo']//*[local-name()='status']/*[local-name()='MD_ProgressCode']/@codeListValue"; String keywords = "//*[local-name()='keyword']/*[local-name()='CharacterString']"; HashMap<String, Object> idMap = new HashMap<>(); result = xPath.compile(titleStr).evaluate(xmlDocument); if (result != null) { idMap.put("title", result.trim()); } result = xPath.compile(abstractStr).evaluate(xmlDocument); if (result != null) { idMap.put("abstract", result.trim()); } result = xPath.compile(statusStr).evaluate(xmlDocument); if (result != null) { idMap.put("status", result.trim()); } list = new JSONArray(); nodeList = (NodeList) xPath.compile(keywords).evaluate(xmlDocument, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { list.add(nodeList.item(i).getFirstChild().getNodeValue()); } if (list.size() > 0) { idMap.put("keywords", list); } jsonObject.put("identificationInfo", idMap); log.trace("idMap: {}", idMap); // get thumbnail product String browseThumbnailStr = "//*[local-name()='graphicOverview']//*[local-name()='MD_BrowseGraphic']//*[local-name()='fileName']//*[local-name()='CharacterString']"; result = xPath.compile(browseThumbnailStr).evaluate(xmlDocument); if (result != null) { idMap.put("thumbnail", result.trim()); log.trace("thumbnail: {}", result); } // add Geo spatial information String westBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='westBoundLongitude']/*[local-name()='Decimal']"; String eastBLonStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='eastBoundLongitude']/*[local-name()='Decimal']"; String northBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='northBoundLatitude']/*[local-name()='Decimal']"; String southBLatStr = "//*[local-name()='extent']//*[local-name()='geographicElement']//*[local-name()='southBoundLatitude']/*[local-name()='Decimal']"; // create a GeoJSON envelope object HashMap<String, Object> latlonMap = new HashMap<>(); latlonMap.put("type", "envelope"); JSONArray envelope = new JSONArray(); JSONArray leftTopPt = new JSONArray(); JSONArray rightDownPt = new JSONArray(); result = xPath.compile(westBLonStr).evaluate(xmlDocument); if (result != null) { leftTopPt.add(Double.parseDouble(result.trim())); } result = xPath.compile(northBLatStr).evaluate(xmlDocument); if (result != null) { leftTopPt.add(Double.parseDouble(result.trim())); } result = xPath.compile(eastBLonStr).evaluate(xmlDocument); if (result != null) { rightDownPt.add(Double.parseDouble(result.trim())); } result = xPath.compile(southBLatStr).evaluate(xmlDocument); if (result != null) { rightDownPt.add(Double.parseDouble(result.trim())); } envelope.add(leftTopPt); envelope.add(rightDownPt); latlonMap.put("coordinates", envelope); jsonObject.put("location", latlonMap); DOMImplementationLS domImplementation = (DOMImplementationLS) xmlDocument.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); String xmlString = lsSerializer.writeToString(xmlDocument); jsonObject.put("xmldoc", xmlString); return jsonObject; }
From source file:edu.vt.vbi.patric.portlets.TranscriptomicsGeneExp.java
@SuppressWarnings("unchecked") public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { response.setContentType("application/json"); String storeType = request.getParameter("storeType"); switch (storeType) { case "summary": { JSONObject jsonResult = this.processSummary(request); PrintWriter writer = response.getWriter(); jsonResult.writeJSONString(writer); writer.close();//from w w w .j a va 2 s . co m break; } case "summary_download": { List<String> tableHeader = new ArrayList<>(); List<String> tableField = new ArrayList<>(); // JSONArray tableSource = new JSONArray(); String fileName = "GeneExpression"; String fileFormat = request.getParameter("fileformat"); JSONObject jsonResult = this.processSummary(request); JSONArray tableSource = (JSONArray) jsonResult.get("features"); tableHeader.addAll(Arrays.asList("Platform", "Samples", "Locus Tag", "Title", "PubMed", "Accession", "Strain", "Gene Modification", "Experimental Condition", "Time Point", "Avg Intensity", "Log Ratio", "Z-score")); tableField.addAll(Arrays.asList("exp_platform", "exp_samples", "exp_locustag", "exp_name", "pmid", "exp_accession", "exp_strain", "exp_mutant", "exp_condition", "exp_timepoint", "exp_pavg", "exp_pratio", "exp_zscore")); ExcelHelper excel = new ExcelHelper("xssf", tableHeader, tableField, tableSource); excel.buildSpreadsheet(); if (fileFormat.equalsIgnoreCase("xlsx")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); excel.writeSpreadsheettoBrowser(response.getPortletOutputStream()); } else if (fileFormat.equalsIgnoreCase("txt")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); response.getPortletOutputStream().write(excel.writeToTextFile().getBytes()); } break; } case "correlation": { JSONObject jsonResult = this.processCorrelation(request); PrintWriter writer = response.getWriter(); jsonResult.writeJSONString(writer); writer.close(); break; } case "correlation_download": { List<String> tableHeader = new ArrayList<>(); List<String> tableField = new ArrayList<>(); // JSONArray tableSource = new JSONArray(); String fileName = "Correlated Genes"; String fileFormat = request.getParameter("fileformat"); JSONObject jsonResult = this.processCorrelation(request); JSONArray tableSource = (JSONArray) jsonResult.get("results"); tableHeader.addAll(Arrays.asList("Genome Name", "Accession", "PATRIC ID", "Alt Locus Tag", "RefSeq Locus Tag", "Gene Symbol", "Annotation", "Feature Type", "Start", "End", "Length(NT)", "Strand", "Protein ID", "Length(AA)", "Product Description", "Correlations", "Comparisons")); tableField.addAll(Arrays.asList("genome_name", "accession", "patric_id", "alt_locus_tag", "refseq_locus_tag", "gene", "annotation", "feature_type", "start", "end", "na_length", "strand", "protein_id", "aa_length", "product", "correlation", "count")); ExcelHelper excel = new ExcelHelper("xssf", tableHeader, tableField, tableSource); excel.buildSpreadsheet(); if (fileFormat.equalsIgnoreCase("xlsx")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); excel.writeSpreadsheettoBrowser(response.getPortletOutputStream()); } else if (fileFormat.equalsIgnoreCase("txt")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); response.getPortletOutputStream().write(excel.writeToTextFile().getBytes()); } break; } } }
From source file:gwap.game.quiz.PlayNCommunicationResource.java
private void doWork(HttpServletRequest request, HttpServletResponse response) throws IOException { // HttpSession session = request.getSession(); this.request = request; this.response = response; ses = request.getSession();//from ww w. j a v a 2 s . c o m SessionTracker.instance().add(ses); // } // give it ten trys to find a valid game configuration for (int ii = 0; ii < 10; ++ii) { JSONObject jsonObject = createJSONObjectForNewGame(); if (jsonObject != null) { jsonObject.put("SID", ses.getId()); InputStream instream = null; OutputStream outstream = null; try { instream = request.getInputStream(); response.setContentType("text/plain"); outstream = response.getOutputStream(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outstream)); jsonObject.writeJSONString(out); out.flush(); outstream.flush(); outstream.close(); instream.close(); logger.info("Successfully initialized game"); break; } catch (IOException e) { e.printStackTrace(); } } else { logger.info("Couldn't initialize a game in try no." + ii); } } }
From source file:com.theisleoffavalon.mcmanager.mobile.RestClient.java
/** * Sends a JSONRPC request/*from w w w.j av a2s .c o m*/ * * @param request * The request to send * @return The response */ private JSONObject sendJSONRPC(JSONObject request) { JSONObject ret = null; try { HttpURLConnection conn = (HttpURLConnection) this.rootUrl.openConnection(); conn.setRequestMethod("POST"); conn.setChunkedStreamingMode(0); conn.setDoInput(true); conn.setDoOutput(true); OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(conn.getOutputStream())); request.writeJSONString(osw); osw.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStreamReader isr = new InputStreamReader(new BufferedInputStream(conn.getInputStream())); ret = (JSONObject) new JSONParser().parse(isr); } else { Log.e("RestClient", String.format("Got %d instead of %d for HTTP Response", conn.getResponseCode(), HttpURLConnection.HTTP_OK)); return null; } } catch (IOException e) { Log.e("RestClient", "Error in sendJSONRPC", e); } catch (ParseException e) { Log.e("RestClient", "Parse return data error", e); } return ret; }
From source file:edu.vt.vbi.patric.proteinfamily.FIGfamData.java
@SuppressWarnings("unchecked") public void getLocusTags(ResourceRequest request, PrintWriter writer) { JSONArray arr = new JSONArray(); DataApiHandler dataApi = new DataApiHandler(request); try {//w w w .j a v a2 s .co m final String familyType = request.getParameter("familyType"); final String familyId = familyType + "_id"; SolrQuery solr_query = new SolrQuery(); solr_query.setQuery("genome_id:(" + request.getParameter("genomeIds") + ") AND " + familyId + ":(" + request.getParameter("familyIds") + ")"); solr_query.setFilterQueries("annotation:PATRIC AND feature_type:CDS"); solr_query.addField("feature_id,patric_id,refseq_locus_tag,alt_locus_tag"); solr_query.setRows(DataApiHandler.MAX_ROWS); LOGGER.debug("getLocusTags(): [{}] {}", SolrCore.FEATURE.toString(), solr_query); String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, solr_query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); List<GenomeFeature> features = dataApi.bindDocuments((List<Map>) respBody.get("docs"), GenomeFeature.class); for (GenomeFeature feature : features) { arr.add(feature.toJSONObject()); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } JSONObject data = new JSONObject(); data.put("data", arr); try { data.writeJSONString(writer); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } }
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;//from w ww . ja v a2s. c o 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; } } } }