Example usage for org.apache.solr.client.solrj SolrQuery setRows

List of usage examples for org.apache.solr.client.solrj SolrQuery setRows

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj SolrQuery setRows.

Prototype

public SolrQuery setRows(Integer rows) 

Source Link

Usage

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

License:Apache License

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

    String contextType = request.getParameter("cType");
    String contextId = request.getParameter("cId");

    DataApiHandler dataApi = new DataApiHandler(request);
    SolrQuery query = new SolrQuery();

    if (contextType.equals("genome")) {
        query.setQuery("genome_id:" + contextId);
    } else if (contextType.equals("feature")) {
        query.setQuery(SolrCore.FEATURE.getSolrCoreJoin("genome_id", "genome_id", "feature_id:" + contextId));
    }/* w  w  w .  j  av a 2 s  . c  o m*/
    query.setRows(dataApi.MAX_ROWS).addSort("accession", SolrQuery.ORDER.asc);

    JSONArray jsonResult = new JSONArray();

    LOGGER.trace("[{}] {}", SolrCore.SEQUENCE.getSolrCoreName(), query.toString());
    String apiResponse = dataApi.solrQuery(SolrCore.SEQUENCE, query);
    Map resp = jsonReader.readValue(apiResponse);
    Map respBody = (Map) resp.get("response");

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

    for (GenomeSequence sequence : sequences) {

        JSONObject seq = new JSONObject();
        seq.put("length", sequence.getLength());
        seq.put("name", sequence.getAccession());
        seq.put("accn", sequence.getAccession());
        //         seq.put("sid", sequence.getId());
        seq.put("sid", sequence.getGenomeId());
        seq.put("start", 0);
        seq.put("end", sequence.getLength());
        seq.put("seqDir", "");
        seq.put("seqChunkSize", sequence.getLength());

        jsonResult.add(seq);
    }

    // TODO: remove this when data API limit is removed
    int i = 1;
    while (sequences.size() == 25000) {
        query.setStart(25000 * i);

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

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

        for (GenomeSequence sequence : sequences) {

            JSONObject seq = new JSONObject();
            seq.put("length", sequence.getLength());
            seq.put("name", sequence.getAccession());
            seq.put("accn", sequence.getAccession());
            seq.put("sid", sequence.getGenomeId());
            seq.put("start", 0);
            seq.put("end", sequence.getLength());
            seq.put("seqDir", "");
            seq.put("seqChunkSize", sequence.getLength());

            jsonResult.add(seq);
        }
        i++;
    }

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

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

