Search in sources :

Example 6 with MinKey

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

the class DocumentCodecTest method testPrimitiveBSONTypeCodecs.

@Test
public void testPrimitiveBSONTypeCodecs() throws IOException {
    DocumentCodec documentCodec = new DocumentCodec();
    Document doc = new Document();
    doc.put("oid", new ObjectId());
    doc.put("integer", 1);
    doc.put("long", 2L);
    doc.put("string", "hello");
    doc.put("double", 3.2);
    doc.put("decimal", Decimal128.parse("0.100"));
    doc.put("binary", new Binary(BsonBinarySubType.USER_DEFINED, new byte[] { 0, 1, 2, 3 }));
    doc.put("date", new Date(1000));
    doc.put("boolean", true);
    doc.put("code", new Code("var i = 0"));
    doc.put("minkey", new MinKey());
    doc.put("maxkey", new MaxKey());
    // doc.put("pattern", Pattern.compile("^hello"));  // TODO: Pattern doesn't override equals method!
    doc.put("null", null);
    documentCodec.encode(writer, doc, EncoderContext.builder().build());
    BsonInput bsonInput = createInputBuffer();
    Document decodedDocument = documentCodec.decode(new BsonBinaryReader(bsonInput), DecoderContext.builder().build());
    assertEquals(doc, decodedDocument);
}
Also used : MinKey(org.bson.types.MinKey) BsonObjectId(org.bson.BsonObjectId) ObjectId(org.bson.types.ObjectId) BsonInput(org.bson.io.BsonInput) ByteBufferBsonInput(org.bson.io.ByteBufferBsonInput) MaxKey(org.bson.types.MaxKey) BsonBinaryReader(org.bson.BsonBinaryReader) Binary(org.bson.types.Binary) Document(org.bson.Document) Code(org.bson.types.Code) Date(java.util.Date) Test(org.junit.Test)

Example 7 with MinKey

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

the class JsonReader method readBsonType.

