Java Code Examples for com.mongodb.BasicDBObject#get()

The following examples show how to use com.mongodb.BasicDBObject#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QueryBuilderTest.java    From XBDD with Apache License 2.0 6 votes vote down vote up
@Test
public void buildSimpleTestQuery() {
	final String[] searchCategories = { "name", "age" };
	final List<String> searchKeys = new ArrayList<>();
	searchKeys.add("hi");
	searchKeys.add("there");

	final BasicDBObject searchQuery = this.queryBuilder.getSearchQuery(searchKeys, this.coordinates, searchCategories);

	@SuppressWarnings("unchecked")
	final List<DBObject> queryResults = (ArrayList<DBObject>) searchQuery.get("$or");

	assertEquals("{\"name\": {\"$regex\": \"hi\", \"$options\": \"i\"}}", queryResults.get(0).toString());
	assertEquals("{\"age\": {\"$regex\": \"hi\", \"$options\": \"i\"}}", queryResults.get(1).toString());
	assertEquals("{\"name\": {\"$regex\": \"there\", \"$options\": \"i\"}}", queryResults.get(2).toString());
	assertEquals("{\"age\": {\"$regex\": \"there\", \"$options\": \"i\"}}", queryResults.get(3).toString());

}
 
Example 2
Source File: Group.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public boolean isEqual(BasicDBObject other) {
  BasicDBList oMembers = (BasicDBList) other.get(JSON_KEY_MEMBERS_LIST);

  return ((oMembers.containsAll(Arrays.asList(this.members))
          && oMembers.size() == this.members.length)
      && this.name.equals(other.get(JSON_KEY_GROUP_NAME))
      && this.id.equals(other.getString(DB_ID)));
}
 
Example 3
Source File: PongoViz.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param seriesKind
 * @param seriesLabel
 * @param xaxis
 * @param yaxis
 * @return
 */
protected String createDataTable(String seriesKind, String seriesLabel, String xaxis, String yaxis) {
	
	Iterator<DBObject> it = collection.find().iterator();
	
	List<List<Object>> dataTable = new ArrayList<List<Object>>();
	List<Object> headerRow = new ArrayList<Object>();
	dataTable.add(headerRow);
	
	while (it.hasNext()) {
		List<Object> row = new ArrayList<Object>();
		dataTable.add(row);
		
		// x-axis
		if (!headerRow.contains("\"Date\"")) headerRow.add("\"Date\"");
		DBObject dbobj = it.next();
		
		String x = (String)dbobj.get(xaxis);
		row.add("\"" + x + "\"");
		BasicDBList rd = (BasicDBList) dbobj.get(seriesKind);
		
		for (BasicDBObject bdbo : rd.toArray(new BasicDBObject[0])) {
			Object srs;
			if (seriesLabel.equals("")) {
				srs = "Series " + rd.indexOf(bdbo); 
			} else {
				srs = bdbo.get(seriesLabel);
			}
			String hdrName = "\"" + srs.toString() + "\"";
			if (!headerRow.contains(hdrName)) headerRow.add(hdrName);
			row.add(bdbo.get(yaxis));
		}
	}
	return dataTable.toString(); //FIXME: properly format this
}
 
Example 4
Source File: QueryModel.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private static BasicDBObject findOperation( BasicDBObject opObj, String operator )
{
    if( opObj == null )
        return null;
    Object op = opObj.get( operator );
    return op instanceof BasicDBObject ? (BasicDBObject)op : null;
}
 