License:Apache License

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

    String accession = request.getParameter("accession");
    String annotation = request.getParameter("annotation");
    String genomeId = request.getParameter("genomeId");
    //      LOGGER.debug("printTrackInfo: {}", request.getParameterMap().toString());

    if (accession != null && annotation != null) {
        DataApiHandler dataApi = new DataApiHandler(request);

        JSONArray ncList = new JSONArray();
        List<Integer> histogram = this.getFeatureCountHistogram(request);
        Integer sum = 0;//from w w w.  j  a  v a2 s  .  c  o  m
        for (Integer hist : histogram) {
            sum += hist;
        }
        double avgCount = sum.doubleValue() / histogram.size();

        SolrQuery query = new SolrQuery("genome_id:" + genomeId + " AND accession:" + accession
                + " AND annotation:" + annotation + " AND !(feature_type:source)");
        query.setRows(dataApi.MAX_ROWS);
        query.addSort("start", SolrQuery.ORDER.asc);

        LOGGER.trace("[{}] {}", SolrCore.FEATURE.getSolrCoreName(), query.toString());
        String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, 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 f : features) {

            JSONArray alist = new JSONArray();

            alist.addAll(Arrays.asList(0, (f.getStart() - 1), f.getStart(), f.getEnd(),
                    (f.getStrand().equals("+") ? 1 : -1), f.getStrand(),

                    f.getId(), f.hasPatricId() ? f.getPatricId() : "",
                    f.hasRefseqLocusTag() ? f.getRefseqLocusTag() : "",
                    f.hasAltLocusTag() ? f.getAltLocusTag() : "", annotation, f.getFeatureType(),
                    f.hasProduct() ? f.getProduct() : "",

                    f.hasGene() ? f.getGene() : "",
                    (f.getFeatureType().equals("CDS") ? 0 : (f.getFeatureType().contains("RNA") ? 1 : 2))));

            ncList.add(alist);
        }

        //         {
        //            "featureCount": <%=features_count %>,
        //            "formatVersion": 1,
        //            "histograms": {
        //               "meta": [{
        //                  "arrayParams": {
        //                     "chunkSize": 10000,
        //                     "length": <%=hist.size()%>,
        //                     "urlTemplate": "Hist.json.jsp?accession=<%=_accession%>&algorithm=<%=_algorithm%>&chunk={Chunk}&format=.json"
        //                  },
        //                  "basesPerBin": "10000"
        //               }],
        //               "stats": [{
        //                  "basesPerBin": "10000",
        //                  "max": <%=(hist.isEmpty())?"0":Collections.max(hist)%>,
        //                  "mean": <%=hist_avg%>
        //               }]
        //            },
        //            "intervals": {
        //               "classes": [{
        //                  "attributes": [
        //                     "Start", "Start_str", "End", "Strand", "strand_str",
        //                     "id", "locus_tag", "source", "type", "product",
        //                     "gene", "refseq", "phase"],
        //                  "isArrayAttr": {}
        //               }],
        //               "count": <%=features_count %>,
        //               "lazyClass": 5,
        //               "maxEnd": 20000,
        //               "minStart": 1,
        //               "nclist": [<%=nclist.toString() %>],
        //               "urlTemplate": "lf-{Chunk}.json"
        //            }
        //         }
        JSONObject track = new JSONObject();
        track.put("featureCount", features.size());
        track.put("formatVersion", 1);
        // histogram
        JSONObject histograms = new JSONObject();
        // meta
        JSONArray meta = new JSONArray();
        JSONObject aMeta = new JSONObject();
        // arrayParams
        JSONObject arrayParams = new JSONObject();
        arrayParams.put("chunkSize", 10000);
        arrayParams.put("length", histogram.size());
        arrayParams.put("urlTemplate",
                "/portal/portal/patric/GenomeBrowser/GBWindow?action=b&cacheability=PAGE&mode=getHistogram&accession="
                        + accession + "&annotation=" + annotation + "&chunk={Chunk}");
        aMeta.put("arrayParams", arrayParams);
        aMeta.put("basesPerBin", 10000);
        meta.add(aMeta);
        // stats
        JSONArray stats = new JSONArray();
        JSONObject aStat = new JSONObject();
        aStat.put("basesPerBin", 10000);
        aStat.put("max", (histogram.isEmpty() ? 0 : Collections.max(histogram)));
        aStat.put("mean", avgCount);
        stats.add(aStat);

        histograms.put("meta", meta);
        histograms.put("stats", stats);

        // intervals
        JSONObject intervals = new JSONObject();
        // classes
        JSONArray classes = new JSONArray();
        JSONObject aClass = new JSONObject();
        JSONArray attributes = new JSONArray();
        attributes.addAll(Arrays.asList("Start", "Start_str", "End", "Strand", "strand_str", "id", "patric_id",
                "refseq_locus_tag", "alt_locus_tag", "source", "type", "product", "gene", "phase"));

        aClass.put("attributes", attributes);
        aClass.put("isArrayAttr", new JSONObject());
        classes.add(aClass);
        intervals.put("classes", classes);
        intervals.put("count", features.size());
        intervals.put("lazyClass", 5);
        intervals.put("maxEnd", 20000);
        intervals.put("minStart", 1);
        intervals.put("nclist", ncList);
        intervals.put("urlTemplate", "lf-{Chunk}.json");

        track.put("histograms", histograms);
        track.put("intervals", intervals);

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

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

License:Apache License

