Example usage for org.json.simple JSONObject writeJSONString

List of usage examples for org.json.simple JSONObject writeJSONString

Introduction

In this page you can find the example usage for org.json.simple JSONObject writeJSONString.

Prototype

public void writeJSONString(Writer out) throws IOException 

Source Link

Usage

From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java

public boolean createCacheFileTranscriptomics(String filePath) {
    boolean isSuccess = false;
    JSONObject jsonData = new JSONObject();
    JSONObject data;/*from w ww  .jav  a2s  .  c o  m*/

    // from WP
    // data
    data = read(baseURL + "/tab/dlp-transcriptomics-data/?req=passphrase");
    if (data != null) {
        jsonData.put("data", data);
    }
    // tools
    data = read(baseURL + "/tab/dlp-transcriptomics-tools/?req=passphrase");
    if (data != null) {
        jsonData.put("tools", data);
    }
    // process
    data = read(baseURL + "/tab/dlp-transcriptomics-process/?req=passphrase");
    if (data != null) {
        jsonData.put("process", data);
    }
    // download
    data = read(baseURL + "/tab/dlp-transcriptomics-download/?req=passphrase");
    if (data != null) {
        jsonData.put("download", data);
    }
    // topSpecies
    data = getTopSpeciesForTranscriptomics();
    if (data != null) {
        jsonData.put("topSpecies", data);
    }
    // featuredExperiment
    data = getFeaturedExperimentForTranscriptomics();
    if (data != null) {
        jsonData.put("featuredExperiment", data);
    }
    // popularGenomes
    data = getPopularGenomesForTranscriptomics();
    if (data != null) {
        jsonData.put("popularGenomes", data);
    }

    // save jsonData to file
    try (PrintWriter jsonOut = new PrintWriter(
            Files.newBufferedWriter(FileSystems.getDefault().getPath(filePath), Charset.defaultCharset()));) {
        jsonData.writeJSONString(jsonOut);
        isSuccess = true;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return isSuccess;
}

From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java

public boolean createCacheFileGenomes(String filePath) {
    boolean isSuccess = false;
    JSONObject jsonData = new JSONObject();
    JSONObject data;/*  www. ja va  2s . c o  m*/
    // from WP
    // data
    data = read(baseURL + "/tab/dlp-genomes-data/?req=passphrase");
    if (data != null) {
        jsonData.put("data", data);
    }
    // tools
    data = read(baseURL + "/tab/dlp-genomes-tools/?req=passphrase");
    if (data != null) {
        jsonData.put("tools", data);
    }
    // process
    data = read(baseURL + "/tab/dlp-genomes-process/?req=passphrase");
    if (data != null) {
        jsonData.put("process", data);
    }
    // download
    data = read(baseURL + "/tab/dlp-genomes-download/?req=passphrase");
    if (data != null) {
        jsonData.put("download", data);
    }
    // from solr or database
    // add popularGenomes
    data = getPopularGenomes();
    if (data != null) {
        jsonData.put("popularGenomes", data);
    }
    // add top5_1
    data = getTop5List("host_name");
    if (data != null) {
        jsonData.put("top5_1", data);
    }
    // add top5_2
    data = getTop5List("isolation_country");
    if (data != null) {
        jsonData.put("top5_2", data);
    }
    // add numberGenomes
    data = getGenomeCounts();
    if (data != null) {
        jsonData.put("numberGenomes", data);
    }

    // add genomeStatus
    data = getGenomeStatus();
    if (data != null) {
        jsonData.put("genomeStatus", data);
    }

    // save jsonData to file
    try (PrintWriter jsonOut = new PrintWriter(
            Files.newBufferedWriter(FileSystems.getDefault().getPath(filePath), Charset.defaultCharset()));) {
        jsonData.writeJSONString(jsonOut);
        isSuccess = true;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return isSuccess;
}

From source file:edu.vt.vbi.patric.portlets.CompPathwayTable.java

@SuppressWarnings("unchecked")
private void getFilterData(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {
    JSONObject val = new JSONObject();
    try {//w ww. j a  v a2 s  . com
        if (request.getParameter("val") != null) {
            LOGGER.trace("parsing param: {}", request.getParameter("val"));
            val = (JSONObject) (new JSONParser()).parse(request.getParameter("val"));
        }
    } catch (ParseException e) {
        LOGGER.error(e.getMessage(), e);
    }

    DataApiHandler dataApi = new DataApiHandler(request);
    JSONObject json = new JSONObject();

    String need = val.get("need") != null ? val.get("need").toString() : "";

    JSONObject defaultItem = new JSONObject();
    defaultItem.put("name", "ALL");
    defaultItem.put("value", "ALL");

    JSONArray items = new JSONArray();
    items.add(defaultItem);

    switch (need) {
    case "pathway":
        try {
            Map facets = dataApi.getPivotFacets(SolrCore.PATHWAY_REF, "*:*", null, "pathway_id,pathway_name");

            Map pivot = (Map) facets.get("pathway_id,pathway_name");

            for (Map.Entry entry : (Iterable<Map.Entry>) pivot.entrySet()) {

                Map entryValue = (Map) entry.getValue();
                String key = (String) entryValue.keySet().iterator().next();

                JSONObject item = new JSONObject();
                item.put("name", key);
                item.put("value", entry.getKey());

                items.add(item);
            }

            json.put(need, items);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        break;
    case "ec":
        try {
            Map facets = dataApi.getFieldFacets(SolrCore.PATHWAY_REF, "*:*", null, "ec_number");
            Map list = (Map) ((Map) facets.get("facets")).get("ec_number");

            for (Map.Entry entry : (Iterable<Map.Entry>) list.entrySet()) {
                JSONObject i = new JSONObject();
                i.put("name", entry.getKey());
                i.put("value", entry.getKey());

                items.add(i);
            }

            json.put(need, items);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        break;
    case "parent":
        try {
            Map facets = dataApi.getFieldFacets(SolrCore.PATHWAY_REF, "*:*", null, "pathway_class");
            Map list = (Map) ((Map) facets.get("facets")).get("pathway_class");

            for (Map.Entry entry : (Iterable<Map.Entry>) list.entrySet()) {
                JSONObject i = new JSONObject();
                i.put("name", entry.getKey());
                i.put("value", entry.getKey());

                items.add(i);
            }

            json.put(need, items);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        break;
    case "algorithm":
        JSONObject annotationPATRIC = new JSONObject();
        annotationPATRIC.put("name", "PATRIC");
        annotationPATRIC.put("value", "PATRIC");
        items.add(annotationPATRIC);

        json.put(need, items);
        break;
    }
    response.setContentType("application/json");
    json.writeJSONString(response.getWriter());
}

From source file:edu.vt.vbi.patric.portlets.TranscriptomicsGene.java

public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {
    String callType = request.getParameter("callType");

    if (callType != null) {
        switch (callType) {
        case "saveParams": {

            String keyword = request.getParameter("keyword");
            DataApiHandler dataApi = new DataApiHandler(request);

            Map<String, String> key = new HashMap<>();
            key.put("keyword", "locus_tag:(" + keyword + ") OR refseq_locus_tag:(" + keyword + ") ");
            key.put("fields", "pid");

            SolrQuery query = dataApi.buildSolrQuery(key, null, null, 0, -1, false);

            String apiResponse = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_GENE, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map) resp.get("response");

            List<Map> sdl = (List<Map>) respBody.get("docs");

            Set<String> sampleIds = new HashSet<>();

            for (Map doc : sdl) {
                sampleIds.add(doc.get("pid").toString());
            }//  www . j  av a  2  s  .c  o m

            String sId = StringUtils.join(sampleIds, ",");

            key = new HashMap();
            if (!keyword.equals("")) {
                key.put("keyword", keyword);
            }

            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();

            if (!sId.equals("")) {
                key.put("sampleId", sId);
                long pk = (new Random()).nextLong();

                SessionHandler.getInstance().set(SessionHandler.PREFIX + pk,
                        jsonWriter.writeValueAsString(key));

                writer.write("" + pk);
            } else {
                writer.write("");
            }
            writer.close();

            break;
        }
        case "getTables": {

            String expId = request.getParameter("expId");
            String sampleId = request.getParameter("sampleId");
            String wsExperimentId = request.getParameter("wsExperimentId");
            String wsSampleId = request.getParameter("wsSampleId");
            String keyword = request.getParameter("keyword");
            DataApiHandler dataApi = new DataApiHandler(request);

            JSONArray sample = new JSONArray();

            if ((sampleId != null && !sampleId.equals("")) || (expId != null && !expId.equals(""))) {

                String query_keyword = "";

                if (expId != null && !expId.equals("")) {
                    query_keyword += "eid:(" + expId.replaceAll(",", " OR ") + ")";
                }

                if (sampleId != null && !sampleId.equals("")) {
                    if (query_keyword.length() > 0) {
                        query_keyword += " AND ";
                    }
                    query_keyword += "pid:(" + sampleId.replaceAll(",", " OR ") + ")";
                }

                Map<String, String> key = new HashMap<>();
                key.put("keyword", query_keyword);
                key.put("fields", "pid,expname,expmean,timepoint,mutant,strain,condition");

                SolrQuery query = dataApi.buildSolrQuery(key, null, null, 0, -1, false);

                String apiResponse = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_COMPARISON, query);

                Map resp = jsonReader.readValue(apiResponse);
                Map respBody = (Map) resp.get("response");

                List<Map> sdl = (List<Map>) respBody.get("docs");

                for (final Map doc : sdl) {
                    final JSONObject item = new JSONObject(doc);
                    sample.add(item);
                }
            }

            // Read from JSON if collection parameter is there
            ExpressionDataCollection parser = null;
            if (wsExperimentId != null && !wsExperimentId.equals("")) {
                String token = getAuthorizationToken(request);

                parser = new ExpressionDataCollection(wsExperimentId, token);
                parser.read(ExpressionDataCollection.CONTENT_SAMPLE);
                if (wsSampleId != null && !wsSampleId.equals("")) {
                    parser.filter(wsSampleId, ExpressionDataCollection.CONTENT_SAMPLE);
                }
                // Append samples from collection to samples from DB
                sample = parser.append(sample, ExpressionDataCollection.CONTENT_SAMPLE);
            }

            String sampleList = "";
            sampleList += ((JSONObject) sample.get(0)).get("pid");

            for (int i = 1; i < sample.size(); i++) {
                sampleList += "," + ((JSONObject) sample.get(i)).get("pid");
            }

            JSONObject jsonResult = new JSONObject();
            jsonResult.put(ExpressionDataCollection.CONTENT_SAMPLE + "Total", sample.size());
            jsonResult.put(ExpressionDataCollection.CONTENT_SAMPLE, sample);
            JSONArray expression = new JSONArray();

            if ((sampleId != null && !sampleId.equals("")) || (expId != null && !expId.equals(""))) {

                String query_keyword = "";

                if (keyword != null && !keyword.equals("")) {
                    query_keyword += "(alt_locus_tag:(" + keyword + ") OR refseq_locus_tag:(" + keyword + ")) ";
                }

                if (expId != null && !expId.equals("")) {
                    if (query_keyword.length() > 0) {
                        query_keyword += " AND ";
                    }
                    query_keyword += "eid:(" + expId.replaceAll(",", " OR ") + ")";
                }

                if (sampleId != null && !sampleId.equals("")) {
                    if (query_keyword.length() > 0) {
                        query_keyword += " AND ";
                    }
                    query_keyword += "pid:(" + sampleId.replaceAll(",", " OR ") + ")";
                }

                Map<String, String> key = new HashMap<>();
                key.put("keyword", query_keyword);
                key.put("fields", "pid,refseq_locus_tag,feature_id,log_ratio,z_score");

                SolrQuery query = dataApi.buildSolrQuery(key, null, null, 0, -1, false);

                LOGGER.trace("getTables: [{}] {}", SolrCore.TRANSCRIPTOMICS_GENE.getSolrCoreName(), query);

                String apiResponse = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_GENE, query);

                Map resp = jsonReader.readValue(apiResponse);
                Map respBody = (Map) resp.get("response");

                List<Map> sdl = (List<Map>) respBody.get("docs");

                for (final Map doc : sdl) {
                    final JSONObject item = new JSONObject(doc);
                    expression.add(item);
                }

                // TODO: re-implement when data API removes limit 25k records
                int start = 0;
                int fetchedSize = sdl.size();
                while (fetchedSize == 25000) {
                    start += 25000;
                    query.setStart(start);

                    LOGGER.trace("getTables: [{}] {}", SolrCore.TRANSCRIPTOMICS_GENE.getSolrCoreName(), query);

                    final String apiResponseSub = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_GENE, query);
                    final Map respSub = jsonReader.readValue(apiResponseSub);
                    final Map respBodySub = (Map) respSub.get("response");

                    sdl = (List<Map>) respBodySub.get("docs");
                    fetchedSize = sdl.size();

                    for (final Map doc : sdl) {
                        final JSONObject item = new JSONObject(doc);
                        expression.add(item);
                    }
                }
            }

            if (wsExperimentId != null && !wsExperimentId.equals("")) {

                parser.read(ExpressionDataCollection.CONTENT_EXPRESSION);
                if (wsSampleId != null && !wsSampleId.equals(""))
                    parser.filter(wsSampleId, ExpressionDataCollection.CONTENT_EXPRESSION);

                // Append expression from collection to expression from DB
                expression = parser.append(expression, ExpressionDataCollection.CONTENT_EXPRESSION);
            }

            JSONArray stats = getExperimentStats(dataApi, expression, sampleList, sample);
            jsonResult.put(ExpressionDataCollection.CONTENT_EXPRESSION + "Total", stats.size());
            jsonResult.put(ExpressionDataCollection.CONTENT_EXPRESSION, stats);

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            jsonResult.writeJSONString(writer);
            writer.close();

            break;
        }
        case "doClustering": {

            String data = request.getParameter("data");
            String g = request.getParameter("g");
            String e = request.getParameter("e");
            String m = request.getParameter("m");
            String ge = request.getParameter("ge");
            String pk = request.getParameter("pk");
            String action = request.getParameter("action");

            String folder = "/tmp/";
            String filename = folder + "tmp_" + pk + ".txt";
            String output_filename = folder + "cluster_tmp_" + pk;
            try {

                PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)));
                out.write(data);
                out.close();

            } catch (Exception es) {
                LOGGER.error(es.getMessage(), es);
            }

            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            if (action.equals("Run"))
                writer.write(doCLustering(filename, output_filename, g, e, m, ge).toString());

            writer.close();

            break;
        }
        case "saveState": {

            String keyType = request.getParameter("keyType");
            String pageAt = request.getParameter("pageAt");
            String sampleFilter = request.getParameter("sampleFilter");
            String regex = request.getParameter("regex");
            String regexGN = request.getParameter("regexGN");
            String upFold = request.getParameter("upFold");
            String downFold = request.getParameter("downFold");
            String upZscore = request.getParameter("upZscore");
            String downZscore = request.getParameter("downZscore");
            String significantGenes = request.getParameter("significantGenes");
            String ClusterColumnOrder = request.getParameter("ClusterColumnOrder");
            String ClusterRowOrder = request.getParameter("ClusterRowOrder");
            String heatmapState = request.getParameter("heatmapState");
            String heatmapAxis = request.getParameter("heatmapAxis");
            String colorScheme = request.getParameter("colorScheme");
            String filterOffset = request.getParameter("filterOffset");

            Map<String, String> key = new HashMap<>();
            key.put("sampleFilter", (sampleFilter == null) ? "" : sampleFilter);
            key.put("pageAt", (pageAt == null) ? "" : pageAt);
            key.put("regex", (regex == null) ? "" : regex);
            key.put("regexGN", (regexGN == null) ? "" : regexGN);
            key.put("upFold", (upFold == null) ? "" : upFold);
            key.put("downFold", (downFold == null) ? "" : downFold);
            key.put("upZscore", (upZscore == null) ? "" : upZscore);
            key.put("downZscore", (downZscore == null) ? "" : downZscore);
            key.put("significantGenes", (significantGenes == null) ? "" : significantGenes);
            key.put("ClusterRowOrder", (ClusterRowOrder == null) ? "" : ClusterRowOrder);
            key.put("ClusterColumnOrder", (ClusterColumnOrder == null) ? "" : ClusterColumnOrder);
            key.put("heatmapState", (heatmapState == null) ? "" : heatmapState);
            key.put("heatmapAxis", (heatmapAxis == null) ? "" : heatmapAxis);
            key.put("colorScheme", (colorScheme == null) ? "" : colorScheme);
            key.put("filterOffset", (filterOffset == null) ? "" : filterOffset);

            long pk = (new Random()).nextLong();
            SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));

            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            writer.write("" + pk);
            writer.close();

            break;
        }
        case "getState": {

            String keyType = request.getParameter("keyType");
            String pk = request.getParameter("random");

            if ((pk != null) && (keyType != null)) {
                JSONArray results = new JSONArray();
                JSONObject a = new JSONObject();
                Map<String, String> key = jsonReader
                        .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
                if (key != null) {
                    a.put("sampleFilter", key.get("sampleFilter"));
                    a.put("pageAt", key.get("pageAt"));
                    a.put("regex", key.get("regex"));
                    a.put("regexGN", key.get("regexGN"));
                    a.put("upFold", key.get("upFold"));
                    a.put("downFold", key.get("downFold"));
                    a.put("upZscore", key.get("upZscore"));
                    a.put("downZscore", key.get("downZscore"));
                    a.put("significantGenes", key.get("significantGenes"));
                    a.put("ClusterRowOrder", key.get("ClusterRowOrder"));
                    a.put("ClusterColumnOrder", key.get("ClusterColumnOrder"));
                    a.put("heatmapState", key.get("heatmapState"));
                    a.put("heatmapAxis", key.get("heatmapAxis"));
                    a.put("colorScheme", key.get("colorScheme"));
                    a.put("filterOffset", key.get("filterOffset"));
                }
                results.add(a);
                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                results.writeJSONString(writer);
                writer.close();
            }
            break;
        }
        case "downloadFeatures": {
            String featureIds = request.getParameter("featureIds");
            String fileFormat = request.getParameter("fileFormat");
            String fileName = "Table_Gene";

            List<String> tableHeader = DownloadHelper.getHeaderForFeatures();
            List<String> tableField = DownloadHelper.getFieldsForFeatures();
            JSONArray tableSource = new JSONArray();

            DataApiHandler dataApi = new DataApiHandler(request);

            SolrQuery query = new SolrQuery("feature_id:(" + featureIds.replaceAll(",", " OR ") + ")");
            query.setFields(StringUtils.join(DownloadHelper.getFieldsForFeatures(), ","));
            query.setRows(dataApi.MAX_ROWS);

            LOGGER.trace("downloadFeatures: [{}] {}", SolrCore.FEATURE.getSolrCoreName(), query);

            final String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);

            final Map resp = jsonReader.readValue(apiResponse);
            final Map respBody = (Map) resp.get("response");

            final List<GenomeFeature> features = (List) dataApi.bindDocuments((List) respBody.get("docs"),
                    GenomeFeature.class);

            for (final GenomeFeature feature : features) {
                tableSource.add(feature.toJSONObject());
            }

            final 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 {
                response.setContentType("application/octetstream");
                response.addProperty("Content-Disposition",
                        "attachment; filename=\"" + fileName + "." + fileFormat + "\"");

                response.getWriter().write(excel.writeToTextFile());
            }
        }
        }
    }
}