Example 5
Source File: RollupStorageInterceptor.java    From hvdf with Apache License 2.0 5 votes vote down vote up
@Override
public void pushSample(DBObject sample, boolean isList, BasicDBList resultIds) {
	
	if(isList){
		
		// Use the batch API to send a number of samples
		updateBatch((BasicDBList)sample);			
	}
	else if(sample != null){
		
		// This is a document, place it straight in appropriate collection
		BasicDBObject doc = ((BasicDBObject) sample);
		long timestamp = this.rollupPeriod * (doc.getLong(Sample.TS_KEY) / this.rollupPeriod);			
		DBCollection collection = collectionAllocator.getCollection(timestamp);
		
		// Ask the id allocator for the query
		BasicDBObject query = this.idFactory.getQuery(sample.get(Sample.SOURCE_KEY), timestamp);
		
		// Build the update clause using the ops list
		BasicDBObject update = new BasicDBObject();
		for(RollupOperation rollupOp : this.rollupOps){
			
			DBObject updateClause = rollupOp.getUpdateClause(sample);
			
			// Check for top level operators that already exist so they dont overwrite
			for(String key : updateClause.keySet()){
				BasicDBObject existingClause = (BasicDBObject) update.get(key);
				if(existingClause != null){
					// Merge the arguments to the top level op
					existingClause.putAll((DBObject)updateClause.get(key));
				} else {
					update.put(key, updateClause.get(key));
				}
			}
		}
		
		collection.update(query, update, true, false);
	}
}
 
Example 6
Source File: QueryBuilderTest.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@Test
public void buildTestQueryWithEmptySearch() {
	final String[] searchCategories = { "name", "age" };
	final List<String> searchKeys = new ArrayList<>();
	searchKeys.add("");

	final BasicDBObject searchQuery = this.queryBuilder.getSearchQuery(searchKeys, this.coordinates, searchCategories);

	@SuppressWarnings("unchecked")
	final List<DBObject> queryResults = (ArrayList<DBObject>) searchQuery.get("$or");

	assertTrue(queryResults.isEmpty());
}
 
Example 7
Source File: Feature.java    From XBDD with Apache License 2.0 5 votes vote down vote up
private void formatStep(final BasicDBList changes, final BasicDBObject step,
		final boolean currManual, final boolean prevManual) {
	String currState, currCause, prevState, prevCause;

	final BasicDBObject currStep = ((BasicDBObject) step.get("curr"));
	if (((BasicDBObject) currStep.get("result")).get("manualStatus") != null) {
		currState = (String) ((BasicDBObject) currStep.get("result")).get("manualStatus");
		currCause = "manual";
	} else {
		currCause = "auto";
		if (currManual) {
			currState = "undefined";
		} else {
			currState = (String) ((BasicDBObject) currStep.get("result")).get("status");
		}
	}

	final BasicDBObject prevStep = ((BasicDBObject) step.get("prev"));
	if (((BasicDBObject) prevStep.get("result")).get("manualStatus") != null) {
		prevState = (String) ((BasicDBObject) prevStep.get("result")).get("manualStatus");
		prevCause = "manual";
	} else {
		prevCause = "auto";
		if (prevManual) {
			prevState = "undefined";
		} else {
			prevState = (String) ((BasicDBObject) prevStep.get("result")).get("status");
		}
	}

	// only add if different
	if (!currState.equals(prevState) || !currCause.equals(prevCause)) {
		final BasicDBObject stateChange = new BasicDBObject()
				.append("id", step.get("id"))
				.append("curr", currState)
				.append("prev", prevState);
		changes.add(stateChange);
	}
}
 
Example 8
Source File: Feature.java    From XBDD with Apache License 2.0 5 votes vote down vote up
private void updateAllSteps(final BasicDBList steps, final String status) {
	for (final Object step : steps) {
		final BasicDBObject dbStep = (BasicDBObject) step;
		final BasicDBObject result = (BasicDBObject) dbStep.get("result");
		result.put("manualStatus", status);
	}
}
 