private List<Integer> getFeatureCountHistogram(ResourceRequest request) throws IOException {

    String accession = request.getParameter("accession");
    String annotation = request.getParameter("annotation");
    String genomeId = request.getParameter("genomeId");

    SolrQuery query = new SolrQuery("accession:" + accession + " AND genome_id:" + genomeId);
    query.setFilterQueries("annotation:" + annotation + " AND !(feature_type:source)");
    query.setRows(0);
    query.setFacet(true);//from ww  w .  ja  v a 2  s  . co m
    query.setFacetMinCount(1);
    query.addNumericRangeFacet("start", 0, 10000000, 10000);

    List<Integer> results = new ArrayList<>();
    DataApiHandler dataApi = new DataApiHandler(request);

    LOGGER.trace("[{}] {}", SolrCore.FEATURE.getSolrCoreName(), query.toString());
    String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);
    Map resp = jsonReader.readValue(apiResponse);
    Map facetCounts = (Map) resp.get("facet_counts");
    Map facetRanges = (Map) facetCounts.get("facet_ranges");
    List counts = (List) ((Map) facetRanges.get("start")).get("counts");

    for (int i = 0; i < counts.size(); i = i + 2) {
        int value = (Integer) counts.get(i + 1);
        results.add(value);
    }

    return results;
}

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

License:Apache License

private Map processGlobalSearchFeature(ResourceRequest request) throws IOException {

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

    SolrQuery query = new SolrQuery(StringHelper.stripQuoteAndParseSolrKeywordOperator(keyword));
    if (need.equals("search")) {
        query.setRows(3).set("hl", "on").set("hl.fl", "*");
    } else {/* w w w. jav a 2 s. c  o m*/
        query.setRows(dataApi.MAX_ROWS);
    }

    query.setFields(StringUtils.join(DownloadHelper.getFieldsForFeatures(), ","));
    query.addFilterQuery("!feature_type:source");
    query.addFilterQuery("!annotation:BRC1");

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

    Map resp = jsonReader.readValue(apiResponse);

    return resp;
}

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

License:Apache License

private Map processGlobalSearchGenome(ResourceRequest request) throws IOException {

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

    SolrQuery query = new SolrQuery(StringHelper.stripQuoteAndParseSolrKeywordOperator(keyword));
    if (need.equals("search")) {
        query.setRows(3).set("hl", "on").set("hl.fl", "*");
    } else {/*from w w  w .j  av  a  2s .  c o m*/
        query.setRows(dataApi.MAX_ROWS);
    }

    query.setFields(StringUtils.join(DownloadHelper.getFieldsForGenomes(), ","));

    LOGGER.trace("processGlobalSearch: [{}] {}", SolrCore.GENOME.getSolrCoreName(), query);
    String apiResponse = dataApi.solrQuery(SolrCore.GENOME, query);

    Map resp = jsonReader.readValue(apiResponse);

    return resp;
}

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

License:Apache License

private Map processGlobalSearchTaxonomy(ResourceRequest request) throws IOException {

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

    SolrQuery query = new SolrQuery(StringHelper.stripQuoteAndParseSolrKeywordOperator(keyword));
    if (need.equals("search")) {
        query.setRows(3).set("hl", "on").set("hl.fl", "*");
    } else {/* w  ww. ja  va  2 s  . co  m*/
        query.setRows(dataApi.MAX_ROWS);
    }

    query.setFields("taxon_id,taxon_name,taxon_rank,genomes");

    LOGGER.trace("processGlobalSearch: [{}] {}", SolrCore.TAXONOMY.getSolrCoreName(), query);
    String apiResponse = dataApi.solrQuery(SolrCore.TAXONOMY, query);

    Map resp = jsonReader.readValue(apiResponse);

    return resp;
}

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

License:Apache License