From source file:edu.vt.vbi.patric.portlets.CompareRegionViewer.java

@SuppressWarnings("unchecked")
private void printTrackList(ResourceRequest request, ResourceResponse response) throws IOException {

    String contextType = request.getParameter("cType");
    String contextId = request.getParameter("cId");
    String pinFeatureSeedId = request.getParameter("feature"); // pin feature
    String windowSize = request.getParameter("window"); // window size

    int _numRegion = Integer.parseInt(request.getParameter("regions")); // number of genomes to compare
    int _numRegion_buffer = 10; // number of genomes to use as a buffer in case that PATRIC has no genome data,
    // which was retrieved from API
    String _key = "";

    DataApiHandler dataApi = new DataApiHandler(request);

    // if pin feature is not given, retrieve from the database based on na_feature_id
    if (pinFeatureSeedId == null
            && (contextType != null && contextType.equals("feature") && contextId != null)) {

        GenomeFeature feature = dataApi.getFeature(contextId);
        pinFeatureSeedId = feature.getPatricId();
    }// ww w . j av a 2  s .c o  m

    if (pinFeatureSeedId != null && !pinFeatureSeedId.equals("") && windowSize != null) {
        CRResultSet crRS = null;

        try {
            SAPserver sapling = new SAPserver("http://servers.nmpdr.org/pseed/sapling/server.cgi");
            crRS = new CRResultSet(pinFeatureSeedId, sapling.compared_regions(pinFeatureSeedId,
                    _numRegion + _numRegion_buffer, Integer.parseInt(windowSize) / 2));

            long pk = (new Random()).nextLong();
            _key = "" + pk;

            Gson gson = new Gson();
            SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, gson.toJson(crRS, CRResultSet.class));
            SessionHandler.getInstance().set(SessionHandler.PREFIX + "_windowsize" + pk, windowSize);

        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        JSONObject trackList = new JSONObject();
        JSONArray tracks = new JSONArray();
        JSONObject trStyle = new JSONObject();
        trStyle.put("className", "feature5");
        trStyle.put("showLabels", false);
        trStyle.put("label", "function( feature ) { return feature.get('patric_id'); }");
        JSONObject trHooks = new JSONObject();
        trHooks.put("modify",
                "function(track, feature, div) { div.style.backgroundColor = ['red','#1F497D','#938953','#4F81BD','#9BBB59','#806482','#4BACC6','#F79646'][feature.get('phase')];}");

        // query genome metadata
        SolrQuery query = new SolrQuery("genome_id:(" + StringUtils.join(crRS.getGenomeIds(), " OR ") + ")");
        query.setFields(
                "genome_id,genome_name,isolation_country,host_name,disease,collection_date,completion_date");
        query.setRows(_numRegion + _numRegion_buffer);

        String apiResponse = dataApi.solrQuery(SolrCore.GENOME, query);
        Map resp = jsonReader.readValue(apiResponse);
        Map respBody = (Map) resp.get("response");

        List<Genome> patricGenomes = dataApi.bindDocuments((List<Map>) respBody.get("docs"), Genome.class);

        int count_genomes = 1;
        if (crRS.getGenomeNames().size() > 0) {
            for (Integer idx : crRS.getTrackMap().keySet()) {
                if (count_genomes > _numRegion) {
                    break;
                }
                CRTrack crTrack = crRS.getTrackMap().get(idx);
                Genome currentGenome = null;
                for (Genome genome : patricGenomes) {
                    if (genome.getId().equals(crTrack.getGenomeID())) {
                        currentGenome = genome;
                    }
                }
                if (currentGenome != null) {
                    count_genomes++;
                    crRS.addToDefaultTracks(crTrack);
                    JSONObject tr = new JSONObject();
                    tr.put("style", trStyle);
                    tr.put("hooks", trHooks);
                    tr.put("type", "FeatureTrack");
                    tr.put("tooltip",
                            "<div style='line-height:1.7em'><b>{patric_id}</b> | {refseq_locus_tag} | {alt_locus_tag} | {gene}<br>{product}<br>{type}:{start}...{end} ({strand_str})<br> <i>Click for detail information</i></div>");
                    tr.put("urlTemplate",
                            "/portal/portal/patric/CompareRegionViewer/CRWindow?action=b&cacheability=PAGE&mode=getTrackInfo&key="
                                    + _key + "&rowId=" + crTrack.getRowID() + "&format=.json");
                    tr.put("key", crTrack.getGenomeName());
                    tr.put("label", "CR" + idx);
                    tr.put("dataKey", _key);
                    JSONObject metaData = new JSONObject();

                    if (currentGenome.getIsolationCountry() != null) {
                        metaData.put("Isolation Country", currentGenome.getIsolationCountry());
                    }
                    if (currentGenome.getHostName() != null) {
                        metaData.put("Host Name", currentGenome.getHostName());
                    }
                    if (currentGenome.getDisease() != null) {
                        metaData.put("Disease", currentGenome.getDisease());
                    }
                    if (currentGenome.getCollectionDate() != null) {
                        metaData.put("Collection Date", currentGenome.getCollectionDate());
                    }
                    if (currentGenome.getCompletionDate() != null) {
                        metaData.put("Completion Date", currentGenome.getCompletionDate());
                    }

                    tr.put("metadata", metaData);
                    tracks.add(tr);
                }
            }
        }
        trackList.put("tracks", tracks);

        JSONObject facetedTL = new JSONObject();
        JSONArray dpColumns = new JSONArray();
        dpColumns.addAll(Arrays.asList("key", "Isolation Country", "Host Name", "Disease", "Collection Date",
                "Completion Date"));
        facetedTL.put("displayColumns", dpColumns);
        facetedTL.put("type", "Faceted");
        facetedTL.put("escapeHTMLInData", false);
        trackList.put("trackSelector", facetedTL);
        trackList.put("defaultTracks", crRS.getDefaultTracks());

        response.setContentType("application/json");
        trackList.writeJSONString(response.getWriter());
        response.getWriter().close();
    } else {
        response.getWriter().write("{}");
    }
}