Example 9
Source File: Feature.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/comments/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateCommentWithPatch(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
		final BasicDBObject patch) {
	try {
		final DBCollection collection = this.mongoLegacyDb.getCollection("features");
		final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
		final BasicDBObject storedFeature = (BasicDBObject) collection.findOne(example);

		final String scenarioId = (String) patch.get("scenarioId");
		final String label = (String) patch.get("label");
		final String content = (String) patch.get("content");

		final BasicDBObject featureToUpdate = (BasicDBObject) storedFeature.copy();
		final BasicDBObject scenarioToUpdate = getScenarioById(scenarioId, featureToUpdate);
		scenarioToUpdate.put(label, content);

		if (label.equals("testing-tips")) {
			final DBCollection tips = this.mongoLegacyDb.getCollection("testingTips");
			updateTestingTipsForScenario(tips, scenarioToUpdate, coordinates, featureId);
		}
		featureToUpdate.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
		featureToUpdate.put("lastEditOn", new Date());
		featureToUpdate.put("calculatedStatus", calculateStatusForFeature(featureToUpdate));
		collection.save(featureToUpdate);
		if (label.equals("testing-tips")) {
			Feature.embedTestingTips(featureToUpdate, coordinates, this.mongoLegacyDb);
		}
		return Response.ok().build();
	} catch (final Throwable th) {
		th.printStackTrace();
		return Response.serverError().build();
	}

}
 
Example 10
Source File: Feature.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/steps/{product}/{major}.{minor}.{servicePack}/{build}/{featureId:.+}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateStepsWithPatch(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId,
		final BasicDBObject patch) {
	try {
		final DBCollection collection = this.mongoLegacyDb.getCollection("features");
		final BasicDBObject example = coordinates.getReportCoordinatesQueryObject().append("id", featureId);
		final BasicDBObject storedFeature = (BasicDBObject) collection.findOne(example);

		final String status = (String) patch.get("status");
		final String scenarioId = (String) patch.get("scenarioId");

		final BasicDBObject featureToUpdate = (BasicDBObject) storedFeature.copy();
		final BasicDBObject scenarioToUpdate = getScenarioById(scenarioId, featureToUpdate);

		if (scenarioToUpdate.get("background") != null) {
			final BasicDBObject backgroundToUpdate = (BasicDBObject) (scenarioToUpdate.get("background"));
			final BasicDBList backgroundStepsToUpdate = (BasicDBList) (backgroundToUpdate.get("steps"));
			updateAllSteps(backgroundStepsToUpdate, status);

		}
		if (scenarioToUpdate.get("steps") != null) {
			final BasicDBList stepsToUpdate = (BasicDBList) (scenarioToUpdate.get("steps"));
			updateAllSteps(stepsToUpdate, status);
		}
		featureToUpdate.put("statusLastEditedBy", LoggedInUserUtil.getLoggedInUser().getDisplay());
		featureToUpdate.put("lastEditOn", new Date());
		featureToUpdate.put("calculatedStatus", calculateStatusForFeature(featureToUpdate));
		collection.save(featureToUpdate);
		return Response.ok().build();
	} catch (final Throwable th) {
		th.printStackTrace();
		return Response.serverError().build();
	}
}
 
Example 11
Source File: Feature.java    From XBDD with Apache License 2.0 5 votes vote down vote up
private boolean updateSteps(final BasicDBList steps, final int stepLine, final String status) {
	for (final Object step : steps) {
		final BasicDBObject dbStep = (BasicDBObject) step;
		if ((int) dbStep.get("line") == stepLine) {
			final BasicDBObject result = (BasicDBObject) dbStep.get("result");
			result.put("manualStatus", status);
			return true;
		}
	}
	return false;
}
 
Example 12
Source File: RequiredFieldsInterceptor.java    From hvdf with Apache License 2.0 5 votes vote down vote up
private void validate(BasicDBObject document, BasicDBList resultIds){
	
	if(document != null){
		
		// First check/retrieve the timestamp
		long timestamp = 0;
		Object tsObj = document.get(Sample.TS_KEY);
		if(tsObj == null){
			timestamp = System.currentTimeMillis();
			document.put(Sample.TS_KEY, timestamp);
		}
		else{
			try{
				// Timestamp must be a Long
				timestamp = (Long)tsObj;					
			
			} catch(ClassCastException ccex){
				
				try{
					// If not a Long, but other Number, convert
					timestamp = ((Number)tsObj).longValue();
					document.put(Sample.TS_KEY, timestamp);		
				} catch(Exception ex){
					throw new ServiceException("Illegal type for timestamp", 
							SampleError.INVALID_SAMPLE).set(Sample.TS_KEY, tsObj);
				}
			}
		}			
	}					
}
 
