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.CompPathwayMap.java

License:Apache License

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 .ja  v  a  2 s .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.portlets.CompPathwayTable.java

License:Apache License

@SuppressWarnings("unchecked")
private JSONObject processPathwayTab(DataApiHandler dataApi, String pathwayClass, String pathwayId,
        String ecNumber, String annotation, String contextType, String contextId)
        throws PortletException, IOException {

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

    if (pathwayClass != null && !pathwayClass.equals("")) {
        query.addFilterQuery("pathway_class:" + pathwayClass);
    }/*w  ww .  ja  v  a2 s  .com*/

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

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

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

    if (contextType.equals("genome")) {
        query.addFilterQuery(
                SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "genome_id:" + contextId));
    } else if (contextType.equals("taxon")) {
        query.addFilterQuery(
                SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "taxon_lineage_ids:" + contextId));
    }

    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("[{}] {}", 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((String) value.get("val"), value);
            listPathwayIds.add((String) value.get("val"));
        }

        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("[{}] {}", 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;
}

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

License:Apache License

@SuppressWarnings("unchecked")
private JSONObject processEcNumberTab(DataApiHandler dataApi, String pathwayClass, String pathwayId,
        String ecNumber, String annotation, String contextType, String contextId)
        throws PortletException, IOException {

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

    if (pathwayClass != null && !pathwayClass.equals("")) {
        query.addFilterQuery("pathway_class:" + pathwayClass);
    }//from   w w w  .ja v  a  2s.  co  m

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

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

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

    if (contextType.equals("genome")) {
        query.addFilterQuery(
                SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "genome_id:" + contextId));
    } else if (contextType.equals("taxon")) {
        query.addFilterQuery(
                SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "taxon_lineage_ids:" + contextId));
    }

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

    try {
        Set<String> listPathwayIds = new HashSet<>();
        Set<String> listEcNumbers = new HashSet<>();

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

        LOGGER.trace("[{}] {}", 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) {

            if (!value.get("genome_count").toString().equals("0")) {
                mapStat.put(value.get("val").toString(), value);

                String[] pathway_ec = value.get("val").toString().split("_");
                listPathwayIds.add(pathway_ec[0]);
                listEcNumbers.add(pathway_ec[1]);
            }
        }

        // get pathway list
        SolrQuery pathwayQuery = new SolrQuery("*:*");
        if (!listPathwayIds.isEmpty()) {
            pathwayQuery.setQuery("pathway_id:(" + StringUtils.join(listPathwayIds, " OR ") + ")");

            pathwayQuery.setFields("pathway_id,pathway_name,pathway_class,ec_number,ec_description");
            pathwayQuery.setRows(Math.max(dataApi.MAX_ROWS, listPathwayIds.size()));

            LOGGER.trace("[{}] {}", 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();
                String aEcNumber = doc.get("ec_number").toString();
                Map stat = mapStat.get(aPathwayId + "_" + aEcNumber);

                if (stat != null && !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_count = Float.parseFloat(stat.get("genome_count").toString());
                    float gene_count = Float.parseFloat(stat.get("gene_count").toString());

                    item.put("ec_name", doc.get("ec_description"));
                    item.put("ec_number", doc.get("ec_number"));
                    item.put("gene_count", gene_count);
                    item.put("genome_count", genome_count);
                    item.put("algorithm", annotation);

                    items.add(item);
                }
            }
            count_total = items.size();
            count_unique = listEcNumbers.size();
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    // Wrapping jsonResult
    jsonResult.put("total", count_total);
    jsonResult.put("results", items);
    jsonResult.put("unique", count_unique);

    return jsonResult;
}

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

License:Apache License

@SuppressWarnings("unchecked")
private JSONObject processGeneTab(DataApiHandler dataApi, String pathwayClass, String pathwayId,
        String ecNumber, String annotation, String contextType, String contextId)
        throws PortletException, IOException {

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

    if (pathwayClass != null && !pathwayClass.equals("")) {
        query.addFilterQuery("pathway_class:" + pathwayClass);
    }/*  w w  w.jav  a 2  s  .co m*/

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

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

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

    if (contextType.equals("genome")) {
        query.addFilterQuery(
                SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "genome_id:" + contextId));
    } else if (contextType.equals("taxon")) {
        query.addFilterQuery(
                SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "taxon_lineage_ids:" + contextId));
    }

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

    try {
        Set<String> listFeatureIds = new HashSet<>();

        query.setFields("pathway_id,pathway_name,feature_id,ec_number,ec_description");
        query.setRows(dataApi.MAX_ROWS);

        LOGGER.trace("[{}] {}", 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");

        Map<String, Map> mapStat = new HashMap<>();
        for (Map doc : sdl) {

            mapStat.put(doc.get("feature_id").toString(), doc);
            listFeatureIds.add(doc.get("feature_id").toString());
        }

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

            LOGGER.trace("[{}] {}, iter={}", SolrCore.PATHWAY.getSolrCoreName(), query, 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) {

                mapStat.put(doc.get("feature_id").toString(), doc);
                listFeatureIds.add(doc.get("feature_id").toString());
            }
            i++;
        }

        // get pathway list
        if (!listFeatureIds.isEmpty()) {
            SolrQuery featureQuery = new SolrQuery(
                    "feature_id:(" + StringUtils.join(listFeatureIds, " OR ") + ")");
            featureQuery.setFields(
                    "genome_name,genome_id,accession,alt_locus_tag,refseq_locus_tag,patric_id,feature_id,gene,product");
            featureQuery.setRows(Math.max(dataApi.MAX_ROWS, listFeatureIds.size()));

            LOGGER.trace("[{}] {}, {}", SolrCore.FEATURE.getSolrCoreName(), featureQuery,
                    listFeatureIds.size());

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

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

            for (GenomeFeature feature : features) {
                String featureId = feature.getId();
                Map stat = mapStat.get(featureId);

                JSONObject item = new JSONObject();
                item.put("genome_name", feature.getGenomeName());
                item.put("genome_id", feature.getGenomeId());
                item.put("accession", feature.getAccession());
                item.put("feature_id", feature.getId());
                item.put("alt_locus_tag", feature.getAltLocusTag());
                item.put("refseq_locus_tag", feature.getRefseqLocusTag());
                item.put("algorithm", annotation);
                item.put("patric_id", feature.getPatricId());
                item.put("gene", feature.getGene());
                item.put("product", feature.getProduct());

                item.put("ec_name", stat.get("ec_description"));
                item.put("ec_number", stat.get("ec_number"));
                item.put("pathway_id", stat.get("pathway_id"));
                item.put("pathway_name", stat.get("pathway_name"));

                items.add(item);
            }

            i = 1;
            while (features.size() == 25000) {
                featureQuery.setStart(25000 * i);

                LOGGER.trace("[{}] {}, iter={}", SolrCore.FEATURE.getSolrCoreName(), featureQuery, i);

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

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

                for (GenomeFeature feature : features) {
                    String featureId = feature.getId();
                    Map stat = mapStat.get(featureId);

                    JSONObject item = new JSONObject();
                    item.put("genome_name", feature.getGenomeName());
                    item.put("genome_id", feature.getGenomeId());
                    item.put("accession", feature.getAccession());
                    item.put("feature_id", feature.getId());
                    item.put("alt_locus_tag", feature.getAltLocusTag());
                    item.put("refseq_locus_tag", feature.getRefseqLocusTag());
                    item.put("algorithm", annotation);
                    item.put("patric_id", feature.getPatricId());
                    item.put("gene", feature.getGene());
                    item.put("product", feature.getProduct());

                    item.put("ec_name", stat.get("ec_description"));
                    item.put("ec_number", stat.get("ec_number"));
                    item.put("pathway_id", stat.get("pathway_id"));
                    item.put("pathway_name", stat.get("pathway_name"));

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

            count_total = items.size();
            count_unique = count_total;
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    // Wrapping jsonResult
    jsonResult.put("total", count_total);
    jsonResult.put("results", items);
    jsonResult.put("unique", count_unique);

    return jsonResult;
}

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

License:Apache License

private void processFeatureIds(ResourceRequest request, ResourceResponse response) throws IOException {
    String cId = request.getParameter("cId");
    String cType = request.getParameter("cType");
    String map = request.getParameter("map");
    String algorithm = request.getParameter("algorithm");
    String ec_number = request.getParameter("ec_number");
    String featureList = request.getParameter("featureList");

    DataApiHandler dataApi = new DataApiHandler(request);
    JSONArray items = new JSONArray();

    try {/*from w  ww. j  a v  a2  s.c o m*/
        SolrQuery query = new SolrQuery("*:*");

        if (cType != null && cType.equals("taxon")) {
            query.addFilterQuery(
                    SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "taxon_lineage_ids:" + cId));
        } else if (cType != null && cType.equals("genome")) {
            query.addFilterQuery(
                    SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "genome_id:(" + cId + ")"));
        }

        if (map != null && !map.equals("")) {
            query.addFilterQuery("pathway_id:(" + map.replaceAll(",", " OR ") + ")");
        }

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

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

        if (featureList != null && !featureList.equals("")) {
            query.addFilterQuery("feature_id:(" + featureList.replaceAll(",", " OR ") + ")");
        }

        query.setRows(dataApi.MAX_ROWS).setFields("feature_id");

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

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

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

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

        for (Map feature : features) {
            items.add(feature.get("feature_id").toString());
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    items.writeJSONString(response.getWriter());
}

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

License:Apache License

public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {

    String mode = request.getParameter("mode");

    if (mode.equals("getGenomeCount")) {

        String taxonId = request.getParameter("taxonId");
        String dataSource = request.getParameter("data_source");

        DataApiHandler dataApi = new DataApiHandler(request);

        SolrQuery query = new SolrQuery();

        if (taxonId != null) {
            query.setQuery("taxon_lineage_ids:" + taxonId);
        } else {/*from w ww. j  a va2  s  . c om*/
            query.setQuery("*:*");
        }

        if (dataSource != null) {
            String[] sources = dataSource.split(",");
            List<String> conditions = new ArrayList<>();

            for (String source : sources) {
                switch (source) {
                case ".PATRIC":
                    conditions.add("patric_cds:[1 TO *]");
                    break;
                case ".RefSeq":
                    conditions.add("refseq_cds:[1 TO *]");
                    break;
                }
            }

            query.setFilterQueries(StringUtils.join(conditions, " OR "));
        }
        query.setRows(0);

        LOGGER.debug("[{}] {}", SolrCore.GENOME, query.toString());
        String apiResponse = dataApi.solrQuery(SolrCore.GENOME, query);

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

        int numFound = (Integer) respBody.get("numFound");

        response.getWriter().write("" + numFound);
    } else if (mode.equals("download")) {

        String genomeId = request.getParameter("genomeId");
        String taxonId = request.getParameter("taxonId");
        String fileTypes = request.getParameter("finalfiletype");
        String annotations = request.getParameter("finalalgorithm");

        Logger LOGGER = LoggerFactory.getLogger(CreateZip.class);

        List<String> genomeIdList = new LinkedList<>();

        DataApiHandler dataApi = new DataApiHandler(request);

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

        if (genomeId != null && !genomeId.equals("")) {
            query.addFilterQuery("genome_id:(" + genomeId.replaceAll(",", " OR ") + ")");
        }
        if (taxonId != null && !taxonId.equals("")) {
            query.addFilterQuery("taxon_lineage_ids:" + taxonId);
        }
        query.setRows(dataApi.MAX_ROWS).addField("genome_id");

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

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

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

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

        CreateZip zip = new CreateZip();
        byte[] bytes = zip.ZipIt(genomeIdList, Arrays.asList(annotations.split(",")),
                Arrays.asList(fileTypes.split(",")));

        if (bytes.length > 0) {
            response.setContentType("application/octetstream");
            response.setProperty("Cache-Control", "cache");
            response.setProperty("Content-Disposition", "attachment; filename=\"patric_downloads.zip\"");
            response.setContentLength(bytes.length);
            response.getPortletOutputStream().write(bytes);
        } else {
            response.getWriter().write("Sorry. The requested file(s) are not available.");
        }
    }
}

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

License:Apache License

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

    response.setContentType("text/html");

    SiteHelper.setHtmlMetaElements(request, response, "Experiment List");
    response.setTitle("Experiment List");

    String cType = request.getParameter("context_type");
    String cId = request.getParameter("context_id");

    if (cType != null && cId != null) {

        String kw = (request.getParameter("keyword") != null) ? request.getParameter("keyword") : "";
        if (kw != null && (kw.startsWith("/") || kw.startsWith("#"))) {
            kw = "";
        }//  w w  w.j  a va2 s  . c  om

        String keyword = "(*)";
        String filter;
        String eid;

        if (cType.equals("taxon") && cId.equals("2")) {
            filter = "*";
            eid = "";
        } else {
            DataApiHandler dataApi = new DataApiHandler(request);
            List<String> items = new ArrayList<>();

            SolrQuery query = new SolrQuery();

            if (cType.equals("taxon")) {
                query.setQuery("*:*");
                query.setFilterQueries(
                        SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_ids", "taxon_lineage_ids:" + cId));
            } else if (cType.equals("genome")) {
                query = new SolrQuery("genome_ids:" + cId);
            }

            query.setRows(10000).setFields("eid");
            String apiResponse = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_EXPERIMENT, query);

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

            for (Map doc : sdl) {
                items.add(doc.get("eid").toString());
            }

            if (items.size() > 0) {
                eid = StringUtils.join(items, "##");
            } else {
                eid = "0";
            }
            filter = eid;
        }

        request.setAttribute("keyword", keyword);
        request.setAttribute("kw", kw);
        request.setAttribute("eid", eid);
        request.setAttribute("filter", filter);

        PortletRequestDispatcher prd = getPortletContext()
                .getRequestDispatcher("/WEB-INF/jsp/experiment/list.jsp");
        prd.include(request, response);
    }
}

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

License:Apache License

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

    response.setContentType("text/html");
    String cType = request.getParameter("context_type");
    String cId = request.getParameter("context_id");

    if (cType != null && cId != null && cType.equals("feature")) {

        List<Map> listAnnotation = new LinkedList<>();
        DataApiHandler dataApi = new DataApiHandler(request);

        GenomeFeature feature = dataApi.getPATRICFeature(cId);

        if (feature != null) {

            if (feature.hasRefseqLocusTag()) {
                SolrQuery query = new SolrQuery("refseq_locus_tag:" + feature.getRefseqLocusTag());
                query.addFilterQuery("!property:Interaction");
                query.addSort("property", SolrQuery.ORDER.asc).addSort("evidence_code", SolrQuery.ORDER.asc);
                query.setRows(dataApi.MAX_ROWS);

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

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

                listAnnotation.addAll((List<Map>) respBody.get("docs"));

                query.setFilterQueries("property:Interaction");
                query.setSort("value", SolrQuery.ORDER.asc).addSort("evidence_code", SolrQuery.ORDER.asc);

                LOGGER.debug("[{}]: {}", SolrCore.STRUCTURED_ASSERTION.getSolrCoreName(), query);
                apiResponse = dataApi.solrQuery(SolrCore.STRUCTURED_ASSERTION, query);

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

                listAnnotation.addAll((List<Map>) respBody.get("docs"));
            }//from w w w .  j a  va  2s  .  co m

            if (!listAnnotation.isEmpty()) {

                request.setAttribute("listAnnotation", listAnnotation);

                PortletRequestDispatcher prd = getPortletContext()
                        .getRequestDispatcher("/WEB-INF/jsp/overview/feature_comments.jsp");
                prd.include(request, response);
            } else {
                PrintWriter writer = response.getWriter();
                writer.write("<!-- no feature comment found -->");
                writer.close();
            }
        }
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("<p>Invalid Parameter - missing context information</p>");
        writer.close();
    }
}

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

License:Apache License

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

    SiteHelper.setHtmlMetaElements(request, response, "Feature Overview");

    response.setContentType("text/html");
    String cType = request.getParameter("context_type");
    String cId = request.getParameter("context_id");

    if (cType != null && cId != null && cType.equals("feature")) {

        DataApiHandler dataApi = new DataApiHandler(request);
        GenomeFeature feature = dataApi.getPATRICFeature(cId);

        if (feature != null) {
            List<GenomeFeature> listReleateFeatures;
            List<String> listUniprotkbAccessions = null;
            List<Map<String, String>> listUniprotIds = null;
            String refseqLink = null;
            String refseqLocusTag = null;
            Map<String, String> virulenceFactor = null;

            SolrQuery query = new SolrQuery("pos_group:" + feature.getPosGroupInQuote());
            query.setSort("annotation_sort", SolrQuery.ORDER.asc);

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

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

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

            // build listUniprotkbAccessions based on GI number
            if (feature.getGi() > 0) {
                query = new SolrQuery("id_value:(" + feature.getGi() + ")");
                query.addFilterQuery("id_type:GI").setRows(dataApi.MAX_ROWS);

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

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

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

                if (uniprotList.size() > 0) {
                    listUniprotkbAccessions = new ArrayList<>();
                }//from w ww .j  a v  a 2  s  .c o  m

                for (Map doc : uniprotList) {
                    listUniprotkbAccessions.add(doc.get("uniprotkb_accession").toString());
                }
            }

            if (listUniprotkbAccessions != null) {
                query = new SolrQuery(
                        "uniprotkb_accession:(" + StringUtils.join(listUniprotkbAccessions, " OR ") + ")");
                query.setFields("uniprotkb_accession,id_type,id_value");
                query.setRows(1000);

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

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

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

                if (!sdl.isEmpty()) {
                    listUniprotIds = new ArrayList<>();
                }

                for (Map doc : sdl) {
                    Map<String, String> uniprot = new HashMap<>();

                    uniprot.put("Accession", doc.get("uniprotkb_accession").toString());
                    uniprot.put("idType", doc.get("id_type").toString());
                    uniprot.put("idValue", doc.get("id_value").toString());

                    listUniprotIds.add(uniprot);
                }
            }

            if (feature.getAnnotation().equals("PATRIC")) {

                if (feature.hasGeneId()) {
                    refseqLink = SiteHelper.getExternalLinks("ncbi_gene").replace("&", "&amp;")
                            + feature.getGeneId();
                }
                refseqLocusTag = feature.getRefseqLocusTag();
            } else if (feature.getAnnotation().equals("RefSeq")) {
                refseqLocusTag = feature.getAltLocusTag();
            }

            query = new SolrQuery("(locus_tag:" + feature.getAltLocusTag()
                    + (feature.hasRefseqLocusTag() ? " OR locus_tag: " + feature.getRefseqLocusTag() : "")
                    + ")");
            query.setFilterQueries("source:PATRIC_VF");
            query.setFields("source,source_id");

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

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

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

            for (Map doc : sdl) {
                virulenceFactor = new HashMap<>();

                virulenceFactor.put("source", doc.get("source").toString());
                virulenceFactor.put("sourceId", doc.get("source_id").toString());
            }

            request.setAttribute("feature", feature);
            request.setAttribute("listReleateFeatures", listReleateFeatures);
            request.setAttribute("listUniprotkbAccessions", listUniprotkbAccessions);
            request.setAttribute("listUniprotIds", listUniprotIds);
            request.setAttribute("refseqLink", refseqLink);
            request.setAttribute("refseqLocusTag", refseqLocusTag);
            request.setAttribute("virulenceFactor", virulenceFactor);

            PortletRequestDispatcher prd = getPortletContext()
                    .getRequestDispatcher("/WEB-INF/jsp/overview/feature_properties.jsp");
            prd.include(request, response);
        } else {
            PrintWriter writer = response.getWriter();
            writer.write(" ");
            writer.close();
        }
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("<p>Invalid Parameter - missing context information</p>");
        writer.close();
    }
}

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

