Example usage for com.mongodb BasicDBObject containsKey

List of usage examples for com.mongodb BasicDBObject containsKey

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject containsKey.

Prototype

@Deprecated
    @Override
    public boolean containsKey(final String key) 

Source Link

Usage

From source file:com.ikanow.infinit.e.api.knowledge.federated.SimpleFederatedQueryEngine.java

License:Open Source License

public BasicDBObject createDocFromJson(BasicDBList jsonList, String url, FederatedRequest request,
        SourceFederatedQueryConfigPojo endpointInfo) {
    BasicDBObject doc = null; // (don't create unless needed)
    BasicDBList ents = null;//from   www.jav a 2 s. co m
    StringBuffer entVals = null;
    HashSet<String> entDedup = null;

    if (_testMode) { // In test mode, need to return the JSON even if no entities are specified 
        doc = new BasicDBObject();
    }
    if (null != endpointInfo.docConversionMap) {
        for (Map.Entry<String, String> docInfo : endpointInfo.docConversionMap.entrySet()) {
            for (Object jsonObj : jsonList) {
                BasicDBObject json = (BasicDBObject) jsonObj;
                try {
                    String key = docInfo.getKey();
                    // (allow user to not prepend array: if they don't want to)
                    if ((1 == json.size()) && json.containsKey((Object) "array")) {
                        if (!key.startsWith("array:") && !key.startsWith(":array") && !key.startsWith("$:array")
                                && !key.startsWith("::") && !key.startsWith("$::")) {
                            if (key.startsWith(":")) { // jpath
                                key = ":array" + key;
                            } else if (key.startsWith("$:")) { // jpath
                                key = "$:array" + key.substring(1);
                            } else {
                                key = "array:" + key;
                            }
                        }
                    } //TESTED (by hand)
                    if (key.startsWith(":")) { // jpath
                        key = "$" + key;
                    }
                    // NOTE: *not* org.json.JSONArray
                    JSONArray candidateEntities = null;
                    if (key.startsWith("$")) {
                        JSONArray candidateEntities_tmp = JsonPath.read(json.toString(), key.replace(':', '.'));
                        if (null != candidateEntities_tmp) {
                            candidateEntities = new JSONArray();
                            for (Object o : candidateEntities_tmp) {
                                if (o instanceof String) {
                                    candidateEntities.add(o);
                                } else if (o instanceof JSONArray) {
                                    candidateEntities.addAll((JSONArray) o);
                                }
                            } //TESTED (displayUrl vs entities, 3.2)
                        }
                        //DEBUG
                        //System.out.println(candidateEntities);

                    } //(TESTED (permutations above by hand))
                    else {
                        String s = (String) MongoDbUtil.getProperty(json, key.replace(':', '.'));
                        if (null != s) {
                            candidateEntities = new JSONArray();
                            candidateEntities.add(s);
                        }
                    } //TESTED (3.1)                                 

                    if (null != candidateEntities)
                        for (int i = 0; i < candidateEntities.size(); ++i) {
                            Object o = candidateEntities.get(i);
                            if (!(o instanceof String)) {
                                continue;
                            }
                            String s = o.toString();
                            if (null == doc) {
                                doc = new BasicDBObject();
                                //(various fields added below)
                            }
                            if (docInfo.getValue().equalsIgnoreCase(DocumentPojo.displayUrl_)) {
                                doc.put(DocumentPojo.displayUrl_, s);
                            } //TESTED (3.1, 4.*)
                            else { // Entities!
                                if (null == ents) {
                                    ents = new BasicDBList();
                                }
                                String index = s.toLowerCase() + "/" + docInfo.getValue().toLowerCase();

                                if (null == entDedup) {
                                    entDedup = new HashSet<String>();
                                } else if (entDedup.contains(index)) { // Entity deduplication
                                    continue;
                                } //TESTED (3.2)
                                entDedup.add(index);

                                if (null == entVals) {
                                    entVals = new StringBuffer(": ");
                                } else {
                                    entVals.append(", ");
                                }
                                entVals.append(s);

                                String dimension = null;
                                if (null != endpointInfo.typeToDimensionMap) {
                                    try {
                                        dimension = EntityPojo.Dimension
                                                .valueOf(
                                                        endpointInfo.typeToDimensionMap.get(docInfo.getValue()))
                                                .toString();
                                    } catch (Exception e) {
                                    }
                                }
                                if (null == dimension) {
                                    dimension = EntityPojo.Dimension.What.toString();
                                } //TESTED (by hand)

                                // (alternative to "made up" values would be to go looking in the existing docs/ents?)
                                // (we'll try to avoid that for now...)
                                BasicDBObject ent = new BasicDBObject();
                                ent.put(EntityPojo.disambiguated_name_, s);
                                ent.put(EntityPojo.type_, docInfo.getValue());
                                ent.put(EntityPojo.dimension_, dimension);
                                ent.put(EntityPojo.relevance_, 1.0);
                                ent.put(EntityPojo.doccount_, 1L); // (ie relative to this query)
                                ent.put(EntityPojo.averageFreq_, 1.0);
                                ent.put(EntityPojo.datasetSignificance_, 10.0); // (ie relative to this query)
                                ent.put(EntityPojo.significance_, 10.0); // (ie relative to this query)
                                ent.put(EntityPojo.frequency_, 1.0);
                                ent.put(EntityPojo.index_, index);
                                ent.put(EntityPojo.queryCoverage_, 100.0); // (ie relative to this query)
                                ent.put(EntityPojo.totalfrequency_, 1.0); // (ie relative to this query)
                                ents.add(ent);
                            } //TESTED (3.1, 4.*)
                        }
                } catch (Exception e) {
                    //(do nothing? null or the wrong type)
                    //e.printStackTrace();
                }
            } //end loop over various JSON objects retrieved
        } //(End loop over doc conversion elements)
    } //TESTED (3.*, 4.*)

    if ((null == ents) && !_testMode) { // don't return unless there are any entities
        return null;
    } else if (null != doc) {
        // Insert mandatory fields:
        // (Note the query format is a little bit different, the following fields are converted to arrays:
        //  sourceKey, source, communityId, mediaType)
        doc.put(DocumentPojo._id_, new ObjectId());
        doc.put(DocumentPojo.url_, url);
        doc.put(DocumentPojo.created_, new Date());
        doc.put(DocumentPojo.modified_, new Date());
        doc.put(DocumentPojo.publishedDate_, new Date());
        doc.put(DocumentPojo.sourceKey_, endpointInfo.parentSource.getKey());
        doc.put(DocumentPojo.source_, endpointInfo.parentSource.getTitle());
        doc.put(DocumentPojo.communityId_, new ObjectId(request.communityIdStrs[0]));
        doc.put(DocumentPojo.mediaType_, endpointInfo.parentSource.getMediaType());
        doc.put(DocumentPojo.metadata_, new BasicDBObject("json", jsonList.toArray()));

        if ((null != entVals) && (entVals.length() > 165)) { // (arbitrary length)
            entVals.setLength(165);
            entVals.append("...");
        }
        doc.put(DocumentPojo.title_, new StringBuffer(endpointInfo.titlePrefix).append(": ")
                .append(request.requestParameter).append(entVals).toString());
        doc.put(DocumentPojo.entities_, ents);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(jsonList.toString());
        doc.put(DocumentPojo.description_, gson.toJson(je)); // (prettified JSON)            
    } //TESTED (3.*, 4.*)

    return doc;
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Public facing servlet to PATCH set values of an existing RERUM object.
 * @respond with state of new object in the body
 * @throws java.io.IOException//  ww  w .  j a va 2  s. c o  m
 * @throws javax.servlet.ServletException
 */
public void patchSetUpdate() throws IOException, ServletException, Exception {
    Boolean historyNextUpdatePassed = false;
    System.out.println("patch set update");
    if (null != processRequestBody(request, true) && methodApproval(request, "set")) {
        BasicDBObject query = new BasicDBObject();
        JSONObject received = JSONObject.fromObject(content);
        if (received.containsKey("@id")) {
            String updateHistoryNextID = received.getString("@id");
            query.append("@id", updateHistoryNextID);
            BasicDBObject originalObject = (BasicDBObject) mongoDBService
                    .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object
            BasicDBObject updatedObject = (BasicDBObject) originalObject.copy(); //A copy of the original, this will be saved as a new object.  Make all edits to this variable.
            boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject));
            boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject));
            if (alreadyDeleted) {
                writeErrorResponse("The object you are trying to update is deleted.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else if (isReleased) {
                writeErrorResponse("The object you are trying to update is released. Fork to make changes.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else {
                if (null != originalObject) {
                    Set<String> update_anno_keys = received.keySet();
                    int updateCount = 0;
                    //If the object already in the database contains the key found from the object recieved from the user...
                    for (String key : update_anno_keys) {
                        if (originalObject.containsKey(key)) { //Keys matched.  Ignore it, set only works for new keys.
                            //@cubap @theHabes do we want to build that this happened into the response at all?
                        } else { //this is a new key, this is a set. Allow null values.
                            updatedObject.append(key, received.get(key));
                            updateCount += 1;
                        }
                    }
                    if (updateCount > 0) {
                        JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning)
                        newObject = configureRerumOptions(newObject, true); //__rerum for the new object being created because of the update action
                        newObject.remove("@id"); //This is being saved as a new object, so remove this @id for the new one to be set.
                        //Since we ignore changes to __rerum for existing objects, we do no configureRerumOptions(updatedObject);
                        DBObject dbo = (DBObject) JSON.parse(newObject.toString());
                        String newNextID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo);
                        String newNextAtID = Constant.RERUM_ID_PREFIX + newNextID;
                        BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo);
                        dboWithObjectID.append("@id", newNextAtID);
                        newObject.element("@id", newNextAtID);
                        newObject.remove("_id");
                        mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID);
                        historyNextUpdatePassed = alterHistoryNext(updateHistoryNextID, newNextAtID); //update history.next or original object to include the newObject @id
                        if (historyNextUpdatePassed) {
                            System.out.println("object patch set updated: " + newNextAtID);
                            JSONObject jo = new JSONObject();
                            JSONObject iiif_validation_response = checkIIIFCompliance(newNextAtID, "2.1");
                            jo.element("code", HttpServletResponse.SC_OK);
                            jo.element("original_object_id", updateHistoryNextID);
                            jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response.
                            jo.element("iiif_validation", iiif_validation_response);
                            try {
                                addWebAnnotationHeaders(newNextID, isContainerType(newObject), isLD(newObject));
                                addLocationHeader(newObject);
                                response.addHeader("Content-Type", "application/json; charset=utf-8");
                                response.setContentType("UTF-8");
                                response.addHeader("Access-Control-Allow-Origin", "*");
                                response.setStatus(HttpServletResponse.SC_OK);
                                out = response.getWriter();
                                out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo));
                            } catch (IOException ex) {
                                Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } else {
                            //The error is already written to response.out, do nothing.
                        }
                    } else {
                        // Nothing could be patched
                        addLocationHeader(received);
                        writeErrorResponse("Nothing could be PATCHed", HttpServletResponse.SC_NO_CONTENT);
                    }
                } else {
                    //This could means it was an external object, but those fail for PATCH updates.
                    writeErrorResponse("Object " + received.getString("@id")
                            + " not found in RERUM, could not update.  PUT update to make this object a part of RERUM.",
                            HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        } else {
            writeErrorResponse("Object did not contain an @id, could not update.",
                    HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Public facing servlet to PATCH unset values of an existing RERUM object.
 * @respond with state of new object in the body
 * @throws java.io.IOException/*from  w w w. j  a  v a 2s  .  c  o m*/
 * @throws javax.servlet.ServletException
 */
public void patchUnsetUpdate() throws IOException, ServletException, Exception {
    Boolean historyNextUpdatePassed = false;
    System.out.println("Patch unset update");
    if (null != processRequestBody(request, true) && methodApproval(request, "unset")) {
        BasicDBObject query = new BasicDBObject();
        JSONObject received = JSONObject.fromObject(content);
        if (received.containsKey("@id")) {
            String updateHistoryNextID = received.getString("@id");
            query.append("@id", updateHistoryNextID);
            BasicDBObject originalObject = (BasicDBObject) mongoDBService
                    .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object
            BasicDBObject updatedObject = (BasicDBObject) originalObject.copy(); //A copy of the original, this will be saved as a new object.  Make all edits to this variable.
            boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject));
            boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject));
            if (alreadyDeleted) {
                writeErrorResponse("The object you are trying to update is deleted.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else if (isReleased) {
                writeErrorResponse("The object you are trying to update is released.  Fork to make changes.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else {
                if (null != originalObject) {
                    Set<String> update_anno_keys = received.keySet();
                    int updateCount = 0;
                    //If the object already in the database contains the key found from the object recieved from the user...
                    for (String key : update_anno_keys) {
                        if (originalObject.containsKey(key)) {
                            if (key.equals("@id") || key.equals("__rerum") || key.equals("objectID")
                                    || key.equals("_id")) {
                                // Ignore these in a PATCH.  DO NOT update, DO NOT count as an attempt to update
                            } else {
                                if (null != received.get(key)) { //Found matching keys and value is not null.  Ignore these.
                                    //@cubap @theHabes do we want to build that this happened into the response at all?
                                } else { //Found matching keys and value is null, this is an unset
                                    updatedObject.remove(key);
                                    updateCount += 1;
                                }
                            }
                        } else { //Original object does not contain this key, perhaps the user meant set.
                                 //@cubap @theHabes do we want to build that this happened into the response at all?
                        }
                    }
                    if (updateCount > 0) {
                        JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning)
                        newObject = configureRerumOptions(newObject, true); //__rerum for the new object being created because of the update action
                        newObject.remove("@id"); //This is being saved as a new object, so remove this @id for the new one to be set.
                        //Since we ignore changes to __rerum for existing objects, we do no configureRerumOptions(updatedObject);
                        DBObject dbo = (DBObject) JSON.parse(newObject.toString());
                        String newNextID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo);
                        String newNextAtID = Constant.RERUM_ID_PREFIX + newNextID;
                        BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo);
                        dboWithObjectID.append("@id", newNextAtID);
                        newObject.element("@id", newNextAtID);
                        newObject.remove("_id");
                        mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID);
                        historyNextUpdatePassed = alterHistoryNext(updateHistoryNextID, newNextAtID); //update history.next or original object to include the newObject @id
                        if (historyNextUpdatePassed) {
                            System.out.println("Patch unset updated: " + newNextAtID);
                            JSONObject jo = new JSONObject();
                            JSONObject iiif_validation_response = checkIIIFCompliance(newNextAtID, "2.1");
                            jo.element("code", HttpServletResponse.SC_OK);
                            jo.element("original_object_id", updateHistoryNextID);
                            jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response.
                            jo.element("iiif_validation", iiif_validation_response);
                            try {
                                addWebAnnotationHeaders(newNextID, isContainerType(newObject), isLD(newObject));
                                addLocationHeader(newObject);
                                response.addHeader("Access-Control-Allow-Origin", "*");
                                response.setStatus(HttpServletResponse.SC_OK);
                                response.addHeader("Content-Type", "application/json; charset=utf-8");
                                response.setContentType("UTF-8");
                                out = response.getWriter();
                                out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo));
                            } catch (IOException ex) {
                                Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } else {
                            //The error is already written to response.out, do nothing.
                        }
                    } else {
                        // Nothing could be patched
                        addLocationHeader(received);
                        writeErrorResponse("Nothing could be PATCHed", HttpServletResponse.SC_NO_CONTENT);
                    }
                } else {
                    //This could means it was an external object, but those fail for PATCH updates.
                    writeErrorResponse("Object " + received.getString("@id")
                            + " not found in RERUM, could not update.  PUT update to make this object a part of RERUM.",
                            HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        } else {
            writeErrorResponse("Object did not contain an @id, could not update.",
                    HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Update a given annotation. Cannot set or unset keys.  
 * @respond with state of new object in the body
 *//*w ww.  j a v  a2  s  . c o  m*/
public void patchUpdateObject() throws ServletException, Exception {
    Boolean historyNextUpdatePassed = false;
    System.out.println("trying to patch");
    if (null != processRequestBody(request, true) && methodApproval(request, "patch")) {
        BasicDBObject query = new BasicDBObject();
        JSONObject received = JSONObject.fromObject(content);
        if (received.containsKey("@id")) {
            String updateHistoryNextID = received.getString("@id");
            query.append("@id", updateHistoryNextID);
            BasicDBObject originalObject = (BasicDBObject) mongoDBService
                    .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object
            boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject));
            boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject));
            if (alreadyDeleted) {
                writeErrorResponse("The object you are trying to update is deleted.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else if (isReleased) {
                writeErrorResponse("The object you are trying to update is released.  Fork to make changes.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else {
                if (null != originalObject) {
                    BasicDBObject updatedObject = (BasicDBObject) originalObject.copy(); //A copy of the original, this will be saved as a new object.  Make all edits to this variable.
                    Set<String> update_anno_keys = received.keySet();
                    boolean triedToSet = false;
                    int updateCount = 0;
                    //If the object already in the database contains the key found from the object recieved from the user, update it barring a few special keys
                    //Users cannot update the __rerum property, so we ignore any update action to that particular field.  
                    for (String key : update_anno_keys) {
                        if (originalObject.containsKey(key)) {
                            //Skip keys we want to ignore and keys that match but have matching values
                            if (!(key.equals("@id") || key.equals("__rerum") || key.equals("objectID")
                                    || key.equals("_id")) && received.get(key) != originalObject.get(key)) {
                                updatedObject.remove(key);
                                updatedObject.append(key, received.get(key));
                                updateCount += 1;
                            }
                        } else {
                            triedToSet = true;
                            // break;
                        }
                    }
                    if (triedToSet) {
                        System.out.println("Patch meh 1");
                        //@cubap @theHabes We continued with what we could patch.  Do we tell the user at all?
                        //writeErrorResponse("A key you are trying to update does not exist on the object.  You can set with the patch_set or put_update action.", HttpServletResponse.SC_BAD_REQUEST);
                    } else if (updateCount == 0) {
                        System.out.println("Patch meh 2");
                        addLocationHeader(received);
                        writeErrorResponse("Nothing could be PATCHed", HttpServletResponse.SC_NO_CONTENT);
                    } else {
                        JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning)
                        newObject = configureRerumOptions(newObject, true); //__rerum for the new object being created because of the update action
                        newObject.remove("@id"); //This is being saved as a new object, so remove this @id for the new one to be set.
                        //Since we ignore changes to __rerum for existing objects, we do no configureRerumOptions(updatedObject);
                        DBObject dbo = (DBObject) JSON.parse(newObject.toString());
                        String newNextID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo);
                        String newNextAtID = Constant.RERUM_ID_PREFIX + newNextID;
                        BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo);
                        dboWithObjectID.append("@id", newNextAtID);
                        newObject.element("@id", newNextAtID);
                        newObject.remove("_id");
                        mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID);
                        historyNextUpdatePassed = alterHistoryNext(updateHistoryNextID, newNextAtID); //update history.next or original object to include the newObject @id
                        if (historyNextUpdatePassed) {
                            System.out.println("Patch updated object: " + newNextAtID);
                            JSONObject jo = new JSONObject();
                            JSONObject iiif_validation_response = checkIIIFCompliance(newNextAtID, "2.1");
                            jo.element("code", HttpServletResponse.SC_OK);
                            jo.element("original_object_id", updateHistoryNextID);
                            jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response.
                            jo.element("iiif_validation", iiif_validation_response);
                            try {
                                addWebAnnotationHeaders(newNextID, isContainerType(newObject), isLD(newObject));
                                addLocationHeader(newObject);
                                response.addHeader("Access-Control-Allow-Origin", "*");
                                response.setStatus(HttpServletResponse.SC_OK);
                                response.addHeader("Content-Type", "application/json; charset=utf-8");
                                response.setContentType("UTF-8");
                                out = response.getWriter();
                                out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo));
                            } catch (IOException ex) {
                                Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } else {
                            //The error is already written to response.out, do nothing.
                        }
                    }
                } else {
                    writeErrorResponse(
                            "Object " + received.getString("@id")
                                    + " not found in RERUM, could not patch update.",
                            HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        } else {
            writeErrorResponse("Object did not contain an @id, could not patch update.",
                    HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file:org.opencb.cellbase.mongodb.db.ClinicalMongoDBAdaptor.java

License:Apache License

private List<QueryResult> prepareClinvarQueryResultList(List<QueryResult> clinicalQueryResultList) {
    List<QueryResult> queryResultList = new ArrayList<>();
    for (QueryResult clinicalQueryResult : clinicalQueryResultList) {
        QueryResult queryResult = new QueryResult();
        queryResult.setId(clinicalQueryResult.getId());
        queryResult.setDbTime(clinicalQueryResult.getDbTime());
        BasicDBList basicDBList = new BasicDBList();
        int numResults = 0;
        for (BasicDBObject clinicalRecord : (List<BasicDBObject>) clinicalQueryResult.getResult()) {
            if (clinicalRecord.containsKey("clinvarList")) {
                basicDBList.add(clinicalRecord);
                numResults += 1;/*from   www  . j a  v a  2  s.  co  m*/
            }
        }
        queryResult.setResult(basicDBList);
        queryResult.setNumResults(numResults);
        queryResultList.add(queryResult);
    }
    return queryResultList;
}

From source file:org.opencb.cellbase.mongodb.db.variation.VariantAnnotationMongoDBAdaptor.java

License:Apache License

public List<QueryResult> getAnnotationByVariantList(List<GenomicVariant> variantList,
        QueryOptions queryOptions) {/* w  ww.j  a  va  2  s.  c om*/

    // TODO: validation of queryoption 'include' values
    List<String> includeList = queryOptions.getAsStringList("include");
    if (includeList.isEmpty()) {
        includeList = Arrays.asList("variation", "clinical", "consequenceType", "conservation",
                "drugInteraction");
    }

    List<QueryResult> annotations = null;
    List<QueryResult> variationQueryResultList = null;
    if (includeList.contains("variation")) {
        variationQueryResultList = variationDBAdaptor.getAllByVariantList(variantList, queryOptions);
        annotations = variationQueryResultList;
    }
    List<QueryResult> clinicalQueryResultList = null;
    if (includeList.contains("clinical")) {
        clinicalQueryResultList = clinicalDBAdaptor.getAllByGenomicVariantList(variantList, queryOptions);
        if (annotations == null) {
            annotations = clinicalQueryResultList;
        }
    }
    //        List<QueryResult> variationConsequenceTypeList = null;
    //        if (includeList.contains("consequenceType")) {
    //            variationConsequenceTypeList = getAllConsequenceTypesByVariantList(variantList, queryOptions);
    //            if (annotations == null) {
    //                annotations = variationConsequenceTypeList;
    //            }
    //        }
    List<QueryResult> conservedRegionQueryResultList = null;
    if (includeList.contains("conservation")) {
        conservedRegionQueryResultList = conservedRegionDBAdaptor
                .getAllScoresByRegionList(variantListToRegionList(variantList), queryOptions);
        if (annotations == null) {
            annotations = conservedRegionQueryResultList;
        }
    }

    for (int i = 0; i < variantList.size(); i++) {
        // TODO: start & end are both being set to variantList.get(i).getPosition(), modify this for indels
        VariantAnnotation variantAnnotation = new VariantAnnotation(variantList.get(i).getChromosome(),
                variantList.get(i).getPosition(), variantList.get(i).getPosition(),
                variantList.get(i).getReference(), variantList.get(i).getAlternative());

        if (clinicalQueryResultList != null) {
            QueryResult clinicalQueryResult = clinicalQueryResultList.get(i);
            if (clinicalQueryResult.getResult() != null && clinicalQueryResult.getResult().size() > 0) {
                variantAnnotation.setClinical((Map<String, Object>) clinicalQueryResult.getResult().get(0));
            }
        }

        //            if (variationConsequenceTypeList != null) {
        if (includeList.contains("consequenceType")) {
            variantAnnotation.setConsequenceTypes(
                    (List<ConsequenceType>) getAllConsequenceTypesByVariant(variantList.get(i),
                            new QueryOptions()).getResult());
        }

        if (includeList.contains("drugInteraction")) {
            Map<String, List<Object>> geneDrugInteractionMap = new HashMap<>(1);
            geneDrugInteractionMap.put("dgidb", getGeneDrugInteractions(variantList.get(i)));
            variantAnnotation.setGeneDrugInteraction(geneDrugInteractionMap);
        }

        if (conservedRegionQueryResultList != null) {
            variantAnnotation
                    .setConservationScores((List<Score>) conservedRegionQueryResultList.get(i).getResult());
        }

        List<BasicDBObject> variationDBList = null;
        if (variationQueryResultList != null) {
            variationDBList = (List<BasicDBObject>) variationQueryResultList.get(i).getResult();
        }

        if (variationDBList != null && variationDBList.size() > 0) {
            String id = variationDBList.get(0).get("id").toString();
            variantAnnotation.setId(id);

            BasicDBList freqsDBList = (BasicDBList) variationDBList.get(0).get("populationFrequencies");
            if (freqsDBList != null) {
                BasicDBObject freqDBObject;
                for (int j = 0; j < freqsDBList.size(); j++) {
                    freqDBObject = ((BasicDBObject) freqsDBList.get(j));
                    if (freqDBObject != null) {
                        if (freqDBObject.containsKey("study")) {
                            variantAnnotation.addPopulationFrequency(new PopulationFrequency(
                                    freqDBObject.get("study").toString(), freqDBObject.get("pop").toString(),
                                    freqDBObject.get("superPop").toString(),
                                    freqDBObject.get("refAllele").toString(),
                                    freqDBObject.get("altAllele").toString(),
                                    Float.valueOf(freqDBObject.get("refAlleleFreq").toString()),
                                    Float.valueOf(freqDBObject.get("altAlleleFreq").toString())));
                        } else {
                            variantAnnotation.addPopulationFrequency(new PopulationFrequency("1000G_PHASE_3",
                                    freqDBObject.get("pop").toString(), freqDBObject.get("superPop").toString(),
                                    freqDBObject.get("refAllele").toString(),
                                    freqDBObject.get("altAllele").toString(),
                                    Float.valueOf(freqDBObject.get("refAlleleFreq").toString()),
                                    Float.valueOf(freqDBObject.get("altAlleleFreq").toString())));
                        }
                    }
                }
            }
        }
        List<VariantAnnotation> value = Collections.singletonList(variantAnnotation);
        annotations.get(i).setResult(value);
    }

    return annotations;
    //        return clinicalQueryResultList;
}