Example 13
Source File: MongoNativeExtractor.java    From deep-spark with Apache License 2.0 4 votes vote down vote up
/**
 * Calculate splits.
 *
 * @param collection the collection
 * @return the deep partition [ ]
 */
private DeepPartition[] calculateSplits(DBCollection collection) {

    BasicDBList splitData = getSplitData(collection);
    List<ServerAddress> serverAddressList = collection.getDB().getMongo().getServerAddressList();

    if (splitData == null) {
        Pair<BasicDBList, List<ServerAddress>> pair = getSplitDataCollectionShardEnviroment(getShards(collection),
                collection.getDB().getName(),
                collection.getName());
        splitData = pair.left;
        serverAddressList = pair.right;
    }

    Object lastKey = null; // Lower boundary of the first min split

    List<String> stringHosts = new ArrayList<>();

    for (ServerAddress serverAddress : serverAddressList) {
        stringHosts.add(serverAddress.toString());
    }
    int i = 0;

    MongoPartition[] partitions = new MongoPartition[splitData.size() + 1];

    for (Object aSplitData : splitData) {

        BasicDBObject currentKey = (BasicDBObject) aSplitData;

        Object currentO = currentKey.get(MONGO_DEFAULT_ID);

        partitions[i] = new MongoPartition(mongoDeepJobConfig.getRddId(), i, new DeepTokenRange(lastKey,
                currentO, stringHosts), MONGO_DEFAULT_ID);

        lastKey = currentO;
        i++;
    }
    QueryBuilder queryBuilder = QueryBuilder.start(MONGO_DEFAULT_ID);
    queryBuilder.greaterThanEquals(lastKey);
    partitions[i] = new MongoPartition(0, i, new DeepTokenRange(lastKey, null, stringHosts), MONGO_DEFAULT_ID);
    return partitions;
}
 
Example 14
Source File: OccasionResource.java    From sample-acmegifts with Eclipse Public License 1.0 4 votes vote down vote up
@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
public Response createOccasion(JsonObject json) {
  String method = "createOccasion";
  logger.entering(clazz, method, json);

  // Validate the JWT.  At this point, anyone create an occasion if they
  // have a valid JWT.
  try {
    validateJWT();
  } catch (JWTException jwte) {
    logger.exiting(clazz, method, Status.UNAUTHORIZED);
    return Response.status(Status.UNAUTHORIZED)
        .type(MediaType.TEXT_PLAIN)
        .entity(jwte.getMessage())
        .build();
  }

  Response response;
  // make sure we received some json
  if (null == json || json.toString().isEmpty()) {
    response = Response.status(400).entity("Create failed. Empty payload.").build();
  } else {
    logger.fine("json = " + json);
    Occasion occasion = new Occasion(json);
    BasicDBObject dbo = occasion.toDbo();
    logger.fine("dbo = " + dbo);

    // new json payload should not contain an id
    ObjectId id = (ObjectId) dbo.get(Occasion.OCCASION_ID_KEY);
    logger.fine("id = " + id);
    if (null != id && !id.toString().isEmpty()) {
      logger.fine("non null id, responding 400");
      response =
          Response.status(400)
              .entity(
                  "Create failed. Payload must not contain an ID. Recieved ID: \"" + id + "\"")
              .build();
    } else {
      // store the occasion and return the ID
      getCollection().insert(dbo);
      ObjectId occasionId = dbo.getObjectId(Occasion.OCCASION_ID_KEY);
      logger.fine("id: " + occasionId.toString());
      String jsonResp =
          new Occasion(occasionId, null, null, null, null, null, null, null).toString();
      logger.fine(jsonResp);
      response = Response.ok(jsonResp, MediaType.APPLICATION_JSON).build();
      occasion.setId(occasionId);

      // Schedule occasion with the orchestrator
      try {
        orchestrator.scheduleOccasion(occasion);
      } catch (ParseException e) {
        e.printStackTrace();
      }
    }
  }

  logger.exiting(clazz, method, response.readEntity(String.class));
  return response;
}
 