// CHECKSTYLE:OFF
@Override
public BsonType readBsonType() {
    if (isClosed()) {
        throw new IllegalStateException("This instance has been closed");
    }
    if (getState() == State.INITIAL || getState() == State.DONE || getState() == State.SCOPE_DOCUMENT) {
        // in JSON the top level value can be of any type so fall through
        setState(State.TYPE);
    }
    if (getState() != State.TYPE) {
        throwInvalidState("readBSONType", State.TYPE);
    }
    if (getContext().getContextType() == BsonContextType.DOCUMENT) {
        JsonToken nameToken = popToken();
        switch(nameToken.getType()) {
            case STRING:
            case UNQUOTED_STRING:
                setCurrentName(nameToken.getValue(String.class));
                break;
            case END_OBJECT:
                setState(State.END_OF_DOCUMENT);
                return BsonType.END_OF_DOCUMENT;
            default:
                throw new JsonParseException("JSON reader was expecting a name but found '%s'.", nameToken.getValue());
        }
        JsonToken colonToken = popToken();
        if (colonToken.getType() != JsonTokenType.COLON) {
            throw new JsonParseException("JSON reader was expecting ':' but found '%s'.", colonToken.getValue());
        }
    }
    JsonToken token = popToken();
    if (getContext().getContextType() == BsonContextType.ARRAY && token.getType() == JsonTokenType.END_ARRAY) {
        setState(State.END_OF_ARRAY);
        return BsonType.END_OF_DOCUMENT;
    }
    boolean noValueFound = false;
    switch(token.getType()) {
        case BEGIN_ARRAY:
            setCurrentBsonType(BsonType.ARRAY);
            break;
        case BEGIN_OBJECT:
            visitExtendedJSON();
            break;
        case DOUBLE:
            setCurrentBsonType(BsonType.DOUBLE);
            currentValue = token.getValue();
            break;
        case END_OF_FILE:
            setCurrentBsonType(BsonType.END_OF_DOCUMENT);
            break;
        case INT32:
            setCurrentBsonType(BsonType.INT32);
            currentValue = token.getValue();
            break;
        case INT64:
            setCurrentBsonType(BsonType.INT64);
            currentValue = token.getValue();
            break;
        case REGULAR_EXPRESSION:
            setCurrentBsonType(BsonType.REGULAR_EXPRESSION);
            currentValue = token.getValue();
            break;
        case STRING:
            setCurrentBsonType(BsonType.STRING);
            currentValue = token.getValue();
            break;
        case UNQUOTED_STRING:
            String value = token.getValue(String.class);
            if ("false".equals(value) || "true".equals(value)) {
                setCurrentBsonType(BsonType.BOOLEAN);
                currentValue = Boolean.parseBoolean(value);
            } else if ("Infinity".equals(value)) {
                setCurrentBsonType(BsonType.DOUBLE);
                currentValue = Double.POSITIVE_INFINITY;
            } else if ("NaN".equals(value)) {
                setCurrentBsonType(BsonType.DOUBLE);
                currentValue = Double.NaN;
            } else if ("null".equals(value)) {
                setCurrentBsonType(BsonType.NULL);
            } else if ("undefined".equals(value)) {
                setCurrentBsonType(BsonType.UNDEFINED);
            } else if ("MinKey".equals(value)) {
                visitEmptyConstructor();
                setCurrentBsonType(BsonType.MIN_KEY);
                currentValue = new MinKey();
            } else if ("MaxKey".equals(value)) {
                visitEmptyConstructor();
                setCurrentBsonType(BsonType.MAX_KEY);
                currentValue = new MaxKey();
            } else if ("BinData".equals(value)) {
                setCurrentBsonType(BsonType.BINARY);
                currentValue = visitBinDataConstructor();
            } else if ("Date".equals(value)) {
                currentValue = visitDateTimeConstructorWithOutNew();
                setCurrentBsonType(BsonType.STRING);
            } else if ("HexData".equals(value)) {
                setCurrentBsonType(BsonType.BINARY);
                currentValue = visitHexDataConstructor();
            } else if ("ISODate".equals(value)) {
                setCurrentBsonType(BsonType.DATE_TIME);
                currentValue = visitISODateTimeConstructor();
            } else if ("NumberInt".equals(value)) {
                setCurrentBsonType(BsonType.INT32);
                currentValue = visitNumberIntConstructor();
            } else if ("NumberLong".equals(value)) {
                setCurrentBsonType(BsonType.INT64);
                currentValue = visitNumberLongConstructor();
            } else if ("NumberDecimal".equals(value)) {
                setCurrentBsonType(BsonType.DECIMAL128);
                currentValue = visitNumberDecimalConstructor();
            } else if ("ObjectId".equals(value)) {
                setCurrentBsonType(BsonType.OBJECT_ID);
                currentValue = visitObjectIdConstructor();
            } else if ("Timestamp".equals(value)) {
                setCurrentBsonType(BsonType.TIMESTAMP);
                currentValue = visitTimestampConstructor();
            } else if ("RegExp".equals(value)) {
                setCurrentBsonType(BsonType.REGULAR_EXPRESSION);
                currentValue = visitRegularExpressionConstructor();
            } else if ("DBPointer".equals(value)) {
                setCurrentBsonType(BsonType.DB_POINTER);
                currentValue = visitDBPointerConstructor();
            } else if ("UUID".equals(value)) {
                setCurrentBsonType(BsonType.BINARY);
                currentValue = visitUUIDConstructor();
            } else if ("new".equals(value)) {
                visitNew();
            } else {
                noValueFound = true;
            }
            break;
        default:
            noValueFound = true;
            break;
    }
    if (noValueFound) {
        throw new JsonParseException("JSON reader was expecting a value but found '%s'.", token.getValue());
    }
    if (getContext().getContextType() == BsonContextType.ARRAY || getContext().getContextType() == BsonContextType.DOCUMENT) {
        JsonToken commaToken = popToken();
        if (commaToken.getType() != JsonTokenType.COMMA) {
            pushToken(commaToken);
        }
    }
    switch(getContext().getContextType()) {
        case DOCUMENT:
        case SCOPE_DOCUMENT:
        default:
            setState(State.NAME);
            break;
        case ARRAY:
        case JAVASCRIPT_WITH_SCOPE:
        case TOP_LEVEL:
            setState(State.VALUE);
            break;
    }
    return getCurrentBsonType();
}
Also used : MinKey(org.bson.types.MinKey) MaxKey(org.bson.types.MaxKey)