From source file:edu.vt.vbi.patric.portlets.CompPathwayMap.java

private void processHeatMap(ResourceRequest request, ResourceResponse response) throws IOException {

    DataApiHandler dataApi = new DataApiHandler(request);

    String genomeId, taxonId, algorithm, map;

    genomeId = request.getParameter("genomeId");
    taxonId = request.getParameter("taxonId");
    algorithm = request.getParameter("algorithm");
    map = request.getParameter("map");

    JSONObject json = new JSONObject();

    try {/* ww w . j  a  v  a 2s .c o m*/

        SolrQuery query = new SolrQuery("pathway_id:" + map);

        if (algorithm != null && !algorithm.equals("")) {
            query.addFilterQuery("annotation:" + algorithm);
        }

        if (taxonId != null && !taxonId.equals("")) {
            query.addFilterQuery(
                    SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "taxon_lineage_ids:" + taxonId));
        }
        if (genomeId != null && !genomeId.equals("")) {
            query.addFilterQuery(SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id",
                    "genome_id:(" + genomeId.replaceAll(",", " OR ") + ")"));
        }
        query.setRows(dataApi.MAX_ROWS).setFields("genome_id,annotation,ec_number,ec_description")
                .setFacet(true);
        // {stat:{field:{field:genome_ec,limit:-1,facet:{gene_count:\"unique(feature_id)\"}}}}
        query.add("json.facet", "{stat:{field:{field:genome_ec,limit:-1}}}}");

        LOGGER.debug("heatmap step 1: {}", query.toString());

        String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

        Map resp = jsonReader.readValue(apiResponse);
        Map respBody = (Map) resp.get("response");
        int numFound = (Integer) respBody.get("numFound");

        if (numFound > 0) {
            List<Map> buckets = (List<Map>) ((Map) ((Map) resp.get("facets")).get("stat")).get("buckets");

            respBody = (Map) resp.get("response");
            List<Map> sdl = (List<Map>) respBody.get("docs");

            Map<String, Integer> mapStat = new HashMap<>();
            for (Map value : buckets) {
                if (Integer.parseInt(value.get("count").toString()) > 0) {
                    mapStat.put(value.get("val").toString(), (Integer) value.get("count"));
                }
            }

            JSONArray items = new JSONArray();
            for (Map doc : sdl) {
                final JSONObject item = new JSONObject();
                item.put("genome_id", doc.get("genome_id"));
                item.put("algorithm", doc.get("annotation"));
                item.put("ec_number", doc.get("ec_number"));
                item.put("ec_name", doc.get("ec_description"));
                Integer count = mapStat.get(doc.get("genome_id") + "_" + doc.get("ec_number"));
                item.put("gene_count", String.format("%02x", count)); // 2-digit hex string

                items.add(item);
            }
            // if data exceeds limit, keep going
            int i = 1;
            while (sdl.size() == 25000) {
                query.setStart(25000 * i);
                apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

                resp = jsonReader.readValue(apiResponse);
                respBody = (Map) resp.get("response");
                sdl = (List<Map>) respBody.get("docs");

                for (Map doc : sdl) {
                    final JSONObject item = new JSONObject();
                    item.put("genome_id", doc.get("genome_id"));
                    item.put("algorithm", doc.get("annotation"));
                    item.put("ec_number", doc.get("ec_number"));
                    item.put("ec_name", doc.get("ec_description"));
                    Integer count = mapStat.get(doc.get("genome_id") + "_" + doc.get("ec_number"));
                    item.put("gene_count", String.format("%02x", count)); // 2-digit hex string

                    items.add(item);
                }
                i++;
            }

            json.put("data", items);
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    try {
        SolrQuery query = new SolrQuery("*:*");

        if (taxonId != null && !taxonId.equals("")) {
            query.addFilterQuery(
                    SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "taxon_lineage_ids:" + taxonId));
        }
        if (genomeId != null && !genomeId.equals("")) {
            query.addFilterQuery(SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id",
                    "genome_id:(" + genomeId.replaceAll(",", " OR ") + ")"));
        }
        if (algorithm != null && !algorithm.equals("")) {
            switch (algorithm) {
            case "PATRIC":
                query.addFilterQuery("patric_cds:[1 TO *]");
                break;
            case "RefSeq":
                query.addFilterQuery("refseq_cds:[1 TO *]");
                break;
            case "BRC1":
                query.addFilterQuery("brc1_cds:[1 TO *]");
                break;
            }
        }
        query.setFields("genome_id,genome_name").setRows(dataApi.MAX_ROWS).addSort("genome_name",
                SolrQuery.ORDER.asc);

        LOGGER.debug("step 2: [{}] {}", SolrCore.GENOME.getSolrCoreName(), query.toString());

        String apiResponse = dataApi.solrQuery(SolrCore.GENOME, query);

        Map resp = jsonReader.readValue(apiResponse);
        Map respBody = (Map) resp.get("response");
        List<Genome> genomes = dataApi.bindDocuments((List<Map>) respBody.get("docs"), Genome.class);

        JSONArray items = new JSONArray();
        for (Genome genome : genomes) {
            JSONObject item = new JSONObject();
            item.put("genome_id", genome.getId());
            item.put("genome_name", genome.getGenomeName());

            items.add(item);
        }

        json.put("genomes", items);

    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    response.setContentType("application/json");
    json.writeJSONString(response.getWriter());
}