Example 15
Source File: RollupStorageTest.java    From hvdf with Apache License 2.0 4 votes vote down vote up
@Test
public void testRollupGroupCountField() throws Exception {

	long sampleTime = TimeUnit.MINUTES.toMillis(1);
	int testSize = 10000;
	
	String configPath = "plugin_config/rollup_group_count.json";
	Channel channel = getConfiguredChannel(configPath);
	
	for(int i=0; i < testSize; i++){
 	BasicDBObject sample = new BasicDBObject(Sample.TS_KEY, i*sampleTime);
 	sample.append(Sample.DATA_KEY, new BasicDBObject("v", i%25));
 	sample.append(Sample.SOURCE_KEY, "sensor1");
 	channel.pushSample(sample, false, new BasicDBList());
	}
	    	
	// get all the rollup documents
	List<Sample> samples = channel.query(null, TimeUnit.MINUTES.toMillis(testSize), 
			TimeUnit.MINUTES.toMillis(testSize), null, null, testSize);
	
	// Each document is 60 samples, may be a partial document at end
	assertEquals((testSize/60) + (testSize%60 > 0 ? 1 : 0), samples.size());
	
	int totalRollupCount = 0;
	for(Sample rollupDoc : samples){
		
		// For each doc, ensure the group count total matches the sample total
		BasicDBObject v = (BasicDBObject)rollupDoc.getData().get("v");
		int rollupCount = v.getInt("count");
		BasicDBObject groups = (BasicDBObject)v.get("group_count");
		int localTotal = 0;
		for(String groupKey : groups.keySet()){
			localTotal += groups.getInt(groupKey);
		}
		
    	assertEquals(rollupCount, localTotal);    	    		
		totalRollupCount += localTotal;
	}
	
	assertEquals(testSize, totalRollupCount);    	
}
 
Example 16
Source File: RollupStorageInterceptor.java    From hvdf with Apache License 2.0 4 votes vote down vote up
private void updateBatch(BasicDBList sample) {
	
	// The batch may span collection splits, so maintain
	// a current collection and batch operation
	BulkWriteOperation currentOp = null;
	int currentOpOffset = 0;
	int sampleIdx = 0;
	DBCollection currentColl = null;	
	
	logger.debug("Received batch of size : {}", sample.size());
	
	try{
		for(; sampleIdx < sample.size(); ++sampleIdx){
			
			// prepare the sample to batch
			BasicDBObject doc = (BasicDBObject) (sample.get(sampleIdx));
			long timestamp = this.rollupPeriod * (doc.getLong(Sample.TS_KEY) / this.rollupPeriod);			
			DBCollection collection = collectionAllocator.getCollection(timestamp);
			
			// if the collection has changed, commit the current
			// batch to the collection and start new
			if(collection.equals(currentColl) == false){
				executeBatchUpdate(currentOp, sample);
				currentColl = collection;
				currentOp = collection.initializeUnorderedBulkOperation();
				currentOpOffset = sampleIdx;
			}
			
			// put the doc insert into the batch
			// Ask the id allocator for the query
			BasicDBObject query = this.idFactory.getQuery(doc.get(Sample.SOURCE_KEY), timestamp);
			
			// Build the update clause using the ops list
			BasicDBObject update = new BasicDBObject();
			for(RollupOperation rollupOp : this.rollupOps){
				
				DBObject updateClause = rollupOp.getUpdateClause(doc);
				
				// Check for top level operators that already exist so they dont overwrite
				for(String key : updateClause.keySet()){
					BasicDBObject existingClause = (BasicDBObject) update.get(key);
					if(existingClause != null){
						// Merge the arguments to the top level op
						existingClause.putAll((DBObject)updateClause.get(key));
					} else {
						update.put(key, updateClause.get(key));
					}
				}
			}
			
			currentOp.find(query).upsert().updateOne(update);
		}		
		
		// Finalize the last batch
		executeBatchUpdate(currentOp, sample);		
		
	} catch(Exception ex){
		
		// One of the bulk writes has failed
		BasicDBList failedDocs = new BasicDBList();
		if(ex instanceof BulkWriteException){
			
			// We need to figure out the failures and remove the writes
			// that worked from the batch
			int batchSize = sampleIdx - currentOpOffset;
			BulkWriteException bwex = (BulkWriteException)ex;
			int errorCount = bwex.getWriteErrors().size(); 
			if(errorCount < batchSize){
				
				for(BulkWriteError we : bwex.getWriteErrors()){
					failedDocs.add(sample.get(currentOpOffset + we.getIndex()));
				}
				
				// since we have accounted for the failures in the current
				// batch, move the offset forward to the last sample
				currentOpOffset = sampleIdx;					
			}
		}
		
		// If this happened part way through the batch, send remaining 
		// docs to failed list and update sample to contain only failed docs
		if(currentOpOffset > 0){
			for(; currentOpOffset < sample.size(); ++currentOpOffset)
				failedDocs.add(sample.get(currentOpOffset));
			sample.clear();
			sample.addAll(failedDocs);	
		}
		
		throw ex;
	}
}
 