License:Apache License

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

    response.setContentType("text/html");
    String cType = request.getParameter("context_type");
    String cId = request.getParameter("context_id");

    PortletRequestDispatcher prd;//from w  w w  .  j a v  a2 s. c  om

    GenomeFeature feature = null;

    DataApiHandler dataApi = new DataApiHandler(request);

    if (cType != null && cId != null && cType.equals("feature")) {
        feature = dataApi.getPATRICFeature(cId);
    }

    if (feature != null) {

        if (feature.getFeatureType().equals("CDS") || feature.getFeatureType().equals("mat_peptide")) {

            // to stuffs to here //
            // UniprotKBAccession
            String uniprotkbAccession = null;
            List<String> pdbIds = new ArrayList<>();
            {
                SolrQuery query = new SolrQuery("id_value:(" + feature.getGi() + ")");
                query.addFilterQuery("id_type:GI");

                LOGGER.debug("[{}] {}", SolrCore.ID_REF.getSolrCoreName(), query);

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

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

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

                for (Map<String, String> doc : docs) {
                    uniprotkbAccession = doc.get("uniprotkb_accession");
                }
            }
            {
                SolrQuery query = new SolrQuery("uniprotkb_accession:(" + uniprotkbAccession + ")");
                query.setRows(DataApiHandler.MAX_ROWS);
                LOGGER.debug("[{}] {}", SolrCore.ID_REF.getSolrCoreName(), query);

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

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

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

                for (Map<String, String> doc : docs) {
                    if (doc.get("id_type").equals("PDB")) {
                        pdbIds.add(doc.get("id_value"));
                    }
                }
            }

            // Structure Center related
            List<Map> listStructure = null;

            SolrQuery query = new SolrQuery(
                    "gene_symbol_collection:\"PATRIC_ID:" + feature.getPatricId() + "\"");
            query.addField("target_id,target_status,has_clones,has_proteins,selection_criteria");
            LOGGER.trace("[{}] {}", SolrCore.STRUCTURE, query);

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

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

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

            if (!docs.isEmpty()) {
                listStructure = docs;
            }

            // taxonomy genus name
            String genusName = null;
            Genome genome = dataApi.getGenome(feature.getGenomeId());
            if (genome != null) {
                genusName = genome.getGenus();
            }

            request.setAttribute("feature", feature);
            request.setAttribute("uniprotkbAccession", uniprotkbAccession);
            request.setAttribute("pdbIds", pdbIds);
            request.setAttribute("listStructure", listStructure);
            request.setAttribute("genusName", genusName);

            prd = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/functional_properties/protein.jsp");
            prd.include(request, response);
        } else if (feature.getFeatureType().contains("RNA")) {
            //            ResultType rnaInfo = conn_summary.getRNAInfo("" + feature.getP2FeatureId());
            //
            //            if (rnaInfo.containsKey("comment_string") && rnaInfo.get("comment_string").contains("structure:")) {
            //               String[] tmp = rnaInfo.get("comment_string").split("structure:");
            //               if (tmp[0] != null) {
            //                  rnaInfo.put("comment", tmp[0]);
            //               }
            //               if (tmp[1] != null) {
            //                  rnaInfo.put("structure", tmp[1]);
            //               }
            //            }
            //            else if (rnaInfo.containsKey("comment_string")) {
            //               rnaInfo.put("comment", rnaInfo.get("comment_string"));
            //            }
            //
            //            request.setAttribute("rna", rnaInfo);
            request.setAttribute("rna", new ResultType());
            prd = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/functional_properties/rna.jsp");
            prd.include(request, response);
        } else if (feature.getFeatureType().equals("misc_feature")) {
            String comment = ""; // conn_shared.getNaFeatureComment("" + feature.getP2FeatureId());
            request.setAttribute("comment", comment);
            prd = getPortletContext()
                    .getRequestDispatcher("/WEB-INF/jsp/functional_properties/misc_feature.jsp");
            prd.include(request, response);
        } else {
            PrintWriter writer = response.getWriter();
            writer.write("No information is available.");
            writer.close();
        }
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("No information is available.");
        writer.close();
    }
}