Java Code Examples for org.bson.Document#put()

The following examples show how to use org.bson.Document#put() . 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: CoreUserPasswordAuthProviderClientUnitTests.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfirmUser() {
  final StitchAuthRoutes routes = new StitchAppRoutes("my_app-12345").getAuthRoutes();
  final String token = "some";
  final String tokenId = "thing";
  final StitchDocRequest.Builder expectedRequestBuilder = new StitchDocRequest.Builder();
  expectedRequestBuilder.withHeaders(null)
      .withMethod(Method.POST)
      .withPath(routes.getAuthProviderExtensionRoute("userPassProvider", "confirm"));
  final Document expectedDoc = new Document("token", token);
  expectedDoc.put("tokenId", tokenId);
  expectedRequestBuilder.withDocument(expectedDoc);

  testClientCall(
      (client) -> {
        client.confirmUserInternal(token, tokenId);
        return null;
      },
      expectedRequestBuilder.build());
}
 
Example 2
Source File: TestCaseStore.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public String storeTestCase(String id, TestCase testCase) throws IResourceStore.ResourceStoreException {
    try {
        testCase.setLastRun(new Date(System.currentTimeMillis()));

        String json = jsonSerialization.serialize(testCase);
        Document document = Document.parse(json);

        if (id != null) {
            document.put("_id", new ObjectId(id));
        }

        testcaseCollection.insertOne(document);

        return document.get("_id").toString();
    } catch (IOException e) {
        log.debug(e.getLocalizedMessage(), e);
        throw new IResourceStore.ResourceStoreException(e.getLocalizedMessage(), e);
    }
}
 
Example 3
Source File: Memory.java    From Much-Assembly-Required with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Document mongoSerialise() {

    Document dbObject = new Document();

    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Deflater compressor = new Deflater(Deflater.BEST_SPEED, true);
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor);
        deflaterOutputStream.write(getBytes());
        deflaterOutputStream.close();
        byte[] compressedBytes = stream.toByteArray();

        dbObject.put("zipBytes", new String(Base64.getEncoder().encode(compressedBytes)));

    } catch (IOException e) {
        e.printStackTrace();
    }

    return dbObject;
}
 
Example 4
Source File: MarketDataServiceBasicImpl.java    From redtorch with MIT License 6 votes vote down vote up
@Override
public List<BarField> queryHistBar5SecList(long startTimestamp, long endTimestamp, String unifiedSymbol) {
	try {
		Document filter = new Document();
		Document dateDocument = new Document();
		dateDocument.put("$gte", startTimestamp);
		dateDocument.put("$lte", endTimestamp);
		filter.put("actionTimestamp", dateDocument);
		filter.put("unifiedSymbol", unifiedSymbol);

		BasicDBObject sortBO = new BasicDBObject();
		sortBO.put("actionTimestamp", 1);
		long beginTime = System.currentTimeMillis();
		List<Document> documentList = this.histMarketDataDBClient.find(histMarketDataDBName, COLLECTION_NAME_BAR_5_SEC, filter, sortBO);
		logger.info("查询Bar数据,数据库{},集合{},操作耗时{}ms,共{}条数据", histMarketDataDBName, COLLECTION_NAME_BAR_5_SEC, (System.currentTimeMillis() - beginTime), documentList.size());
		return documentListToBarList(documentList, MarketDataDBTypeEnum.MDDT_HIST.getValueDescriptor().getName());
	} catch (Exception e) {
		logger.error("查询历史5秒钟数据发生错误", e);
	}
	return new ArrayList<>();
}
 
Example 5
Source File: Clock.java    From Much-Assembly-Required with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Document mongoSerialise() {

    Document dbObject = new Document();
    dbObject.put("type", getClass().getCanonicalName());

    return dbObject;
}
 
Example 6
Source File: MongoResourceStorage.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public IHistoryResource<T> newHistoryResourceFor(IResource resource, boolean deleted) {
    Resource mongoResource = checkInternalResource(resource);
    Document historyObject = new Document(mongoResource.getMongoDocument());

    Document idObject = new Document();
    idObject.put(ID_FIELD, new ObjectId(resource.getId()));
    idObject.put(VERSION_FIELD, resource.getVersion());
    historyObject.put(ID_FIELD, idObject);
    if (deleted) {
        historyObject.put(DELETED_FIELD, true);
    }

    return new HistoryResource(historyObject);
}
 
