Search in sources :

Example 16 with ObjectId

use of org.bson.types.ObjectId in project mongo-java-driver by mongodb.

the class WorkerCodec method decode.

@Override
public Worker decode(final BsonReader reader, final DecoderContext decoderContext) {
    reader.readStartDocument();
    ObjectId id = reader.readObjectId("_id");
    String name = reader.readString("name");
    String jobTitle = reader.readString("jobTitle");
    Date dateStarted = new Date(reader.readDateTime("dateStarted"));
    int numberOfJobs = reader.readInt32("numberOfJobs");
    reader.readEndDocument();
    return new Worker(id, name, jobTitle, dateStarted, numberOfJobs);
}
Also used : BsonObjectId(org.bson.BsonObjectId) ObjectId(org.bson.types.ObjectId) Date(java.util.Date)

Example 17 with ObjectId

use of org.bson.types.ObjectId in project mongo-java-driver by mongodb.

the class DBCollection method insert.

/**
     * <p>Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document
     * does not contain an '_id' field, it will be added.</p>
     *
     * <p>If the value of the continueOnError property of the given {@code InsertOptions} is true,
     * that value will override the value of the continueOnError property of the given {@code WriteConcern}. Otherwise,
     * the value of the continueOnError property of the given {@code WriteConcern} will take effect. </p>
     *
     * @param documents     a list of {@code DBObject}'s to be inserted
     * @param insertOptions the options to use for the insert
     * @return the result of the operation
     * @throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key
     * @throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the insert command
     * @throws MongoException if the operation failed for some other reason
     * @mongodb.driver.manual tutorial/insert-documents/ Insert Documents
     */
public WriteResult insert(final List<? extends DBObject> documents, final InsertOptions insertOptions) {
    WriteConcern writeConcern = insertOptions.getWriteConcern() != null ? insertOptions.getWriteConcern() : getWriteConcern();
    Encoder<DBObject> encoder = toEncoder(insertOptions.getDbEncoder());
    List<InsertRequest> insertRequestList = new ArrayList<InsertRequest>(documents.size());
    for (DBObject cur : documents) {
        if (cur.get(ID_FIELD_NAME) == null) {
            cur.put(ID_FIELD_NAME, new ObjectId());
        }
        insertRequestList.add(new InsertRequest(new BsonDocumentWrapper<DBObject>(cur, encoder)));
    }
    return insert(insertRequestList, writeConcern, insertOptions.isContinueOnError(), insertOptions.getBypassDocumentValidation());
}
Also used : ObjectId(org.bson.types.ObjectId) InsertRequest(com.mongodb.bulk.InsertRequest) ArrayList(java.util.ArrayList) BsonDocumentWrapper(org.bson.BsonDocumentWrapper)

Example 18 with ObjectId

use of org.bson.types.ObjectId in project mongo-java-driver by mongodb.

the class BasicBSONEncoder method _putObjectField.

/**
     * Encodes any Object type
     *
     * @param name         the field name
     * @param initialValue the value to write
     */
protected void _putObjectField(final String name, final Object initialValue) {
    if ("_transientFields".equals(name)) {
        return;
    }
    if (name.contains("\0")) {
        throw new IllegalArgumentException("Document field names can't have a NULL character. (Bad Key: '" + name + "')");
    }
    if ("$where".equals(name) && initialValue instanceof String) {
        putCode(name, new Code((String) initialValue));
    }
    Object value = BSON.applyEncodingHooks(initialValue);
    if (value == null) {
        putNull(name);
    } else if (value instanceof Date) {
        putDate(name, (Date) value);
    } else if (value instanceof Number) {
        putNumber(name, (Number) value);
    } else if (value instanceof Decimal128) {
        putDecimal128(name, (Decimal128) value);
    } else if (value instanceof Character) {
        putString(name, value.toString());
    } else if (value instanceof String) {
        putString(name, value.toString());
    } else if (value instanceof ObjectId) {
        putObjectId(name, (ObjectId) value);
    } else if (value instanceof Boolean) {
        putBoolean(name, (Boolean) value);
    } else if (value instanceof Pattern) {
        putPattern(name, (Pattern) value);
    } else if (value instanceof Iterable) {
        putIterable(name, (Iterable) value);
    } else if (value instanceof BSONObject) {
        putObject(name, (BSONObject) value);
    } else if (value instanceof Map) {
        putMap(name, (Map) value);
    } else if (value instanceof byte[]) {
        putBinary(name, (byte[]) value);
    } else if (value instanceof Binary) {
        putBinary(name, (Binary) value);
    } else if (value instanceof UUID) {
        putUUID(name, (UUID) value);
    } else if (value.getClass().isArray()) {
        putArray(name, value);
    } else if (value instanceof Symbol) {
        putSymbol(name, (Symbol) value);
    } else if (value instanceof BSONTimestamp) {
        putTimestamp(name, (BSONTimestamp) value);
    } else if (value instanceof CodeWScope) {
        putCodeWScope(name, (CodeWScope) value);
    } else if (value instanceof Code) {
        putCode(name, (Code) value);
    } else if (value instanceof DBRef) {
        BSONObject temp = new BasicBSONObject();
        DBRef dbRef = (DBRef) value;
        temp.put("$ref", dbRef.getCollectionName());
        temp.put("$id", dbRef.getId());
        if (dbRef.getDatabaseName() != null) {
            temp.put("$db", dbRef.getDatabaseName());
        }
        putObject(name, temp);
    } else if (value instanceof MinKey) {
        putMinKey(name);
    } else if (value instanceof MaxKey) {
        putMaxKey(name);
    } else if (putSpecial(name, value)) {
    // no-op
    } else {
        throw new IllegalArgumentException("Can't serialize " + value.getClass());
    }
}
Also used : Pattern(java.util.regex.Pattern) ObjectId(org.bson.types.ObjectId) Symbol(org.bson.types.Symbol) DBRef(com.mongodb.DBRef) MaxKey(org.bson.types.MaxKey) BSONTimestamp(org.bson.types.BSONTimestamp) Decimal128(org.bson.types.Decimal128) Code(org.bson.types.Code) Date(java.util.Date) CodeWScope(org.bson.types.CodeWScope) MinKey(org.bson.types.MinKey) Binary(org.bson.types.Binary) UUID(java.util.UUID) Map(java.util.Map)