Example 8 with MinKey

use of org.bson.types.MinKey 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) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) List(java.util.List) Binary(org.bson.types.Binary) Test(org.junit.Test)

Example 9 with MinKey

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

the class JSONCallback method objectDone.

@Override
public Object objectDone() {
    String name = curName();
    Object o = super.objectDone();
    if (_lastArray) {
        return o;
    }
    BSONObject b = (BSONObject) o;
    // override the object if it's a special type
    if (b.containsField("$oid")) {
        o = new ObjectId((String) b.get("$oid"));
    } else if (b.containsField("$date")) {
        if (b.get("$date") instanceof Number) {
            o = new Date(((Number) b.get("$date")).longValue());
        } else {
            SimpleDateFormat format = new SimpleDateFormat(_msDateFormat);
            format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
            o = format.parse(b.get("$date").toString(), new ParsePosition(0));
            if (o == null) {
                // try older format with no ms
                format = new SimpleDateFormat(_secDateFormat);
                format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
                o = format.parse(b.get("$date").toString(), new ParsePosition(0));
            }
        }
    } else if (b.containsField("$regex")) {
        o = Pattern.compile((String) b.get("$regex"), BSON.regexFlags((String) b.get("$options")));
    } else if (b.containsField("$ts")) {
        //Legacy timestamp format
        Integer ts = ((Number) b.get("$ts")).intValue();
        Integer inc = ((Number) b.get("$inc")).intValue();
        o = new BSONTimestamp(ts, inc);
    } else if (b.containsField("$timestamp")) {
        BSONObject tsObject = (BSONObject) b.get("$timestamp");
        Integer ts = ((Number) tsObject.get("t")).intValue();
        Integer inc = ((Number) tsObject.get("i")).intValue();
        o = new BSONTimestamp(ts, inc);
    } else if (b.containsField("$code")) {
        if (b.containsField("$scope")) {
            o = new CodeWScope((String) b.get("$code"), (DBObject) b.get("$scope"));
        } else {
            o = new Code((String) b.get("$code"));
        }
    } else if (b.containsField("$ref")) {
        o = new DBRef((String) b.get("$ref"), b.get("$id"));
    } else if (b.containsField("$minKey")) {
        o = new MinKey();
    } else if (b.containsField("$maxKey")) {
        o = new MaxKey();
    } else if (b.containsField("$uuid")) {
        o = UUID.fromString((String) b.get("$uuid"));
    } else if (b.containsField("$binary")) {
        int type = (b.get("$type") instanceof String) ? Integer.valueOf((String) b.get("$type"), 16) : (Integer) b.get("$type");
        byte[] bytes = DatatypeConverter.parseBase64Binary((String) b.get("$binary"));
        o = new Binary((byte) type, bytes);
    } else if (b.containsField("$undefined") && b.get("$undefined").equals(true)) {
        o = new BsonUndefined();
    } else if (b.containsField("$numberLong")) {
        o = Long.valueOf((String) b.get("$numberLong"));
    } else if (b.containsField("$numberDecimal")) {
        o = Decimal128.parse((String) b.get("$numberDecimal"));
    }
    if (!isStackEmpty()) {
        _put(name, o);
    } else {
        o = !BSON.hasDecodeHooks() ? o : BSON.applyDecodingHooks(o);
        setRoot(o);
    }
    return o;
}
Also used : ObjectId(org.bson.types.ObjectId) BSONObject(org.bson.BSONObject) GregorianCalendar(java.util.GregorianCalendar) DBRef(com.mongodb.DBRef) MaxKey(org.bson.types.MaxKey) BSONTimestamp(org.bson.types.BSONTimestamp) Code(org.bson.types.Code) Date(java.util.Date) CodeWScope(org.bson.types.CodeWScope) MinKey(org.bson.types.MinKey) SimpleTimeZone(java.util.SimpleTimeZone) BasicDBObject(com.mongodb.BasicDBObject) BSONObject(org.bson.BSONObject) DBObject(com.mongodb.DBObject) Binary(org.bson.types.Binary) SimpleDateFormat(java.text.SimpleDateFormat) BsonUndefined(org.bson.BsonUndefined) ParsePosition(java.text.ParsePosition)