Example 7
Source File: ChainInfo.java    From nuls-v2 with MIT License 5 votes vote down vote up
public Document toDocument() {
    Document document = new Document();
    document.put("_id", chainId);
    document.put("chainName", chainName);
    Document defaultAssetDoc = DocumentTransferTool.toDocument(defaultAsset);
    document.put("defaultAsset", defaultAssetDoc);

    document.put("assets", DocumentTransferTool.toDocumentList(assets));
    document.put("seeds", seeds);
    return document;
}
 
Example 8
Source File: MongoEventRepository.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private Document convert(Payload payload) {
    if (payload == null) {
        return null;
    }

    Document document = new Document();
    payload.put("action", payload.getAction().toString());
    document.put("content", payload);

    return document;
}
 
Example 9
Source File: OneM2MDmAdapter.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected Document firmwareUpdate(String deviceId, String url, String version, String packageName) throws HitDMException, IOException {
	String to = "/firmware";
	
	Document content = new Document();
	content.put("d", deviceId);
	content.put("url", url);
	content.put("version", version);
	content.put("pkgName", packageName);
	
	return callPostApi(to, content);
}
 
Example 10
Source File: DatabaseLogs.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private Document createFilter(Environment environment, String botId, String conversationId, String userId) {
    Document filter = new Document();
    filter.put(CONTEXT_MAP_ENVIRONMENT, environment.toString());
    filter.put(CONTEXT_MAP_BOT_ID, botId);
    if (conversationId != null) {
        filter.put(CONTEXT_MAP_CONVERSATION_ID, conversationId);
    }
    if (userId != null) {
        filter.put(CONTEXT_MAP_USER_ID, userId);
    }

    return filter;
}
 
Example 11
Source File: MongoDirectory.java    From lumongo with Apache License 2.0 5 votes vote down vote up
public MongoDirectory(MongoClient mongo, String ddName, String indexName, boolean sharded, int blockSize) throws MongoException, IOException {

		this.mongo = mongo;
		this.dbname = ddName;
		this.indexName = indexName;
		this.blockSize = blockSize;

		synchronized (MongoDirectory.class) {
			//get back a index number to use instead of the string
			//this is not a persisted number and is just in memory
			String key = dbname + "-" + indexName;
			Short indexNumber = indexNameToNumberMap.get(key);
			if (indexNumber == null) {
				indexNameToNumberMap.put(key, indexCount);
				indexNumber = indexCount;
				indexCount++;
			}
			this.indexNumber = indexNumber;
		}

		getFilesCollection().createIndex(new Document(FILE_NUMBER, 1));

		Document indexes = new Document();
		indexes.put(FILE_NUMBER, 1);
		indexes.put(BLOCK_NUMBER, 1);
		getBlocksCollection().createIndex(indexes);

		if (sharded) {
			String blockCollectionName = getBlocksCollection().getNamespace().getFullName();
			MongoDatabase db = mongo.getDatabase(MongoConstants.StandardDBs.ADMIN);
			Document shardCommand = new Document();
			shardCommand.put(MongoConstants.Commands.SHARD_COLLECTION, blockCollectionName);
			shardCommand.put(MongoConstants.Commands.SHARD_KEY, indexes);
			db.runCommand(shardCommand);
		}

		nameToFileMap = new ConcurrentHashMap<>();

		fetchInitialContents();
	}
 
Example 12
Source File: OneM2MDmAdapter.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected Document softwareUninstall(String deviceId, String url, String packageName) throws HitDMException, IOException {
	String to = "/software/unstall";
	
	Document content = new Document();
	content.put("d", deviceId);
	content.put("url", url);
	content.put("pkgName", packageName);
	
	//return callDocGetApi(to, content);	blocked in 2017-09-16
	return callPostApi(to, content);
}
 
Example 13
Source File: MongoNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/**
 * Convert note to document.
 */
private Document noteToDocument(Note note) {
  // note to JSON
  String json = note.toJson();
  // JSON to document
  Document doc = Document.parse(json);
  // set object id as note id
  doc.put(Fields.ID, note.getId());
  return doc;
}
 
Example 14
Source File: FindOptions.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * @param iterable the iterable to use
 * @param mapper   the mapper to use
 * @param type     the result type
 * @param <T>      the result type
 * @return the iterable instance for the query results
 * @morphia.internal
 */
