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

The following examples show how to use com.mongodb.BasicDBObject#append() . 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: ExecutionApp.java    From android-kubernetes-blockchain with Apache License 2.0 6 votes vote down vote up
private static void executeRequest(String data, MongoClient mongo) {
	String body;
	try {
		body = Task.post(executionURL, data);
		JsonObject jsonObj = new JsonParser().parse(body).getAsJsonObject();
		if (jsonObj.get("status").toString().equals("\"success\"")) {
			DB database = mongo.getDB(dbName);
			DBCollection collection = Task.getDBCollection(database, "results");
			List<DBObject> list = new ArrayList<>();
			BasicDBObject dataObject = new BasicDBObject();
			dataObject.append("resultId", jsonObj.get("resultId").getAsString());
			dataObject.append("query", data);
			list.add(dataObject);
			collection.insert(list);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: MongoDB.java    From act with GNU General Public License v3.0 6 votes vote down vote up
public Map<String, Long> constructAllInChIs() {
  Map<String, Long> chems = new HashMap<String, Long>();
  BasicDBObject keys = new BasicDBObject();
  keys.append("_id", true);
  keys.append("InChI", true);
  DBCursor cur = constructCursorForMatchingChemicals(null, null, keys);
  while (cur.hasNext()) {
    DBObject o = cur.next();
    long uuid = (Long)o.get("_id"); // checked: db type IS long
    String inchi = (String)o.get("InChI");
    chems.put(inchi, uuid);
  }

  cur.close();
  return chems;
}
 
Example 3
Source File: BatchSampleTest.java    From hvdf with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPushBatchToChannel() throws Exception {

	long sampleTime = TimeUnit.HOURS.toMillis(1);
	int batchSize = 1000;
	
	// put a sample in using default config
	Channel channel = getConfiguredChannel(null);
	
	// Construct a large batch
	BasicDBList batch = new BasicDBList();
	for(int i=0; i < batchSize; i++){
 	BasicDBObject sample = new BasicDBObject(Sample.TS_KEY, (i+1)*sampleTime);
 	sample.append(Sample.DATA_KEY, new BasicDBObject("v", i));
 	batch.add(sample);
	}  	
	
	channel.pushSample(batch, true, new BasicDBList());
	
	// get the sample by id
	List<Sample> samples = channel.query(null, TimeUnit.DAYS.toMillis(50), TimeUnit.DAYS.toMillis(50), null, null, 1000);
	assertEquals(samples.size(), 1000);
	Sample found = samples.get(0);
	assertEquals(found.getTimeStamp(), TimeUnit.HOURS.toMillis(batchSize));    	
}
 
Example 4
Source File: EntityDataController.java    From restfiddle with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/api/{projectId}/entities/{name}/{uuid}", method = RequestMethod.DELETE, headers = "Accept=application/json")
   public @ResponseBody
   StatusResponse deleteEntityData(@PathVariable("projectId") String projectId, @PathVariable("name") String entityName,
    @PathVariable("uuid") String uuid,
    @RequestHeader(value = "authToken", required = false) String authToken) {


StatusResponse res = new StatusResponse();

JSONObject authRes = authService.authorize(projectId,authToken,"USER");
if(!authRes.getBoolean(SUCCESS)){
    res.setStatus("Unauthorized");
    return res;
}

DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_"+entityName);
BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(uuid));
dbCollection.remove(queryObject);


res.setStatus("DELETED");

return res;
   }
 
Example 5
Source File: User.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return a DBObject that can be used for updating the user in the mongo database. We only include
 * the fields that the client should be changing (leave out the internal fields).
 */
public DBObject getDBObjectForModify() {
  BasicDBObject user = new BasicDBObject();
  user.append(JSON_KEY_USER_FIRST_NAME, firstName);
  user.append(JSON_KEY_USER_LAST_NAME, lastName);
  user.append(JSON_KEY_USER_WISH_LIST_LINK, wishListLink);

  // If the user logs in with Twitter, don't let them change their
  // twitter handle, username, or password.
  if (isTwitterLogin == false) {
    user.append(JSON_KEY_USER_TWITTER_HANDLE, twitterHandle);
    if (userName != null) {
      user.append(JSON_KEY_USER_NAME, userName);
    }
    if (passwordHash != null) {
      user.append(JSON_KEY_USER_PASSWORD_HASH, passwordHash);
    }
    if (passwordSalt != null) {
      user.append(JSON_KEY_USER_PASSWORD_SALT, passwordSalt);
    }
  }
  return user;
}
 
Example 6
Source File: User.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
/** Return an object suitable to create a new user in MongoDB. */
public BasicDBObject getDBObject(boolean includeId) {
  BasicDBObject user = new BasicDBObject();
  if (includeId) {
    user.append(DB_ID, new ObjectId(id));
  }
  user.append(JSON_KEY_USER_FIRST_NAME, firstName);
  user.append(JSON_KEY_USER_LAST_NAME, lastName);
  user.append(JSON_KEY_USER_NAME, userName);
  user.append(JSON_KEY_USER_TWITTER_HANDLE, twitterHandle);
  user.append(JSON_KEY_USER_WISH_LIST_LINK, wishListLink);
  user.append(JSON_KEY_USER_PASSWORD_HASH, passwordHash);
  user.append(JSON_KEY_USER_PASSWORD_SALT, passwordSalt);
  user.append(JSON_KEY_USER_TWITTER_LOGIN, isTwitterLogin);

  return user;
}
 
Example 7
Source File: ChannelConfigTest.java    From hvdf with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterceptorOrdering() throws Exception {

	String feedName = "feed3";
	String channelName = "channel1";
	String configPath = "plugin_config/interceptor_ordering.json";   	
	
	// Try to configure
	Channel channel = getConfiguredChannel(configPath, feedName, channelName);

	BasicDBObject sample = new BasicDBObject(Sample.TS_KEY, 100L);
	sample.append(Sample.DATA_KEY, new BasicDBObject("v", 240));
	channel.pushSample(sample, false, new BasicDBList());
	
	List<Sample> recalled = channel.query(null, 1000, 1000, null, null, 1);
	
	// The interceptors should have added the field x and then posted the values [2,1]
	BasicDBList testList = (BasicDBList) recalled.get(0).getData().get("x");
	assertEquals(testList.get(0), 2);
	assertEquals(testList.get(1), 1);   	
}
 
Example 8
Source File: DefaultGroupParser.java    From QueryBuilder with Apache License 2.0 6 votes vote down vote up
/**
 * 解析
 * @param group
 * @param parser
 * @return
 */
@Override
public Object parse(IGroup group, JsonRuleParser parser) {
    // rules
    BasicDBList operates = new BasicDBList();
    for (JsonRule jsonRule : group.getRules()) {
        operates.add(parser.parse(jsonRule));
    }

    // AND or OR
    BasicDBObject andOrObj = new BasicDBObject();
    andOrObj.append(EnumCondition.AND.equals(group.getCondition()) ? "$and" : "$or", operates);

    // Not
    if (group.getNot() != null && group.getNot()) {
        BasicDBList list = new BasicDBList();
        list.add(andOrObj);
        return new BasicDBObject("$nor", list);
    }
    return andOrObj;
}
 
Example 9
Source File: NotBetweenRuleParser.java    From QueryBuilder with Apache License 2.0 5 votes vote down vote up
public BasicDBObject parse(IRule rule, JsonRuleParser parser) {
    List<Object> values = (List<Object>) rule.getValue();
    BasicDBObject operate = new BasicDBObject();
    operate.append("$lt", values.get(0));
    operate.append("$gt", values.get(1));
    return new BasicDBObject(rule.getField(), operate);
}
 
Example 10
Source File: BingCacheMongoDB.java    From act with GNU General Public License v3.0 5 votes vote down vote up
public void updateTotalCountSearchResults(String formattedName, NameSearchResults nameSearchResults) {
  BasicDBObject whereQuery = new BasicDBObject();
  whereQuery.put("name", formattedName);
  // Update the existing document in the cache
  BasicDBObject newTotalCountSearchResults = new BasicDBObject();
  newTotalCountSearchResults.append("$set",
      new BasicDBObject().append("totalCountSearchResults", nameSearchResults.getTotalCountSearchResults()));
  dbBingCache.update(whereQuery, newTotalCountSearchResults);
}
 
Example 11
Source File: MongoTransactionServiceImpl.java    From nuls-v2 with MIT License 5 votes vote down vote up
public void deleteTxs(int chainId) {
    long totalCount = mongoDBService.getCount(TX_TABLE + chainId);
    if (totalCount > 1000000) {
        int deleteCount = (int) (totalCount - 1000000);
        BasicDBObject fields = new BasicDBObject();
        fields.append("_id", 1);
        List<Document> docList = this.mongoDBService.pageQuery(TX_TABLE + chainId, null, fields, Sorts.ascending("createTime"), 1, deleteCount);
        List<String> hashList = new ArrayList<>();
        for (Document document : docList) {
            hashList.add(document.getString("_id"));
        }
        mongoDBService.delete(TX_TABLE + chainId, Filters.in("_id", hashList));
    }
}
 
Example 12
Source File: MongoDbFeatureExecutor.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void executeScript(final String script, final MongoDatabase connection) {
    if (script.isEmpty()) {
        return;
    }
    final BasicDBObject command = new BasicDBObject();
    command.append("$eval", script);
    connection.runCommand(command);
}
 
Example 13
Source File: MongoDbDeltaStoreUtil.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public static BasicDBObject serialize(WaveletOperation waveletOp) {
  final BasicDBObject mongoOp = new BasicDBObject();

  if (waveletOp instanceof NoOp) {
    mongoOp.append(FIELD_TYPE, WAVELET_OP_NOOP);

  } else if (waveletOp instanceof AddParticipant) {
    mongoOp.append(FIELD_TYPE, WAVELET_OP_ADD_PARTICIPANT);
    mongoOp.append(FIELD_PARTICIPANT, serialize(((AddParticipant) waveletOp).getParticipantId()));

  } else if (waveletOp instanceof RemoveParticipant) {
    mongoOp.append(FIELD_TYPE, WAVELET_OP_REMOVE_PARTICIPANT);
    mongoOp.append(FIELD_PARTICIPANT,
        serialize(((RemoveParticipant) waveletOp).getParticipantId()));
  } else if (waveletOp instanceof WaveletBlipOperation) {
    final WaveletBlipOperation waveletBlipOp = (WaveletBlipOperation) waveletOp;

    mongoOp.append(FIELD_TYPE, WAVELET_OP_WAVELET_BLIP_OPERATION);
    mongoOp.append(FIELD_BLIPID, waveletBlipOp.getBlipId());

    if (waveletBlipOp.getBlipOp() instanceof BlipContentOperation) {
      mongoOp.append(FIELD_BLIPOP, serialize((BlipContentOperation) waveletBlipOp.getBlipOp()));
    } else {
      throw new IllegalArgumentException("Unsupported blip operation: "
          + waveletBlipOp.getBlipOp());
    }
  } else {
    throw new IllegalArgumentException("Unsupported wavelet operation: " + waveletOp);
  }
  return mongoOp;
}
 
Example 14
Source File: RollupStorageTest.java    From hvdf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinSingleField() throws Exception {

	long sampleTime = TimeUnit.MINUTES.toMillis(1);
	int testSize = 10000;
	int maxValue = 5;
	
	String configPath = "plugin_config/rollup_max_min_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 % (maxValue + 1)));
 	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());
	
	// Check every rollup document has a min of 0
	for(Sample rollupDoc : samples){
		BasicDBObject v = (BasicDBObject)rollupDoc.getData().get("v");
		assertEquals(0, (int)v.getInt("min"));
	}    	
}
 
Example 15
Source File: MongoQuery.java    From MongoDB-Plugin with Apache License 2.0 5 votes vote down vote up
public MongoQuery projection(String... keys) {
    BasicDBObject dbObj = new BasicDBObject();
    for (String key : keys) {
        dbObj.append(key, 1);
    }

    this.projection = dbObj;
    return this;
}
 
Example 16
Source File: PongoCollection.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public Iterable<T> find(QueryProducer... queries) {
		BasicDBObject obj = new BasicDBObject();
		BasicDBList list = new BasicDBList();
		
		for (int i = 0; i < queries.length; i++) {
			list.add(queries[i].getDBObject());
		}
		obj.append("$and", list);
//		System.out.println(obj.toString());
		return new IteratorIterable<T>(new PongoCursorIterator<T>(this, dbCollection.find(obj)));
	}
 
Example 17
Source File: MongoDbDeltaStoreUtil.java    From swellrt with Apache License 2.0 4 votes vote down vote up
public static BasicDBObject serialize(ParticipantId participantId) {
  BasicDBObject mongoParticipantId = new BasicDBObject();
  mongoParticipantId.append(FIELD_ADDRESS, participantId.getAddress());
  return mongoParticipantId;
}
 
Example 18
Source File: EntityAuthService.java    From restfiddle with Apache License 2.0 4 votes vote down vote up
public JSONObject authorize(String projectId, String authToken, String... roles) {

JSONObject response = new JSONObject();
if(authToken == null){
    return response.put(SUCCESS, false).put("msg", UNAUTHORIZED);
}

List<String> roleList = Arrays.asList(roles);

DBCollection dbCollection = mongoTemplate.getCollection(ENTITY_AUTH);

BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(authToken));

DBObject authData = dbCollection.findOne(queryObject);

if(authData != null && projectId.equals(authData.get("projectId"))) {
    DBRef userRef = (DBRef)authData.get("user");
    DBObject user = mongoTemplate.getCollection(userRef.getCollectionName()).findOne(userRef.getId());
    
    DBObject roleObj = null;
    if(user.containsField("role")){
	DBRef roleRef = (DBRef)user.get("role");
	roleObj = mongoTemplate.getCollection(roleRef.getCollectionName()).findOne(roleRef.getId());
    }
    
    if((roleObj != null && roleList.contains(roleObj.get("name"))) || roleList.contains("USER")){
	response.put(SUCCESS, true);
	response.put("user", userRef);
	
	authData.put("expireAt", new Date(System.currentTimeMillis() + 3600 * 1000));
	dbCollection.save(authData);
    } else {
	response.put(SUCCESS, false).put("msg", UNAUTHORIZED);
    }
} else {
    response.put(SUCCESS, false).put("msg", UNAUTHORIZED);
}

return response;
   }
 
Example 19
Source File: MongoDbDeltaStoreUtil.java    From swellrt with Apache License 2.0 4 votes vote down vote up
public static BasicDBObject serialize(DocOp docOp) {
  BasicDBObject mongoDocOp = new BasicDBObject();
  mongoDocOp.append(FIELD_BYTES, CoreWaveletOperationSerializer.serialize(docOp).toByteArray());
  return mongoDocOp;
}
 
Example 20
Source File: IndexingTaskTest.java    From hvdf with Apache License 2.0 3 votes vote down vote up
private void pushDataToChannel(Channel channel, 
   		String field, int numSamples, int samplePeriod, TimeUnit unit) {
   	
   	
   	long periodMs = TimeUnit.MILLISECONDS.convert(samplePeriod, unit);
   	
   	for(int i=0; i < numSamples; i++){
    	BasicDBObject sample = new BasicDBObject(Sample.TS_KEY, i*periodMs);
    	sample.append(Sample.DATA_KEY, new BasicDBObject("v", i));
    	channel.pushSample(sample, false, new BasicDBList());
   	}
   	
}