private Map processGlobalSearchExperiment(ResourceRequest request) throws IOException {

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

    SolrQuery query = new SolrQuery(StringHelper.stripQuoteAndParseSolrKeywordOperator(keyword));
    if (need.equals("search")) {
        query.setRows(3).set("hl", "on").set("hl.fl", "*");
    } else {/*  w ww  .ja v  a  2 s  .com*/
        query.setRows(dataApi.MAX_ROWS);
    }

    query.setFields("eid,accession,title,description,organism,strain,mutant,timeseries,condition");

    LOGGER.trace("processGlobalSearch: [{}] {}", SolrCore.TRANSCRIPTOMICS_EXPERIMENT.getSolrCoreName(), query);
    String apiResponse = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_EXPERIMENT, query);

    Map resp = jsonReader.readValue(apiResponse);

    return resp;
}

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

License:Apache License

@SuppressWarnings("unchecked")
private JSONObject processIDMapping(DataApiHandler dataApi, String fromId, String fromIdGroup, String toId,
        String toIdGroup, String keyword) throws IOException {

    JSONArray results = new JSONArray();
    int total;/*from w w  w .j  a v  a2s  .  c  om*/

    if (fromIdGroup.equals("PATRIC")) {
        if (toIdGroup.equals("PATRIC")) { // from PATRIC to PATRIC

            // query to GenomeFeature
            try {
                SolrQuery query = new SolrQuery(fromId + ":(" + keyword + ")");
                query.addFilterQuery("annotation:PATRIC").setRows(10000);

                if (toId.equals("gene_id") || toId.equals("gi")) {
                    query.addFilterQuery(toId + ":[1 TO *]");
                }

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

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

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

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

                for (GenomeFeature feature : featureList) {
                    results.add(feature.toJSONObject());
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }

            total = results.size();
        } else { // from PATRIC to Other

            Set<Long> giList = new HashSet<>();
            Map<String, String> accessionGiMap = new LinkedHashMap<>();
            List<Map<Long, String>> giTargetList = new LinkedList<>();
            List<GenomeFeature> featureList = new ArrayList<>();

            // Query GenomeFeature, get GInumbers
            try {
                SolrQuery query = new SolrQuery(fromId + ":(" + keyword + ")");
                query.setRows(10000);
                LOGGER.trace("PATRIC TO Other 1/3: [{}] {}", SolrCore.FEATURE.getSolrCoreName(), query);

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

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

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

                for (GenomeFeature feature : featureList) {
                    giList.add(feature.getGi());
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }

            // get UniprotKBAccessions wigh GI
            try {
                SolrQuery query = new SolrQuery("id_value:(" + StringUtils.join(giList, " OR ") + ")");
                query.addFilterQuery("id_type:GI").setRows(10000);

                LOGGER.trace("PATRIC TO Other 2/3: [{}] {}", SolrCore.ID_REF.getSolrCoreName(),
                        query.toString());

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

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

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

                for (Map doc : uniprotList) {

                    accessionGiMap.put(doc.get("uniprotkb_accession").toString(),
                            doc.get("id_value").toString());
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
            LOGGER.trace("accessionGiMap:{}", accessionGiMap);

            if (!accessionGiMap.isEmpty()) {
                // get Target Value
                try {
                    SolrQuery query = new SolrQuery(
                            "uniprotkb_accession:(" + StringUtils.join(accessionGiMap.keySet(), " OR ") + ")");
                    if (toId.equals("UniProtKB-Accession")) {
                        query.addFilterQuery("id_type:GI");
                    } else {
                        query.addFilterQuery("id_type:(" + toId + ")");
                    }
                    query.setRows(accessionGiMap.size());

                    LOGGER.trace("PATRIC TO Other 3/3: [{}] {}", SolrCore.ID_REF.getSolrCoreName(),
                            query.toString());

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

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

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

                    for (Map doc : targets) {
                        String accession = doc.get("uniprotkb_accession").toString();
                        String target = doc.get("id_value").toString();

                        Long targetGi = Long.parseLong(accessionGiMap.get(accession));

                        Map<Long, String> giTarget = new HashMap<>();
                        if (toId.equals("UniProtKB-Accession")) {
                            giTarget.put(targetGi, accession);
                        } else {
                            giTarget.put(targetGi, target);
                        }
                        giTargetList.add(giTarget);
                    }
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }

                LOGGER.trace("giTargetList:{}", giTargetList);

                // query to GenomeFeature
                for (GenomeFeature feature : featureList) {
                    for (Map<Long, String> targetMap : giTargetList) {
                        if (targetMap.containsKey(feature.getGi())) {
                            JSONObject item = feature.toJSONObject();
                            item.put("target", targetMap.get(feature.getGi()));

                            results.add(item);
                        }
                    }
                }
            }

            total = results.size();
        }
    } else { // from Other to PATRIC (patric_id)

        Map<String, String> accessionTargetMap = new LinkedHashMap<>();
        Set<Long> giList = new HashSet<>();
        List<Map<Long, String>> giTargetList = new LinkedList<>();

        if (fromId.equals("UniProtKB-Accession")) {
            // we have treat this as a special case, since UniProtKB-Accession is stored in a separate field, named 'uniprotkb_accession'
            for (String accession : keyword.split(" OR ")) {
                accessionTargetMap.put(accession, accession);
            }
        } else {
            try {
                SolrQuery query = new SolrQuery("id_value:(" + keyword + ")");
                query.addFilterQuery("id_type:" + fromId).setRows(10000)
                        .addField("uniprotkb_accession,id_value");

                LOGGER.trace("Other to PATRIC 1/3: [{}] {}", SolrCore.ID_REF.getSolrCoreName(),
                        query.toString());

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

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

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

                for (Map doc : accessions) {
                    accessionTargetMap.put(doc.get("uniprotkb_accession").toString(),
                            doc.get("id_value").toString());
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }

        if (!accessionTargetMap.isEmpty()) {
            try {
                SolrQuery query = new SolrQuery(
                        "uniprotkb_accession:(" + StringUtils.join(accessionTargetMap.keySet(), " OR ") + ")");
                query.addFilterQuery("id_type:GI").setRows(10000);

                LOGGER.trace("Other to PATRIC 2/3: [{}] {}", SolrCore.ID_REF.getSolrCoreName(),
                        query.toString());

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

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

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

                for (Map doc : accessions) {
                    Long targetGi = Long.parseLong(doc.get("id_value").toString());
                    String accession = doc.get("uniprotkb_accession").toString();
                    String target = accessionTargetMap.get(accession);

                    giList.add(targetGi);

                    Map<Long, String> targetMap = new HashMap<>();
                    targetMap.put(targetGi, target);
                    giTargetList.add(targetMap);
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }

        LOGGER.trace("giTargetList:{}", giTargetList);
        if (!giList.isEmpty()) {
            try {
                SolrQuery query = new SolrQuery("gi:(" + StringUtils.join(giList, " OR ") + ")");
                query.addFilterQuery("annotation:PATRIC").setRows(10000);

                LOGGER.trace("Other to PATRIC 3/3: [{}] {}", SolrCore.FEATURE.getSolrCoreName(),
                        query.toString());

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

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

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

                for (GenomeFeature feature : featureList) {
                    for (Map<Long, String> targetMap : giTargetList) {
                        if (targetMap.containsKey(feature.getGi())) {
                            JSONObject item = feature.toJSONObject();
                            item.put("target", targetMap.get(feature.getGi()));

                            results.add(item);
                        }
                    }
                }

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

        total = results.size();
    }

    JSONObject jsonResult = new JSONObject();
    jsonResult.put("total", total);
    jsonResult.put("results", results);

    return jsonResult;
}

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

License:Apache License

protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {

    SiteHelper.setHtmlMetaElements(request, response, "3D Structure");

    response.setContentType("text/html");
    String pdbID = request.getParameter("pdb_id");

    if (pdbID != null) {

        String chainID = request.getParameter("chain_id");

        String _context_path = request.getContextPath();
        String _codebase = _context_path + "/jmol";
        String _datafile = "https://" + request.getServerName() + _context_path + "/jsp/readPDB.jsp?pdbID="
                + pdbID;//from   w w w. j a v a2 s .  c  om

        String urlNCBIStructure = "http://www.ncbi.nlm.nih.gov/sites/entrez?db=structure&cmd=DetailsSearch&term=";
        String urlPDB = "http://www.pdb.org/pdb/explore/explore.do?structureId=";
        String urlSSGCID = "http://www.ssgcid.org/";
        String urlCSGID = "http://www.csgid.org/";

        String nameSSGCID = "Seattle Structural Genomics Center for Infectious Disease";
        String nameCSGID = "Center for Structural Genomics of Infectious Diseases";

        PDBInterface api = new PDBInterface();
        Map<String, String> description = api.getDescription(pdbID);

        if (description != null) {

            DataApiHandler dataApi = new DataApiHandler(request);
            List<GenomeFeature> features = new ArrayList<>();
            List<String> targetIDs = new ArrayList<>();

            // 1. read associated features for given PDB ID
            // 1.1 read uniprotkb_accession
            List<String> uniprotKbAccessions = new ArrayList<>();
            SolrQuery query = new SolrQuery("id_type:PDB AND id_value:" + pdbID);

            LOGGER.trace("[{}] {}", SolrCore.ID_REF.getSolrCoreName(), query.toString());
            String apiResponse = dataApi.solrQuery(SolrCore.ID_REF, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map<String, Object>) resp.get("response");

            int numFound = (Integer) respBody.get("numFound");
            if (numFound > 0) {
                List<Map> records = (List<Map>) respBody.get("docs");
                for (Map item : records) {
                    uniprotKbAccessions.add(item.get("uniprotkb_accession").toString());
                }
            }

            // 1.2 read features with uniprotkb_accession
            if (!uniprotKbAccessions.isEmpty()) {
                query = new SolrQuery(
                        "uniprotkb_accession:(" + StringUtils.join(uniprotKbAccessions, " OR ") + ")");

                LOGGER.trace("[{}] {}", SolrCore.FEATURE.getSolrCoreName(), query.toString());
                apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);
                resp = jsonReader.readValue(apiResponse);
                respBody = (Map<String, Object>) resp.get("response");

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

            // 2. retrieve structural meta data
            if (!uniprotKbAccessions.isEmpty()) {
                List<String> ids = new ArrayList<>();
                for (String uniprotkbAccession : uniprotKbAccessions) {
                    ids.add("\"UniProt:" + uniprotkbAccession + "\"");
                }

                query = new SolrQuery("gene_symbol_collection:(" + StringUtils.join(ids, " OR ") + ")");
                query.setRows(uniprotKbAccessions.size());

                LOGGER.trace("[{}] {}", SolrCore.STRUCTURE.getSolrCoreName(), query.toString());
                apiResponse = dataApi.solrQuery(SolrCore.STRUCTURE, query);
                resp = jsonReader.readValue(apiResponse);
                respBody = (Map<String, Object>) resp.get("response");

                List<Map> sdl = (List<Map>) respBody.get("docs");
                for (Map doc : sdl) {
                    targetIDs.add(doc.get("target_id").toString());
                }
            }

            //
            request.setAttribute("pdbID", pdbID);
            request.setAttribute("chainID", chainID);
            request.setAttribute("_codebase", _codebase);
            request.setAttribute("_datafile", _datafile);
            request.setAttribute("urlNCBIStructure", urlNCBIStructure);
            request.setAttribute("urlPDB", urlPDB);
            request.setAttribute("urlSSGCID", urlSSGCID);
            request.setAttribute("urlCSGID", urlCSGID);
            request.setAttribute("nameSSGCID", nameSSGCID);
            request.setAttribute("nameCSGID", nameCSGID);
            request.setAttribute("description", description); // Map<String, String>
            request.setAttribute("features", features); // List<GenomeFeature>
            request.setAttribute("targetIDs", targetIDs); // List<String>

            PortletRequestDispatcher prd = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/jmol.jsp");
            prd.include(request, response);
        } else {
            PrintWriter writer = response.getWriter();
            writer.write("No data available.");
            writer.close();
        }
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("Invalid Parameter - missing context information");
        writer.close();
    }
}

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

License:Apache License

@SuppressWarnings("unchecked")
private JSONObject processPathwayTab(DataApiHandler dataApi, String pathwayId, String ecNumber,
        String annotation, String taxonId, String genomeId, String keyword)
        throws PortletException, IOException {

    JSONObject jsonResult = new JSONObject();
    SolrQuery query = new SolrQuery("*:*");

    if (pathwayId != null && !pathwayId.equals("")) {
        query.addFilterQuery("pathway_id:" + pathwayId);
    }/*from  w ww .  java 2 s . c om*/

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

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

    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 (keyword != null && !keyword.equals("")) {
        query.setQuery(keyword);
    }

    JSONArray items = new JSONArray();
    int count_total = 0;
    int count_unique = 0;

    try {
        Set<String> listPathwayIds = new HashSet<>();
        Map<String, JSONObject> uniquePathways = new HashMap<>();

        // get pathway stat
        query.setRows(0).setFacet(true);
        query.add("json.facet",
                "{stat:{field:{field:pathway_id,limit:-1,facet:{genome_count:\"unique(genome_id)\",gene_count:\"unique(feature_id)\",ec_count:\"unique(ec_number)\",genome_ec:\"unique(genome_ec)\"}}}}");

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

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

        Map resp = jsonReader.readValue(apiResponse);
        List<Map> buckets = (List<Map>) ((Map) ((Map) resp.get("facets")).get("stat")).get("buckets");

        Map<String, Map> mapStat = new HashMap<>();
        for (Map value : buckets) {
            mapStat.put(value.get("val").toString(), value);
            listPathwayIds.add(value.get("val").toString());
        }

        if (!listPathwayIds.isEmpty()) {
            // get pathway list
            SolrQuery pathwayQuery = new SolrQuery(
                    "pathway_id:(" + StringUtils.join(listPathwayIds, " OR ") + ")");
            pathwayQuery.setFields("pathway_id,pathway_name,pathway_class");
            pathwayQuery.setRows(Math.max(dataApi.MAX_ROWS, listPathwayIds.size()));

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

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

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

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

                if (!uniquePathways.containsKey(aPathwayId)
                        && !stat.get("genome_count").toString().equals("0")) {
                    JSONObject item = new JSONObject();
                    item.put("pathway_id", aPathwayId);
                    item.put("pathway_name", doc.get("pathway_name"));
                    item.put("pathway_class", doc.get("pathway_class"));

                    float genome_ec = Float.parseFloat(stat.get("genome_ec").toString());
                    float genome_count = Float.parseFloat(stat.get("genome_count").toString());
                    float ec_count = Float.parseFloat(stat.get("ec_count").toString());
                    float gene_count = Float.parseFloat(stat.get("gene_count").toString());

                    float ec_cons = 0;
                    float gene_cons = 0;
                    if (genome_count > 0 && ec_count > 0) {
                        ec_cons = genome_ec / genome_count / ec_count * 100;
                        gene_cons = gene_count / genome_count / ec_count;
                    }

                    item.put("ec_cons", ec_cons);
                    item.put("ec_count", ec_count);
                    item.put("gene_cons", gene_cons);
                    item.put("gene_count", gene_count);
                    item.put("genome_count", genome_count);
                    item.put("algorithm", annotation);

                    uniquePathways.put(aPathwayId, item);
                }
            }

            for (Map.Entry<String, JSONObject> pathway : uniquePathways.entrySet()) {
                items.add(pathway.getValue());
            }
            count_total = uniquePathways.entrySet().size();
            count_unique = count_total;
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    // Wrapping jsonResult
    try {
        jsonResult.put("total", count_total);
        jsonResult.put("results", items);
        jsonResult.put("unique", count_unique);
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
    }

    return jsonResult;
}