Example 19 with ObjectId

use of org.bson.types.ObjectId in project mongo-java-driver by mongodb.

the class ServerDescriptionTest method testBuilder.

@Test
public void testBuilder() throws UnknownHostException {
    IllegalArgumentException exception = new IllegalArgumentException();
    ServerDescription serverDescription = builder().address(new ServerAddress("localhost:27018")).type(ServerType.REPLICA_SET_PRIMARY).tagSet(new TagSet(new Tag("dc", "ny"))).setName("test").maxDocumentSize(100).roundTripTime(50000, java.util.concurrent.TimeUnit.NANOSECONDS).primary("localhost:27017").canonicalAddress("localhost:27018").hosts(new HashSet<String>(asList("localhost:27017", "localhost:27018", "localhost:27019", "localhost:27020"))).arbiters(new HashSet<String>(asList("localhost:27019"))).passives(new HashSet<String>(asList("localhost:27020"))).ok(true).state(CONNECTED).version(new ServerVersion(asList(2, 4, 1))).minWireVersion(1).maxWireVersion(2).electionId(new ObjectId("123412341234123412341234")).setVersion(new Integer(2)).lastWriteDate(new Date(1234L)).lastUpdateTimeNanos(40000L).exception(exception).build();
    assertEquals(new ServerAddress("localhost:27018"), serverDescription.getAddress());
    assertTrue(serverDescription.isOk());
    assertEquals(CONNECTED, serverDescription.getState());
    assertEquals(REPLICA_SET_PRIMARY, serverDescription.getType());
    assertTrue(serverDescription.isReplicaSetMember());
    assertFalse(serverDescription.isShardRouter());
    assertFalse(serverDescription.isStandAlone());
    assertTrue(serverDescription.isPrimary());
    assertFalse(serverDescription.isSecondary());
    assertEquals(50000, serverDescription.getRoundTripTimeNanos(), 0L);
    assertEquals(100, serverDescription.getMaxDocumentSize());
    assertEquals("localhost:27017", serverDescription.getPrimary());
    assertEquals("localhost:27018", serverDescription.getCanonicalAddress());
    assertEquals(new HashSet<String>(asList("localhost:27017", "localhost:27018", "localhost:27019", "localhost:27020")), serverDescription.getHosts());
    assertEquals(new TagSet(new Tag("dc", "ny")), serverDescription.getTagSet());
    assertEquals(new HashSet<String>(asList("localhost:27019")), serverDescription.getArbiters());
    assertEquals(new HashSet<String>(asList("localhost:27020")), serverDescription.getPassives());
    assertEquals("test", serverDescription.getSetName());
    assertEquals(new ServerVersion(asList(2, 4, 1)), serverDescription.getVersion());
    assertEquals(1, serverDescription.getMinWireVersion());
    assertEquals(2, serverDescription.getMaxWireVersion());
    assertEquals(new ObjectId("123412341234123412341234"), serverDescription.getElectionId());
    assertEquals(new Integer(2), serverDescription.getSetVersion());
    assertEquals(new Date(1234), serverDescription.getLastWriteDate());
    assertEquals(40000L, serverDescription.getLastUpdateTime(TimeUnit.NANOSECONDS));
    assertEquals(exception, serverDescription.getException());
}
Also used : ObjectId(org.bson.types.ObjectId) TagSet(com.mongodb.TagSet) ServerAddress(com.mongodb.ServerAddress) Tag(com.mongodb.Tag) Date(java.util.Date) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 20 with ObjectId