Example 17
Source File: IsCorrectQuery.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
private boolean matches(Query arg) {
        String queryKey;
        String argKey;

        for (String key : query.getQueryObject().keySet()) {
            queryKey = query.getQueryObject().get(key).getClass().getSimpleName();
            argKey = arg.getQueryObject().get(key).getClass().getSimpleName();

            if (!queryKey.equals(argKey)) {
                return false;
            } else if (queryKey.equals("BasicDBObject")) {
                BasicDBObject queryObj = (BasicDBObject) query.getQueryObject().get(key);
                BasicDBObject argObj = (BasicDBObject) arg.getQueryObject().get(key);

//                System.out.println(key);
//                System.out.print("\t"+queryObj);
//                System.out.println(" "+argObj);

                for (String key2 : queryObj.keySet()) {
                    if (queryObj.get(key2).getClass() != argObj.get(key2).getClass())
                    {
                        return false;
                    } else if (key2.equals("$in")) {
                        List<?> queryVal = (List<?>) queryObj.get(key2);
                        List<?> argVal = (List<?>) argObj.get(key2);
                        if (queryVal.size() != argVal.size()) {
                            return false;
                        }
                        for (int i = 0; i < queryVal.size(); ++i) {
                            if (!(queryVal.get(i).equals(argVal.get(i)))) {
                                return false;
                            }
                        }
                        return true;
                    }
                }
            } else if (!query.getQueryObject().get(key).equals(arg.getQueryObject().get(key))) {
                return false;
            }
        }

        return true;
    }
 