From source file:edu.vt.vbi.patric.proteinfamily.FIGfamData.java

@SuppressWarnings("unchecked")
public void getGroupStats(ResourceRequest request, PrintWriter writer) throws IOException {

    DataApiHandler dataApi = new DataApiHandler(request);

    JSONObject figfams = new JSONObject();
    Set<String> figfamIdList = new HashSet<>();
    List<String> genomeIdList = new LinkedList<>();
    // get family Type
    final String familyType = request.getParameter("familyType");
    final String familyId = familyType + "_id";

    // get genome list in order
    String genomeIds = request.getParameter("genomeIds");
    try {//from  ww w  .  j a va  2 s.  c  o m
        SolrQuery query = new SolrQuery("genome_id:(" + genomeIds.replaceAll(",", " OR ") + ")");
        query.addSort("genome_name", SolrQuery.ORDER.asc).addField("genome_id")
                .setRows(DataApiHandler.MAX_ROWS);

        LOGGER.trace("[{}] {}", SolrCore.GENOME.getSolrCoreName(), query);

        String apiResponse = dataApi.solrQuery(SolrCore.GENOME, query);
        Map resp = jsonReader.readValue(apiResponse);
        Map respBody = (Map) resp.get("response");

        List<Genome> genomes = dataApi.bindDocuments((List<Map>) respBody.get("docs"), Genome.class);

        for (final Genome genome : genomes) {
            genomeIdList.add(genome.getId());
        }

        if (genomeIdList.size() == 25000) {
            query.setStart(25000);

            apiResponse = dataApi.solrQuery(SolrCore.GENOME, query);
            resp = jsonReader.readValue(apiResponse);
            respBody = (Map) resp.get("response");

            genomes = dataApi.bindDocuments((List<Map>) respBody.get("docs"), Genome.class);

            for (final Genome genome : genomes) {
                genomeIdList.add(genome.getId());
            }
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    //      LOGGER.debug("genomeIdList: {}", genomeIdList);

    // getting genome counts per figfamID (figfam)
    // {stat:{field:{field:figfam_id,limit:-1,facet:{min:"min(aa_length)",max:"max(aa_length)",mean:"avg(aa_length)",ss:"sumsq(aa_length)",sum:"sum(aa_length)",dist:"percentile(aa_length,50,75,99,99.9)",field:{field:genome_id}}}}}

    try {
        long start = System.currentTimeMillis();
        SolrQuery query = new SolrQuery("annotation:PATRIC AND feature_type:CDS");
        //         query.addFilterQuery("end:[3200 TO 4300] OR end:[4400 TO 4490] OR end:[4990 TO 4999]");
        query.addFilterQuery(getSolrQuery(request));
        query.addFilterQuery("!" + familyId + ":\"\"");
        query.setRows(0).setFacet(true).set("facet.threads", 15);
        query.add("json.facet", "{stat:{type:field,field:genome_id,limit:-1,facet:{figfams:{type:field,field:"
                + familyId + ",limit:-1,sort:{index:asc}}}}}");

        LOGGER.trace("getGroupStats() 1/3: [{}] {}", SolrCore.FEATURE.getSolrCoreName(), query);
        String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);

        long point = System.currentTimeMillis();
        LOGGER.debug("1st query: {} ms", (point - start));
        start = point;

        Map resp = jsonReader.readValue(apiResponse);
        Map facets = (Map) resp.get("facets");
        Map stat = (Map) facets.get("stat");

        final Map<String, String> figfamGenomeIdStr = new LinkedHashMap<>();
        final Map<String, Integer> figfamGenomeCount = new LinkedHashMap<>();

        final int genomeTotal = genomeIdList.size();
        final Map<String, Integer> genomePosMap = new LinkedHashMap<>();
        for (String genomeId : genomeIdList) {
            genomePosMap.put(genomeId, genomeIdList.indexOf(genomeId));
        }

        final Map<String, List> figfamGenomeIdCountMap = new ConcurrentHashMap<>();
        final Map<String, Set> figfamGenomeIdSet = new ConcurrentHashMap<>();

        List<Map> genomeBuckets = (List<Map>) stat.get("buckets");

        for (final Map bucket : genomeBuckets) {

            final String genomeId = (String) bucket.get("val");
            final List<Map> figfamBucket = (List<Map>) ((Map) bucket.get("figfams")).get("buckets");

            for (final Map figfam : figfamBucket) {
                final String figfamId = (String) figfam.get("val");
                final String genomeCount = String.format("%02x", (Integer) figfam.get("count"));

                if (figfamGenomeIdCountMap.containsKey(figfamId)) {
                    figfamGenomeIdCountMap.get(figfamId).set(genomePosMap.get(genomeId), genomeCount);
                } else {
                    final List<String> genomeIdCount = new LinkedList<>(Collections.nCopies(genomeTotal, "00"));
                    genomeIdCount.set(genomePosMap.get(genomeId), genomeCount);
                    figfamGenomeIdCountMap.put(figfamId, genomeIdCount);
                }

                if (figfamGenomeIdSet.containsKey(figfamId)) {
                    figfamGenomeIdSet.get(figfamId).add(genomeId);
                } else {
                    final Set<String> genomeIdSet = new HashSet<>();
                    genomeIdSet.add(genomeId);
                    figfamGenomeIdSet.put(figfamId, genomeIdSet);
                }
            }
        }

        for (String figfamId : figfamGenomeIdCountMap.keySet()) {
            final List genomeIdStr = figfamGenomeIdCountMap.get(figfamId);
            figfamGenomeIdStr.put(figfamId, StringUtils.join(genomeIdStr, ""));
            figfamGenomeCount.put(figfamId, figfamGenomeIdSet.get(figfamId).size());
        }

        point = System.currentTimeMillis();
        LOGGER.debug("1st query process : {} ms, figfamGenomeIdStr:{}, figfamGenomeCount:{}", (point - start),
                figfamGenomeIdStr.size(), figfamGenomeCount.size());

        long start2nd = System.currentTimeMillis();
        // 2nd query

        query.set("json.facet", "{stat:{type:field,field:" + familyId
                + ",limit:-1,facet:{min:\"min(aa_length)\",max:\"max(aa_length)\",mean:\"avg(aa_length)\",ss:\"sumsq(aa_length)\",sum:\"sum(aa_length)\"}}}");

        LOGGER.trace("getGroupStats() 2/3: [{}] {}", SolrCore.FEATURE.getSolrCoreName(), query);
        apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);

        point = System.currentTimeMillis();
        LOGGER.debug("2st query: {} ms", (point - start2nd));
        start2nd = point;

        resp = jsonReader.readValue(apiResponse);
        facets = (Map) resp.get("facets");
        stat = (Map) facets.get("stat");

        List<Map> buckets = (List<Map>) stat.get("buckets");

        for (Map bucket : buckets) {
            final String figfamId = (String) bucket.get("val");
            final int count = (Integer) bucket.get("count");

            double min, max, mean, sumsq, sum;
            if (bucket.get("min") instanceof Double) {
                min = (Double) bucket.get("min");
            } else if (bucket.get("min") instanceof Integer) {
                min = ((Integer) bucket.get("min")).doubleValue();
            } else {
                min = 0;
            }
            if (bucket.get("max") instanceof Double) {
                max = (Double) bucket.get("max");
            } else if (bucket.get("max") instanceof Integer) {
                max = ((Integer) bucket.get("max")).doubleValue();
            } else {
                max = 0;
            }
            if (bucket.get("mean") instanceof Double) {
                mean = (Double) bucket.get("mean");
            } else if (bucket.get("mean") instanceof Integer) {
                mean = ((Integer) bucket.get("mean")).doubleValue();
            } else {
                mean = 0;
            }
            if (bucket.get("ss") instanceof Double) {
                sumsq = (Double) bucket.get("ss");
            } else if (bucket.get("ss") instanceof Integer) {
                sumsq = ((Integer) bucket.get("ss")).doubleValue();
            } else {
                sumsq = 0;
            }
            if (bucket.get("sum") instanceof Double) {
                sum = (Double) bucket.get("sum");
            } else if (bucket.get("sum") instanceof Integer) {
                sum = ((Integer) bucket.get("sum")).doubleValue();
            } else {
                sum = 0;
            }

            //            LOGGER.debug("bucket:{}, sumsq:{}, count: {}", bucket, sumsq, count);
            double std;
            if (count > 1) {
                // std = Math.sqrt(sumsq / (count - 1));
                final double realSq = sumsq - (sum * sum) / count;
                std = Math.sqrt(realSq / (count - 1));
            } else {
                std = 0;
            }
            final JSONObject aaLength = new JSONObject();
            aaLength.put("min", min);
            aaLength.put("max", max);
            aaLength.put("mean", mean);
            aaLength.put("stddev", std);

            figfamIdList.add(figfamId);

            final JSONObject figfam = new JSONObject();
            figfam.put("genomes", figfamGenomeIdStr.get(figfamId));
            figfam.put("genome_count", figfamGenomeCount.get(figfamId));
            figfam.put("feature_count", count);
            figfam.put("stats", aaLength);

            figfams.put(figfamId, figfam);
        }

        point = System.currentTimeMillis();
        LOGGER.debug("2st query process: {} ms", (point - start2nd));
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    // getting distinct figfam_product
    if (!figfamIdList.isEmpty()) {

        figfamIdList.remove("");

        try {
            SolrQuery query = new SolrQuery("family_id:(" + StringUtils.join(figfamIdList, " OR ") + ")");
            query.addFilterQuery("family_type:" + familyType);
            query.addField("family_id,family_product").setRows(figfamIdList.size());

            LOGGER.debug("getGroupStats() 3/3: [{}] {}", SolrCore.FIGFAM_DIC.getSolrCoreName(), query);

            String apiResponse = dataApi.solrQuery(SolrCore.FIGFAM_DIC, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map) resp.get("response");

            List<Map> sdl = (List<Map>) respBody.get("docs");

            for (final Map doc : sdl) {
                final JSONObject figfam = (JSONObject) figfams.get(doc.get("family_id"));
                figfam.put("description", doc.get("family_product"));
                figfams.put(doc.get("family_id").toString(), figfam);
            }

            int i = 1;
            while (sdl.size() == 25000) {
                query.setStart(25000 * i);

                apiResponse = dataApi.solrQuery(SolrCore.FIGFAM_DIC, query);
                resp = jsonReader.readValue(apiResponse);
                respBody = (Map) resp.get("response");

                sdl = (List<Map>) respBody.get("docs");

                for (final Map doc : sdl) {
                    final JSONObject figfam = (JSONObject) figfams.get(doc.get("family_id"));
                    figfam.put("description", doc.get("family_product"));
                    figfams.put(doc.get("family_id").toString(), figfam);
                }
                i++;
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            LOGGER.debug("::getGroupStats() 3/3, params: {}", request.getParameterMap().toString());
        }
        figfams.writeJSONString(writer);
    }
}

From source file:edu.vt.vbi.patric.portlets.CompPathwayMap.java

private void processKeggMap(ResourceRequest request, ResourceResponse response) throws IOException {

    Map<String, String> key = new HashMap<>();

    DataApiHandler dataApi = new DataApiHandler(request);
    JSONObject ret = new JSONObject();
    JSONObject val = new JSONObject();
    try {//  w ww  .  j  a v a2  s  .  c  om
        val = (JSONObject) (new JSONParser()).parse(request.getParameter("val").toString());
    } catch (ParseException e) {
        LOGGER.error(e.getMessage(), e);
    }

    String need = val.get("need").toString();
    String genomeId = null, taxonId = null, map = null, pk = null;
    if (val.containsKey("genomeId") && val.get("genomeId") != null && !val.get("genomeId").equals("")) {
        genomeId = val.get("genomeId").toString();
    }

    if (val.containsKey("taxonId") && val.get("taxonId") != null && !val.get("taxonId").equals("")) {
        taxonId = val.get("taxonId").toString();
    }

    if (val.containsKey("map") && val.get("map") != null && !val.get("map").equals("")) {
        map = val.get("map").toString();
    }

    if (val.containsKey("pk") && val.get("pk") != null && !val.get("pk").equals("")) {
        pk = val.get("pk").toString();
    }

    if (need.equals("all")) {
        if (genomeId != null) {
            key.put("genomeId", genomeId);
        }
        if (taxonId != null) {
            key.put("taxonId", taxonId);
        }
        if (map != null) {
            key.put("map", map);
        }

        Map<String, String> sessKey = null;
        if (pk != null && !pk.isEmpty()) {
            sessKey = jsonReader.readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));
            if (sessKey != null && sessKey.containsKey("genomeId") && !sessKey.get("genomeId").equals("")) {
                genomeId = sessKey.get("genomeId");
            }
        }

        List<String> annotations = Arrays.asList("PATRIC", "RefSeq");

        // getting coordinates
        try {
            JSONArray listCoordinates = new JSONArray();

            for (String annotation : annotations) {
                Set<String> ecNumbers = new HashSet<String>();

                // step1. genome_count, feature_count
                // pathway/select?q=pathway_id:00053+AND+annotation:PATRIC&fq={!join+from=genome_id+to=genome_id+fromIndex=genome}taxon_lineage_ids:83332+AND+genome_status:(complete+OR+wgs)
                // &rows=0&facet=true&json.facet={stat:{field:{field:ec_number,limit:-1,facet:{genome_count:"unique(genome_id)",gene_count:"unique(feature_id)"}}}}

                SolrQuery query = new SolrQuery("pathway_id:" + map + " AND annotation:" + annotation);
                if (taxonId != null) {
                    query.addFilterQuery(SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id",
                            "taxon_lineage_ids:" + taxonId));
                }
                if (genomeId != null) {
                    query.addFilterQuery(SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id",
                            "genome_id:(" + genomeId.replaceAll(",", " OR ") + ")"));
                }
                query.setRows(0).setFacet(true);

                query.add("json.facet",
                        "{stat:{field:{field:ec_number,limit:-1,facet:{genome_count:\"unique(genome_id)\",gene_count:\"unique(feature_id)\"}}}}");

                LOGGER.debug("step 1. [{}] {}", SolrCore.PATHWAY.getSolrCoreName(), query);

                String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

                Map resp = jsonReader.readValue(apiResponse);
                Map respBody = (Map) resp.get("response");
                int numFound = (Integer) respBody.get("numFound");

                if (numFound > 0) {
                    List<Map> buckets = (List<Map>) ((Map) ((Map) resp.get("facets")).get("stat"))
                            .get("buckets");

                    Map<String, Map> mapStat = new HashMap<>();
                    for (Map value : buckets) {
                        if (Integer.parseInt(value.get("count").toString()) > 0) {
                            mapStat.put(value.get("val").toString(), value);
                            ecNumbers.add(value.get("val").toString());
                        }
                    }

                    // step2. coordinates, occurrence
                    // pathway_ref/select?q=pathway_id:00010+AND+map_type:enzyme%+AND+ec_number:("1.2.1.3"+OR+"1.1.1.1")&fl=ec_number,ec_description,map_location,occurrence

                    if (!ecNumbers.isEmpty()) {
                        query = new SolrQuery("pathway_id:" + map + " AND map_type:enzyme AND ec_number:("
                                + StringUtils.join(ecNumbers, " OR ") + ")");
                        query.setFields("ec_number,ec_description,map_location,occurrence");
                        query.setRows(dataApi.MAX_ROWS);

                        LOGGER.trace("genome_x_y: [{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query);

                        apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query);

                        resp = jsonReader.readValue(apiResponse);
                        respBody = (Map) resp.get("response");

                        List<Map> sdl = (List<Map>) respBody.get("docs");

                        for (Map doc : sdl) {
                            String ecNumber = doc.get("ec_number").toString();
                            Map stat = mapStat.get(ecNumber);

                            if (!stat.get("gene_count").toString().equals("0")) {

                                List<String> locations = (List<String>) doc.get("map_location");
                                for (String location : locations) {

                                    JSONObject coordinate = new JSONObject();
                                    coordinate.put("algorithm", annotation);
                                    coordinate.put("description", doc.get("ec_description"));
                                    coordinate.put("ec_number", ecNumber);
                                    coordinate.put("genome_count", stat.get("genome_count"));

                                    String[] loc = location.split(",");
                                    coordinate.put("x", loc[0]);
                                    coordinate.put("y", loc[1]);

                                    listCoordinates.add(coordinate);
                                }
                            }
                        }
                    }
                }
            }

            ret.put("genome_x_y", listCoordinates);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        // get pathways
        try {

            SolrQuery query = new SolrQuery("annotation:(" + StringUtils.join(annotations, " OR ") + ")");
            if (taxonId != null) {
                query.addFilterQuery(SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id",
                        "taxon_lineage_ids:" + taxonId));
            }
            if (genomeId != null) {
                query.addFilterQuery("genome_id:(" + genomeId.replaceAll(",", " OR ") + ")");
            }
            query.setFields("pathway_id,pathway_name,annotation").setRows(dataApi.MAX_ROWS);

            LOGGER.trace("genome_pathway_x_y: [{}] {}", SolrCore.PATHWAY.getSolrCoreName(), query);

            String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map) resp.get("response");

            List<Map> sdl = (List<Map>) respBody.get("docs");

            JSONArray listEnzymes = new JSONArray();
            Set<String> hash = new HashSet<>();

            for (Map doc : sdl) {
                // TODO: need to improve this using solr
                String hashKey = doc.get("pathway_id").toString() + ":" + doc.get("annotation").toString();

                if (!hash.contains(hashKey)) {

                    hash.add(hashKey);

                    JSONObject enzyme = new JSONObject();
                    enzyme.put("algorithm", doc.get("annotation"));
                    enzyme.put("map_id", doc.get("pathway_id"));
                    enzyme.put("map_name", doc.get("pathway_name"));

                    listEnzymes.add(enzyme);
                }
            }

            ret.put("genome_pathway_x_y", listEnzymes);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        // map_ids_in_map
        try {
            SolrQuery query = new SolrQuery("pathway_id:" + map + " AND map_type:path");
            query.setFields("ec_number,ec_description,map_location").setRows(dataApi.MAX_ROWS);

            LOGGER.trace("map_ids_in_map: [{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query);

            String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map) resp.get("response");

            List<Map> sdl = (List<Map>) respBody.get("docs");

            JSONArray listCoordinates = new JSONArray();
            for (Map doc : sdl) {
                List<String> locations = (List<String>) doc.get("map_location");
                for (String location : locations) {

                    JSONObject coordinate = new JSONObject();
                    coordinate.put("source_id", doc.get("ec_number"));

                    String[] loc = location.split(",");
                    coordinate.put("x", loc[0]);
                    coordinate.put("y", loc[1]);
                    coordinate.put("width", loc[2]);
                    coordinate.put("height", loc[3]);

                    listCoordinates.add(coordinate);
                }
            }

            ret.put("map_ids_in_map", listCoordinates);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        // all coordinates
        try {
            SolrQuery query = new SolrQuery("pathway_id:" + map + " AND map_type:enzyme");
            query.setFields("ec_number,ec_description,map_location").setRows(dataApi.MAX_ROWS);

            LOGGER.trace("all_coordinates: [{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query);

            String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map) resp.get("response");

            List<Map> sdl = (List<Map>) respBody.get("docs");

            JSONArray listCoordinates = new JSONArray();
            for (Map doc : sdl) {
                List<String> locations = (List<String>) doc.get("map_location");
                for (String location : locations) {

                    JSONObject coordinate = new JSONObject();
                    coordinate.put("ec", doc.get("ec_number"));
                    coordinate.put("description", doc.get("ec_description"));

                    String[] loc = location.split(",");
                    coordinate.put("x", loc[0]);
                    coordinate.put("y", loc[1]);

                    listCoordinates.add(coordinate);
                }
            }

            ret.put("all_coordinates", listCoordinates);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

    } else {
        // need: feature_id or ec_number
        JSONArray coordinates = new JSONArray();

        if (need.equals("ec_number")) {
            try {
                SolrQuery query = new SolrQuery("*:*");
                if (map != null) {
                    query.addFilterQuery("pathway_id:(" + map + ")");
                }

                LOGGER.trace("[{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query);

                String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query);

                Map resp = jsonReader.readValue(apiResponse);
                Map respBody = (Map) resp.get("response");

                List<Map> sdl = (List<Map>) respBody.get("docs");

                for (Map doc : sdl) {
                    List<String> locations = (List<String>) doc.get("map_location");

                    for (String loc : locations) {
                        JSONObject coordinate = new JSONObject();
                        coordinate.put("ec_number", doc.get("ec_number"));
                        String[] xy = loc.split(",");
                        coordinate.put("x", xy[0]);
                        coordinate.put("y", xy[1]);

                        coordinates.add(coordinate);
                    }
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
        } else {
            // feature
            String featureIds = null;
            if (val.containsKey("value") && val.get("value") != null && !val.get("value").equals("")) {
                featureIds = val.get("value").toString();
            }

            try {
                SolrQuery query = new SolrQuery("*:*");
                if (map != null) {
                    query.addFilterQuery("pathway_id:(" + map + ")");
                }
                if (featureIds != null) {
                    query.addFilterQuery(SolrCore.PATHWAY.getSolrCoreJoin("ec_number", "ec_number",
                            "feature_id:(" + featureIds.replaceAll(",", " OR ") + ")"));
                }

                LOGGER.trace("coordinates: [{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query);

                String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query);

                Map resp = jsonReader.readValue(apiResponse);
                Map respBody = (Map) resp.get("response");

                List<Map> sdl = (List<Map>) respBody.get("docs");

                for (Map doc : sdl) {
                    List<String> locations = (List<String>) doc.get("map_location");

                    for (String loc : locations) {
                        JSONObject coordinate = new JSONObject();
                        coordinate.put("ec_number", doc.get("ec_number"));
                        String[] xy = loc.split(",");
                        coordinate.put("x", xy[0]);
                        coordinate.put("y", xy[1]);

                        coordinates.add(coordinate);
                    }
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }

        ret.put("coordinates", coordinates);
    }

    response.setContentType("application/json");
    ret.writeJSONString(response.getWriter());
}

From source file:nl.strohalm.cyclos.http.RestFilter.java

@Override
@SuppressWarnings("unchecked")
protected void onError(final HttpServletRequest request, final HttpServletResponse response, final Throwable t)
        throws IOException {
    log(request, t);//from  w  ww .j  a va  2s .  c om
    LOG.error("Error on REST call", t);
    final Pair<ServerErrorVO, Integer> error = RestHelper.resolveError(t);
    final ServerErrorVO vo = error.getFirst();
    final JSONObject json = new JSONObject();
    if (StringUtils.isNotEmpty(vo.getErrorCode())) {
        json.put("errorCode", vo.getErrorCode());
    }
    if (StringUtils.isNotEmpty(vo.getErrorDetails())) {
        json.put("errorDetails", vo.getErrorDetails());
    }
    response.setStatus(error.getSecond());
    response.setContentType("application/json");
    json.writeJSONString(response.getWriter());
    response.flushBuffer();
}

From source file:org.alfresco.cacheserver.CacheServerIdentityImpl.java

private Data createData(File syncFile) throws IOException {
    String id = GUID.generate();// w w w .  j  av  a 2  s  .c  om
    Data data = new Data(id);
    JSONObject dataObject = toJSON(data);

    Writer writer = new FileWriter(syncFile);
    try {
        dataObject.writeJSONString(writer);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    return data;
}