Example 10 with MinKey

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

the class LazyBSONObject method readValue.

Object readValue(final BsonBinaryReader reader) {
    switch(reader.getCurrentBsonType()) {
        case DOCUMENT:
            return readDocument(reader);
        case ARRAY:
            return readArray(reader);
        case DOUBLE:
            return reader.readDouble();
        case STRING:
            return reader.readString();
        case BINARY:
            byte binarySubType = reader.peekBinarySubType();
            if (BsonBinarySubType.isUuid(binarySubType) && reader.peekBinarySize() == 16) {
                return new UuidCodec().decode(reader, DecoderContext.builder().build());
            }
            BsonBinary binary = reader.readBinaryData();
            if (binarySubType == BINARY.getValue() || binarySubType == OLD_BINARY.getValue()) {
                return binary.getData();
            } else {
                return new Binary(binary.getType(), binary.getData());
            }
        case NULL:
            reader.readNull();
            return null;
        case UNDEFINED:
            reader.readUndefined();
            return null;
        case OBJECT_ID:
            return reader.readObjectId();
        case BOOLEAN:
            return reader.readBoolean();
        case DATE_TIME:
            return new Date(reader.readDateTime());
        case REGULAR_EXPRESSION:
            BsonRegularExpression regularExpression = reader.readRegularExpression();
            return Pattern.compile(regularExpression.getPattern(), BSON.regexFlags(regularExpression.getOptions()));
        case DB_POINTER:
            BsonDbPointer dbPointer = reader.readDBPointer();
            return callback.createDBRef(dbPointer.getNamespace(), dbPointer.getId());
        case JAVASCRIPT:
            return new Code(reader.readJavaScript());
        case SYMBOL:
            return new Symbol(reader.readSymbol());
        case JAVASCRIPT_WITH_SCOPE:
            return new CodeWScope(reader.readJavaScriptWithScope(), (BSONObject) readJavaScriptWithScopeDocument(reader));
        case INT32:
            return reader.readInt32();
        case TIMESTAMP:
            BsonTimestamp timestamp = reader.readTimestamp();
            return new BSONTimestamp(timestamp.getTime(), timestamp.getInc());
        case INT64:
            return reader.readInt64();
        case DECIMAL128:
            return reader.readDecimal128();
        case MIN_KEY:
            reader.readMinKey();
            return new MinKey();
        case MAX_KEY:
            reader.readMaxKey();
            return new MaxKey();
        default:
            throw new IllegalArgumentException("unhandled BSON type: " + reader.getCurrentBsonType());
    }
}
Also used : UuidCodec(org.bson.codecs.UuidCodec) Symbol(org.bson.types.Symbol) MaxKey(org.bson.types.MaxKey) BSONTimestamp(org.bson.types.BSONTimestamp) Code(org.bson.types.Code) Date(java.util.Date) CodeWScope(org.bson.types.CodeWScope) MinKey(org.bson.types.MinKey) Binary(org.bson.types.Binary)

Aggregations

MinKey (org.bson.types.MinKey)15 MaxKey (org.bson.types.MaxKey)14 Binary (org.bson.types.Binary)8 Date (java.util.Date)7 Document (org.bson.Document)7 Code (org.bson.types.Code)7 ObjectId (org.bson.types.ObjectId)7 Test (org.junit.Test)7 ArrayList (java.util.ArrayList)5 BSONTimestamp (org.bson.types.BSONTimestamp)5 CodeWScope (org.bson.types.CodeWScope)5 DBRef (com.mongodb.DBRef)4 List (java.util.List)4 Map (java.util.Map)3 BasicDBObject (com.mongodb.BasicDBObject)2 DBObject (com.mongodb.DBObject)2 ServerAddress (com.mongodb.ServerAddress)2 MongoDatabase (com.mongodb.client.MongoDatabase)2 SimpleDateFormat (java.text.SimpleDateFormat)2 Arrays.asList (java.util.Arrays.asList)2