Example 18
Source File: MongoDB.java    From act with GNU General Public License v3.0 4 votes vote down vote up
public NamesOfMolecule getNamesFromBasicDBObject(BasicDBObject c) {

    String inchi = (String) c.get("InChI");

    NamesOfMolecule moleculeNames = new NamesOfMolecule(inchi);
    BasicDBObject names = (BasicDBObject) c.get("names");
    if (names != null) {
      BasicDBList brendaNamesList = (BasicDBList) names.get("brenda");
      if (brendaNamesList != null) {
        Set<String> brendaNames = new HashSet<>();
        for (Object brendaName : brendaNamesList) {
          brendaNames.add((String) brendaName);
        }
        moleculeNames.setBrendaNames(brendaNames);
      }
    }
    // XREF
    BasicDBObject xref = (BasicDBObject) c.get("xref");
    if (xref != null) {
      // CHEBI
      BasicDBObject chebi = (BasicDBObject) xref.get("CHEBI");
      if (chebi != null) {
        Set<String> chebiNames = new HashSet<>();
        BasicDBObject chebiMetadata = (BasicDBObject) chebi.get("metadata");
        BasicDBList chebiSynonymsList = (BasicDBList) chebiMetadata.get("Synonym");
        if (chebiSynonymsList != null) {
          for (Object chebiName : chebiSynonymsList) {
            chebiNames.add((String) chebiName);
          }
          moleculeNames.setChebiNames(chebiNames);
        }
      }
      // METACYC
      BasicDBObject metacyc = (BasicDBObject) xref.get("METACYC");
      if (metacyc != null) {
        Set<String> metacycNames = new HashSet<>();
        BasicDBList metacycMetadata = (BasicDBList) metacyc.get("meta");
        if (metacycMetadata != null) {
          for (Object metaCycMeta : metacycMetadata) {
            BasicDBObject metaCycMetaDBObject = (BasicDBObject) metaCycMeta;
            String metaCycName = (String) metaCycMetaDBObject.get("sname");
            if (metaCycName == null) {continue;}
            metacycNames.add(metaCycName);
          }
          moleculeNames.setMetacycNames(metacycNames);
        }
      }
      // DRUGBANK
      BasicDBObject drugbank = (BasicDBObject) xref.get("DRUGBANK");
      if (drugbank != null) {
        Set<String> drugbankNames = new HashSet<>();
        BasicDBObject drugbankMetadata = (BasicDBObject) drugbank.get("metadata");
        drugbankNames.add((String) drugbankMetadata.get("name"));
        BasicDBObject drugbankSynonyms = (BasicDBObject) drugbankMetadata.get("synonyms");
        if (drugbankSynonyms != null) {
          if (drugbankSynonyms.get("synonym") instanceof String) {
            drugbankNames.add((String) drugbankSynonyms.get("synonym"));
            moleculeNames.setDrugbankNames(drugbankNames);
          } else {
            BasicDBList drugbankSynonymsList = (BasicDBList) drugbankSynonyms.get("synonym");
            if (drugbankSynonymsList != null) {
              for (Object drugbankSynonym : drugbankSynonymsList) {
                drugbankNames.add((String) drugbankSynonym);
              }
              moleculeNames.setDrugbankNames(drugbankNames);
            }
          }
        }
        Set<String> drugbankBrands = new HashSet<>();
        BasicDBObject drugbankBrandsObject = (BasicDBObject) drugbankMetadata.get("brands");
        if (drugbankBrandsObject != null) {
          if (drugbankBrandsObject.get("brand") instanceof String) {
            drugbankBrands.add((String) drugbankBrandsObject.get("brand"));
            moleculeNames.setDrugbankBrands(drugbankBrands);
          } else {
            BasicDBList drugbankBrandsList = (BasicDBList) drugbankBrandsObject.get("brand");
            if (drugbankBrandsList != null) {
              for (Object drugbankBrand : drugbankBrandsList) {
                drugbankBrands.add((String) drugbankBrand);
              }
              moleculeNames.setDrugbankBrands(drugbankBrands);
            }
          }
        }
      }
      // WIKIPEDIA
      BasicDBObject wikipedia = (BasicDBObject) xref.get("WIKIPEDIA");
      if (wikipedia != null) {
        BasicDBObject wikipediaMetadata = (BasicDBObject) wikipedia.get("metadata");
        if (wikipediaMetadata != null) {
          String wikipediaName = (String) wikipediaMetadata.get("article");
          moleculeNames.setWikipediaName(wikipediaName);
        }
      }
    }
    return moleculeNames;
  }
 
Example 19
Source File: BingSearchRanker.java    From act with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Updates a TSV row (actually a Map from header to value) with InChI, names and usage information.
 * @param o BasicDBObject containing InChI, and xrefs.{BING, CHEBI, WIKIPEDIA} info
 * @param row TSV row (map from TSV header to value) to be updated
 */