use of org.bson.types.ObjectId in project mongo-java-driver by mongodb.

the class DBCollectionTest method shouldAcceptDocumentsWithAllValidValueTypes.

@Test
public void shouldAcceptDocumentsWithAllValidValueTypes() {
    BasicDBObject doc = new BasicDBObject();
    doc.append("_id", new ObjectId());
    doc.append("bool", true);
    doc.append("int", 3);
    doc.append("short", (short) 4);
    doc.append("long", 5L);
    doc.append("str", "Hello MongoDB");
    doc.append("float", 6.0f);
    doc.append("double", 1.1);
    doc.append("date", new Date());
    doc.append("ts", new BSONTimestamp(5, 1));
    doc.append("pattern", Pattern.compile(".*"));
    doc.append("minKey", new MinKey());
    doc.append("maxKey", new MaxKey());
    doc.append("js", new Code("code"));
    doc.append("jsWithScope", new CodeWScope("code", new BasicDBObject()));
    doc.append("null", null);
    doc.append("uuid", UUID.randomUUID());
    doc.append("db ref", new com.mongodb.DBRef("test", new ObjectId()));
    doc.append("binary", new Binary((byte) 42, new byte[] { 10, 11, 12 }));
    doc.append("byte array", new byte[] { 1, 2, 3 });
    doc.append("int array", new int[] { 4, 5, 6 });
    doc.append("list", asList(7, 8, 9));
    doc.append("doc list", asList(new Document("x", 1), new Document("x", 2)));
    collection.insert(doc);
    DBObject found = collection.findOne();
    assertNotNull(found);
    assertEquals(ObjectId.class, found.get("_id").getClass());
    assertEquals(Boolean.class, found.get("bool").getClass());
    assertEquals(Integer.class, found.get("int").getClass());
    assertEquals(Integer.class, found.get("short").getClass());
    assertEquals(Long.class, found.get("long").getClass());
    assertEquals(String.class, found.get("str").getClass());
    assertEquals(Double.class, found.get("float").getClass());
    assertEquals(Double.class, found.get("double").getClass());
    assertEquals(Date.class, found.get("date").getClass());
    assertEquals(BSONTimestamp.class, found.get("ts").getClass());
    assertEquals(Pattern.class, found.get("pattern").getClass());
    assertEquals(MinKey.class, found.get("minKey").getClass());
    assertEquals(MaxKey.class, found.get("maxKey").getClass());
    assertEquals(Code.class, found.get("js").getClass());
    assertEquals(CodeWScope.class, found.get("jsWithScope").getClass());
    assertNull(found.get("null"));
    assertEquals(UUID.class, found.get("uuid").getClass());
    assertEquals(DBRef.class, found.get("db ref").getClass());
    assertEquals(Binary.class, found.get("binary").getClass());
    assertEquals(byte[].class, found.get("byte array").getClass());
    assertTrue(found.get("int array") instanceof List);
    assertTrue(found.get("list") instanceof List);
    assertTrue(found.get("doc list") instanceof List);
}
Also used : BsonObjectId(org.bson.BsonObjectId) ObjectId(org.bson.types.ObjectId) MaxKey(org.bson.types.MaxKey) BSONTimestamp(org.bson.types.BSONTimestamp) Document(org.bson.Document) Code(org.bson.types.Code) Date(java.util.Date) CodeWScope(org.bson.types.CodeWScope) MinKey(org.bson.types.MinKey) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ArrayList(java.util.ArrayList) Binary(org.bson.types.Binary) Test(org.junit.Test)

Aggregations

ObjectId (org.bson.types.ObjectId)194 Test (org.junit.Test)113 BasicDBObject (com.mongodb.BasicDBObject)46 DBObject (com.mongodb.DBObject)28 Date (java.util.Date)23 Document (org.bson.Document)21 ArrayList (java.util.ArrayList)20 BsonObjectId (org.bson.BsonObjectId)16 StreamRuleMock (org.graylog2.streams.matchers.StreamRuleMock)14 Message (org.graylog2.plugin.Message)13 BasicBSONObject (org.bson.BasicBSONObject)12 List (java.util.List)11 Binary (org.bson.types.Binary)10 UsingDataSet (com.lordofthejars.nosqlunit.annotation.UsingDataSet)9 Map (java.util.Map)8 DBRef (com.mongodb.DBRef)7 Code (org.bson.types.Code)7 Stream (org.graylog2.plugin.streams.Stream)7 ImmutableList (com.google.common.collect.ImmutableList)6 BsonDocument (org.bson.BsonDocument)6