public <T> FindIterable<T> apply(final FindIterable<T> iterable, final Mapper mapper, final Class<?> type) {
    if (projection != null) {
        iterable.projection(projection.map(mapper, type));
    }

    iterable.batchSize(batchSize);
    iterable.collation(collation);
    iterable.comment(comment);
    if (cursorType != null) {
        iterable.cursorType(cursorType);
    }
    iterable.hint(hint);
    iterable.hintString(hintString);
    iterable.limit(limit);
    iterable.max(max);
    iterable.maxAwaitTime(maxAwaitTimeMS, TimeUnit.MILLISECONDS);
    iterable.maxTime(maxTimeMS, TimeUnit.MILLISECONDS);
    iterable.min(min);
    iterable.noCursorTimeout(noCursorTimeout);
    iterable.oplogReplay(oplogReplay);
    iterable.partial(partial);
    iterable.returnKey(returnKey);
    iterable.showRecordId(showRecordId);
    iterable.skip(skip);
    if (sort != null) {
        Document mapped = new Document();
        MappedClass mappedClass = mapper.getMappedClass(type);
        for (final Entry<String, Object> entry : sort.entrySet()) {
            Object value = entry.getValue();
            boolean metaScore = value instanceof Document && ((Document) value).get("$meta") != null;
            mapped.put(new PathTarget(mapper, mappedClass, entry.getKey(), !metaScore).translatedPath(), value);
        }
        iterable.sort(mapped);
    }
    return iterable;
}
 
Example 15
Source File: OneM2MDmAdapter.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected Document readFirmwareStatus(String deviceId) throws HitDMException, IOException {
	String to = "/freemem";
	
	Document content = new Document();
	content.put("d", deviceId);
	
	return callDocGetApi(to, content);
}
 