private void updateRowWithChemicalInformation(BasicDBObject o, Map<String, String> row) {
  String inchi = o.get("InChI").toString();
  row.put(BingRankerHeaderFields.INCHI.name(), inchi);
  BasicDBObject xref = (BasicDBObject) o.get("xref");
  BasicDBObject bing = (BasicDBObject) xref.get("BING");
  BasicDBObject bingMetadata = (BasicDBObject) bing.get("metadata");
  row.put(BingRankerHeaderFields.BEST_NAME.name(), bingMetadata.get("best_name").toString());
  row.put(BingRankerHeaderFields.TOTAL_COUNT_SEARCH_RESULTS.name(),
      bingMetadata.get("total_count_search_results").toString());
  NamesOfMolecule namesOfMolecule = mongoDB.getNamesFromBasicDBObject(o);
  Set<String> names = namesOfMolecule.getAllNames();
  row.put(BingRankerHeaderFields.ALL_NAMES.name(), names.toString());
  if (includeChebiApplications) {
    BasicDBObject chebi = (BasicDBObject) xref.get("CHEBI");
    if (chebi != null) {
      BasicDBObject chebiMetadata = (BasicDBObject) chebi.get("metadata");
      BasicDBObject chebiApplications = (BasicDBObject) chebiMetadata.get("applications");
      if (chebiApplications != null) {
        row.put(BingRankerHeaderFields.CHEBI_MAIN_APPLICATIONS.name(),
            chebiApplications.get("main_applications").toString());
        row.put(BingRankerHeaderFields.CHEBI_DIRECT_APPLICATIONS.name(),
            chebiApplications.get("direct_applications").toString());
      } else {
        LOGGER.debug("ChEBI cross-reference found, but no ChEBI applications for %s", inchi);
        row.put(BingRankerHeaderFields.CHEBI_MAIN_APPLICATIONS.name(), EMPTY_STRING);
        row.put(BingRankerHeaderFields.CHEBI_DIRECT_APPLICATIONS.name(), EMPTY_STRING);
      }
    } else {
      LOGGER.debug("No ChEBI cross-reference found for %s", inchi);
    }
  }
  if (includeWikipediaUrl) {
    BasicDBObject wikipedia = (BasicDBObject) xref.get("WIKIPEDIA");
    if (wikipedia != null) {
      row.put(BingRankerHeaderFields.WIKIPEDIA_URL.name(), wikipedia.get("dbid").toString());
    } else {
      LOGGER.debug("No Wikipedia cross-reference found for %s", inchi);
      row.put(BingRankerHeaderFields.WIKIPEDIA_URL.name(), EMPTY_STRING);
    }
  }
  if (includeUsageExplorerUrl) {
   row.put(BingRankerHeaderFields.USAGE_EXPLORER_URL.name(), getUsageExplorerURLStringFromInchi(inchi));
  }
}
 
Example 20
Source File: OccasionResource.java    From sample-acmegifts with Eclipse Public License 1.0 4 votes vote down vote up
@POST
@Path("/run")
@Consumes(MediaType.APPLICATION_JSON)
public Response runOccasion(JsonObject json) {
  String method = "runOccasion";
  logger.entering(clazz, method, json);

  // Validate the JWT. At this point, anyone create an occasion if they
  // have a valid JWT.
  try {
    validateJWT();
  } catch (JWTException jwte) {
    logger.exiting(clazz, method, Status.UNAUTHORIZED);
    return Response.status(Status.UNAUTHORIZED)
        .type(MediaType.TEXT_PLAIN)
        .entity(jwte.getMessage())
        .build();
  }

  Response response;
  // make sure we received some json
  if (null == json || json.toString().isEmpty()) {
    response = Response.status(400).entity("Run failed. Empty payload.").build();
  } else {
    logger.fine("json = " + json);
    Occasion occasion = new Occasion(json);
    BasicDBObject dbo = occasion.toDbo();
    logger.fine("dbo = " + dbo);

    // new json payload should not contain an id
    ObjectId id = (ObjectId) dbo.get(Occasion.OCCASION_ID_KEY);
    logger.fine("ObjectId id = " + id + " Occasion id = " + occasion.getId());

    if (null == id || id.toString().isEmpty()) {
      logger.fine("non null id, responding 400");
      response = Response.status(400).entity("Run failed. Payload must contain an ID.").build();
    } else {
      // Run the occasion
      OccasionResponse occasionResponse = orchestrator.runOccasion(occasion);
      response = buildPostRunResponse(occasionResponse);
    }
  }

  logger.exiting(clazz, method, response);
  return response;
}