Example 16
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testDeleteOne() {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  when(service.getCodecRegistry()).thenReturn(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoClient client =
      CoreRemoteClientFactory.getClient(
          service,
          getClientInfo(),
          null);
  final CoreRemoteMongoCollection<Document> coll = getCollection(client);

  doReturn(new RemoteDeleteResult(1))
      .when(service).callFunction(any(), any(), any(Decoder.class));

  final Document expectedFilter = new Document("one", 2);
  final RemoteDeleteResult result = coll.deleteOne(expectedFilter);
  assertEquals(1, result.getDeletedCount());

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<Collection<Document>>> resultClassArg =
      ArgumentCaptor.forClass(Decoder.class);
  verify(service)
      .callFunction(
          funcNameArg.capture(),
          funcArgsArg.capture(),
          resultClassArg.capture());

  assertEquals("deleteOne", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("query",
      expectedFilter.toBsonDocument(null, BsonUtils.DEFAULT_CODEC_REGISTRY));
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(ResultDecoders.deleteResultDecoder, resultClassArg.getValue());

  // Should pass along errors
  doThrow(new IllegalArgumentException("whoops"))
      .when(service).callFunction(any(), any(), any(Decoder.class));
  assertThrows(() -> coll.deleteOne(new Document()),
      IllegalArgumentException.class);
}
 
Example 17
Source File: ReferenceTest.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Test
public void testIdOnlyReferences() {
    final List<Ref> refs = asList(new Ref("foo"), new Ref("bar"), new Ref("baz"));
    final Container c = new Container(refs);

    // test that we can save it
    final ObjectId key = getDs().save(c).getId();
    getDs().save(refs);

    // ensure that we're not using DBRef
    final MongoCollection<Document> collection = getDocumentCollection(Container.class);
    final Document persisted = collection.find(new Document("_id", key)).first();
    assertNotNull(persisted);
    assertEquals("foo", persisted.get("singleRef"));
    assertEquals("foo", persisted.get("lazySingleRef"));

    final List<String> expectedList = new ArrayList<>();
    expectedList.add("foo");
    expectedList.add("bar");
    expectedList.add("baz");
    assertEquals(expectedList, persisted.get("collectionRef"));
    assertEquals(expectedList, persisted.get("lazyCollectionRef"));

    final Document expectedMap = new Document();
    expectedMap.put("0", "foo");
    expectedMap.put("1", "bar");
    expectedMap.put("2", "baz");
    assertEquals(expectedMap, persisted.get("mapRef"));
    assertEquals(expectedMap, persisted.get("lazyMapRef"));

    // ensure that we can retrieve it
    final Container retrieved = getDs().find(Container.class)
                                       .filter(eq("_id", key))
                                       .first();

    assertEquals(refs.get(0), retrieved.getSingleRef());
    if (assertProxyClassesPresent()) {
        assertIsProxy(retrieved.getLazySingleRef());
    }
    assertEquals(refs.get(0), retrieved.getLazySingleRef());

    final List<Ref> expectedRefList = new ArrayList<>();
    final Map<Integer, Ref> expectedRefMap = new LinkedHashMap<>();

    for (int i = 0; i < refs.size(); i++) {
        expectedRefList.add(refs.get(i));
        expectedRefMap.put(i, refs.get(i));
    }

    assertEquals(expectedRefList, retrieved.getCollectionRef());
    assertEquals(expectedRefList, retrieved.getLazyCollectionRef());
    assertEquals(expectedRefMap, retrieved.getMapRef());
    assertEquals(expectedRefMap.keySet(), retrieved.getLazyMapRef().keySet());
}
 
Example 18
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testFindOne() {
  final CoreStitchServiceClient service = Mockito.mock(CoreStitchServiceClient.class);
  when(service.getCodecRegistry()).thenReturn(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoClient client =
          CoreRemoteClientFactory.getClient(
                  service,
                  getClientInfo(),
                  null);
  final CoreRemoteMongoCollection<Document> coll = getCollection(client);

  final Document doc1 = new Document("one", 2);
  doReturn(doc1).when(service).callFunction(any(), any(), any(Decoder.class));

  // Test simple findOne
  final Document result1 = coll.findOne();
  assertEquals(result1, doc1);

  final ArgumentCaptor<String> funcNameArg = ArgumentCaptor.forClass(String.class);
  final ArgumentCaptor<List> funcArgsArg = ArgumentCaptor.forClass(List.class);
  final ArgumentCaptor<Decoder<Collection<Document>>> resultClassArg =
          ArgumentCaptor.forClass(Decoder.class);
  verify(service)
          .callFunction(
                  funcNameArg.capture(),
                  funcArgsArg.capture(),
                  resultClassArg.capture());

  assertEquals("findOne", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  final Document expectedArgs = new Document();
  expectedArgs.put("database", "dbName1");
  expectedArgs.put("collection", "collName1");
  expectedArgs.put("query", new BsonDocument());
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(DocumentCodec.class, resultClassArg.getValue().getClass());

  // Test more complicated findOne()
  final BsonDocument expectedFilter  = new BsonDocument("one", new BsonInt32(23));
  final BsonDocument expectedSort    = new BsonDocument("field1", new BsonInt32(1));
  final BsonDocument expectedProject = new BsonDocument("field2", new BsonInt32(-1));
  final RemoteFindOptions options    = new RemoteFindOptions()
          .limit(2)
          .projection(expectedProject)
          .sort(expectedSort);
  final Document result2 = coll.findOne(expectedFilter, options);
  assertEquals(result2, doc1);

  verify(service, times(2))
          .callFunction(
                  funcNameArg.capture(),
                  funcArgsArg.capture(),
                  resultClassArg.capture());

  assertEquals("findOne", funcNameArg.getValue());
  assertEquals(1, funcArgsArg.getValue().size());
  expectedArgs.put("query", expectedFilter);
  expectedArgs.put("project", expectedProject);
  expectedArgs.put("sort", expectedSort);
  assertEquals(expectedArgs, funcArgsArg.getValue().get(0));
  assertEquals(DocumentCodec.class, resultClassArg.getValue().getClass());

  // Test custom class
  doReturn(1).when(service).callFunction(any(), any(), any(Decoder.class));
  final int res = coll.findOne(expectedFilter, Integer.class);
  assertEquals(1, res);

  // Should pass along errors
  doThrow(new IllegalArgumentException("whoops"))
          .when(service).callFunction(any(), any(), any(Decoder.class));
  assertThrows(() -> coll.findOne(), IllegalArgumentException.class);
}
 
Example 19
Source File: HeritDMAdaptor.java    From SI with BSD 2-Clause "Simplified" License 3 votes vote down vote up
protected Document reboot(String deviceId) throws HitDMException {

		String to = "/hit/openapi/dm/reboot";
		
		Document content = new Document();
		content.put("d", deviceId);
		
		return callApi(to, content);	
		
	}
 
Example 20
Source File: Tr069DMAdapter.java    From SI with BSD 2-Clause "Simplified" License 3 votes vote down vote up
protected Document reboot(String deviceId) throws HitDMException {
	if(timeout < 0) {
		timeout = 3000;
	}
	
	String to = "/devices/" + deviceId + "/tasks?timeout=" + this.timeout + "&connection_request";
	
	Document content = new Document();
	content.put("name", "reboot");
	
	Document resultDoc = callPostApi(to, content);
	
	return resultDoc;
	
}