org.bson.BsonType Java Examples
The following examples show how to use
org.bson.BsonType.
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: JavaTimeTest.java From immutables with Apache License 2.0 | 6 votes |
@Test public void instant() throws IOException { Instant now = Instant.now(); long epoch = now.toEpochMilli(); TypeAdapter<Instant> adapter = gson.getAdapter(Instant.class); // read Instant date = adapter.read(Jsons.readerAt(new BsonDateTime(epoch))); check(date).is(now); // write BsonValue bson = writeAndReadBson(now); check(bson.getBsonType()).is(BsonType.DATE_TIME); check(Instant.ofEpochMilli(bson.asDateTime().getValue())).is(now); }
Example #2
Source File: TypedArrayCodec.java From morphia with Apache License 2.0 | 6 votes |
@Override public Object decode(final BsonReader reader, final DecoderContext decoderContext) { reader.readStartArray(); List list = new ArrayList<>(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { list.add(getCodec().decode(reader, decoderContext)); } reader.readEndArray(); Object array = Array.newInstance(type, list.size()); for (int i = 0; i < list.size(); i++) { Array.set(array, i, list.get(i)); } return array; }
Example #3
Source File: ArrayCodec.java From morphia with Apache License 2.0 | 6 votes |
@Override public Object[] decode(final BsonReader reader, final DecoderContext decoderContext) { List<Object> list = new ArrayList<>(); if (reader.getCurrentBsonType() == BsonType.ARRAY) { reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { list.add(readValue(reader, decoderContext)); } reader.readEndArray(); } else { list.add(readValue(reader, decoderContext)); } return list.toArray(); }
Example #4
Source File: EnumCodec.java From core-ng-project with Apache License 2.0 | 6 votes |
public T read(BsonReader reader, String field) { BsonType currentType = reader.getCurrentBsonType(); if (currentType == BsonType.NULL) { reader.readNull(); return null; } else if (currentType == BsonType.STRING) { String enumValue = reader.readString(); T value = decodingMappings.get(enumValue); if (value == null) throw new Error(format("can not decode value to enum, enumClass={}, value={}", enumClass.getCanonicalName(), enumValue)); return value; } else { logger.warn("unexpected field type, field={}, type={}", field, currentType); reader.skipValue(); return null; } }
Example #5
Source File: BsonTypeMap.java From morphia with Apache License 2.0 | 6 votes |
/** * Creates the map */ public BsonTypeMap() { map.put(List.class, BsonType.ARRAY); map.put(Binary.class, BsonType.BINARY); map.put(Boolean.class, BsonType.BOOLEAN); map.put(Date.class, BsonType.DATE_TIME); map.put(BsonDbPointer.class, BsonType.DB_POINTER); map.put(Document.class, BsonType.DOCUMENT); map.put(Double.class, BsonType.DOUBLE); map.put(Integer.class, BsonType.INT32); map.put(Long.class, BsonType.INT64); map.put(Decimal128.class, BsonType.DECIMAL128); map.put(MaxKey.class, BsonType.MAX_KEY); map.put(MinKey.class, BsonType.MIN_KEY); map.put(Code.class, BsonType.JAVASCRIPT); map.put(CodeWithScope.class, BsonType.JAVASCRIPT_WITH_SCOPE); map.put(ObjectId.class, BsonType.OBJECT_ID); map.put(BsonRegularExpression.class, BsonType.REGULAR_EXPRESSION); map.put(String.class, BsonType.STRING); map.put(Symbol.class, BsonType.SYMBOL); map.put(BsonTimestamp.class, BsonType.TIMESTAMP); map.put(BsonUndefined.class, BsonType.UNDEFINED); }
Example #6
Source File: EntityDecoder.java From morphia with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") protected Codec<T> getCodecFromDocument(final BsonReader reader, final boolean useDiscriminator, final String discriminatorKey, final CodecRegistry registry, final DiscriminatorLookup discriminatorLookup, final Codec<T> defaultCodec) { Codec<T> codec = null; if (useDiscriminator) { BsonReaderMark mark = reader.getMark(); try { reader.readStartDocument(); while (codec == null && reader.readBsonType() != BsonType.END_OF_DOCUMENT) { if (discriminatorKey.equals(reader.readName())) { codec = (Codec<T>) registry.get(discriminatorLookup.lookup(reader.readString())); } else { reader.skipValue(); } } } catch (Exception e) { throw new CodecConfigurationException(String.format("Failed to decode '%s'. Decoding errored with: %s", morphiaCodec.getEntityModel().getName(), e.getMessage()), e); } finally { mark.reset(); } } return codec != null ? codec : defaultCodec; }
Example #7
Source File: MorphiaMapPropertyCodecProvider.java From morphia with Apache License 2.0 | 6 votes |
@Override public Map<K, V> decode(final BsonReader reader, final DecoderContext context) { reader.readStartDocument(); Map<K, V> map = getInstance(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { final K key = (K) Conversions.convert(reader.readName(), keyType); if (reader.getCurrentBsonType() == BsonType.NULL) { map.put(key, null); reader.readNull(); } else { map.put(key, codec.decode(reader, context)); } } reader.readEndDocument(); return map; }
Example #8
Source File: CoreStitchAuth.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
/** * Performs a request against Stitch using the provided {@link StitchAuthRequest} object, and * decodes the JSON body of the response into a T value as specified by the provided class type. * The type will be decoded using the codec found for T in the codec registry given. * If the provided type is not supported by the codec registry to be used, the method will throw * a {@link org.bson.codecs.configuration.CodecConfigurationException}. * * @param stitchReq the request to perform. * @param resultClass the class that the JSON response should be decoded as. * @param codecRegistry the codec registry used for de/serialization. * @param <T> the type into which the JSON response will be decoded into. * @return the decoded value. */ public <T> T doAuthenticatedRequest( final StitchAuthRequest stitchReq, final Class<T> resultClass, final CodecRegistry codecRegistry ) { final Response response = doAuthenticatedRequest(stitchReq); try { final String bodyStr = IoUtils.readAllToString(response.getBody()); final JsonReader bsonReader = new JsonReader(bodyStr); // We must check this condition because the decoder will throw trying to decode null if (bsonReader.readBsonType() == BsonType.NULL) { return null; } final CodecRegistry newReg = CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry); return newReg.get(resultClass).decode(bsonReader, DecoderContext.builder().build()); } catch (final Exception e) { throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR); } }
Example #9
Source File: CoreStitchAuth.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
/** * Performs a request against Stitch using the provided {@link StitchAuthRequest} object, * and decodes the response using the provided result decoder. * * @param stitchReq The request to perform. * @return The response to the request, successful or not. */ public <T> T doAuthenticatedRequest(final StitchAuthRequest stitchReq, final Decoder<T> resultDecoder) { final Response response = doAuthenticatedRequest(stitchReq); try { final String bodyStr = IoUtils.readAllToString(response.getBody()); final JsonReader bsonReader = new JsonReader(bodyStr); // We must check this condition because the decoder will throw trying to decode null if (bsonReader.readBsonType() == BsonType.NULL) { return null; } return resultDecoder.decode(bsonReader, DecoderContext.builder().build()); } catch (final Exception e) { throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR); } }
Example #10
Source File: JavaTimeTest.java From immutables with Apache License 2.0 | 6 votes |
@Test public void javaUtilDate() throws IOException { Date now = new Date(); long epoch = now.getTime(); TypeAdapter<Date> adapter = GsonCodecs.typeAdapterFromCodec(new DateCodec()); // read Date date = adapter.read(Jsons.readerAt(new BsonDateTime(epoch))); check(date).is(now); // write BsonValue bson = writeAndReadBson(now); check(bson.getBsonType()).is(BsonType.DATE_TIME); check(new Date(bson.asDateTime().getValue())).is(now); }
Example #11
Source File: BsonParser.java From immutables with Apache License 2.0 | 6 votes |
@Override public NumberType getNumberType() throws IOException { final BsonType type = type(); switch (type) { case DOUBLE: return NumberType.DOUBLE; case INT32: return NumberType.INT; case INT64: return NumberType.LONG; case DECIMAL128: return NumberType.BIG_DECIMAL; default: throw new JsonParseException(this, String.format("Not a numeric type json:%s bson%s", currentToken(), type)); } }
Example #12
Source File: JavaTimeTest.java From immutables with Apache License 2.0 | 6 votes |
@Test public void localDateTime() throws IOException { LocalDateTime now = LocalDateTime.now(); long epoch = now.toInstant(ZoneOffset.UTC).toEpochMilli(); TypeAdapter<LocalDateTime> adapter = gson.getAdapter(LocalDateTime.class); // read LocalDateTime date = adapter.read(Jsons.readerAt(new BsonDateTime(epoch))); LocalDateTime valueRead = Instant.ofEpochMilli(epoch).atOffset(ZoneOffset.UTC).toLocalDateTime(); check(date).is(now); // write BsonValue bson = writeAndReadBson(valueRead); check(bson.getBsonType()).is(BsonType.DATE_TIME); check(Instant.ofEpochMilli(bson.asDateTime().getValue()).atOffset(ZoneOffset.UTC).toLocalDateTime()).is(valueRead); }
Example #13
Source File: JavaTimeTest.java From immutables with Apache License 2.0 | 6 votes |
@Test public void localDate() throws IOException { long epoch = System.currentTimeMillis(); LocalDate now = Instant.ofEpochMilli(epoch).atOffset(ZoneOffset.UTC).toLocalDate(); TypeAdapter<LocalDate> adapter = gson.getAdapter(LocalDate.class); // read LocalDate date = adapter.read(Jsons.readerAt(new BsonDateTime(epoch))); check(date).is(now); // write BsonValue bson = writeAndReadBson(now); check(bson.getBsonType()).is(BsonType.DATE_TIME); check(Instant.ofEpochMilli(bson.asDateTime().getValue()).atOffset(ZoneOffset.UTC).toLocalDate()).is(now); }
Example #14
Source File: BsonDecimal128Test.java From immutables with Apache License 2.0 | 6 votes |
@Test public void write() throws Exception { JsonObject obj = new JsonObject(); BigInteger bigInteger = new BigInteger(Long.toString(Long.MAX_VALUE)).multiply(new BigInteger("128")); obj.addProperty("bigInteger", bigInteger); BigDecimal bigDecimal = new BigDecimal(Long.MAX_VALUE).multiply(new BigDecimal(1024)); obj.addProperty("bigDecimal", bigDecimal); BsonDocument doc = Jsons.toBson(obj); check(doc.get("bigInteger").getBsonType()).is(BsonType.DECIMAL128); check(doc.get("bigInteger").asDecimal128().decimal128Value().bigDecimalValue().toBigInteger()).is(bigInteger); check(doc.get("bigDecimal").getBsonType()).is(BsonType.DECIMAL128); check(doc.get("bigDecimal").asDecimal128().decimal128Value().bigDecimalValue()).is(bigDecimal); }
Example #15
Source File: BsonNumbersTest.java From immutables with Apache License 2.0 | 6 votes |
@Test public void bigNumbers() throws Exception { JsonObject obj = new JsonObject(); BigInteger bigInteger = new BigInteger(Long.toString(Long.MAX_VALUE)).multiply(new BigInteger("128")); obj.addProperty("bigInteger", bigInteger); BigDecimal bigDecimal = new BigDecimal(Long.MAX_VALUE).multiply(new BigDecimal(1024)); obj.addProperty("bigDecimal", bigDecimal); BsonDocument bson = Jsons.toBson(obj); check(bson.get("bigInteger").getBsonType()).is(BsonType.DECIMAL128); check(bson.get("bigInteger").asDecimal128().decimal128Value().bigDecimalValue().toBigInteger()).is(bigInteger); check(bson.get("bigDecimal").getBsonType()).is(BsonType.DECIMAL128); check(bson.get("bigDecimal").asDecimal128().decimal128Value().bigDecimalValue()).is(bigDecimal); check(Jsons.toGson(bson)).is(obj); }
Example #16
Source File: AbstractJsonCodec.java From vertx-mongo-client with Apache License 2.0 | 6 votes |
protected BsonType getBsonType(Object value) { if (value == null) { return BsonType.NULL; } else if (value instanceof Boolean) { return BsonType.BOOLEAN; } else if (value instanceof Double) { return BsonType.DOUBLE; } else if (value instanceof Integer) { return BsonType.INT32; } else if (value instanceof Long) { return BsonType.INT64; } else if (value instanceof String) { return BsonType.STRING; } else if (isObjectIdInstance(value)) { return BsonType.OBJECT_ID; } else if (isObjectInstance(value)) { return BsonType.DOCUMENT; } else if (isArrayInstance(value)) { return BsonType.ARRAY; } else { return null; } }
Example #17
Source File: BsonParser.java From immutables with Apache License 2.0 | 6 votes |
@Override public NumberType getNumberType() throws IOException { final BsonType type = type(); switch (type) { case DOUBLE: return NumberType.DOUBLE; case INT32: return NumberType.INT; case INT64: return NumberType.LONG; case DECIMAL128: return NumberType.BIG_DECIMAL; default: throw new IllegalStateException(String.format("Not a number type %s", type)); } }
Example #18
Source File: BsonParser.java From immutables with Apache License 2.0 | 6 votes |
@Override public BigDecimal getDecimalValue() throws IOException { final BsonType type = type(); switch (type) { case DOUBLE: return BigDecimal.valueOf(getNumberValue().doubleValue()); case INT32: return new BigDecimal(getNumberValue().intValue()); case INT64: return BigDecimal.valueOf(getNumberValue().longValue()); case DECIMAL128: case STRING: return (BigDecimal) getNumberValue(); default: throw new IllegalStateException(String.format("Can't convert %s to %s", type, BigDecimal.class.getName())); } }
Example #19
Source File: BsonParser.java From immutables with Apache License 2.0 | 6 votes |
@Override public Number getNumberValue() throws IOException { final BsonType type = type(); switch (type) { case DOUBLE: return reader.readDouble(); case INT32: return reader.readInt32(); case INT64: return reader.readInt64(); case DECIMAL128: return reader.readDecimal128().bigDecimalValue(); case STRING: return new BigDecimal(reader.readString()); default: throw new IllegalStateException(String.format("Can't convert %s to %s", type, Number.class.getName())); } }
Example #20
Source File: BsonReader.java From immutables with Apache License 2.0 | 6 votes |
/** * Gson library reads numbers lazily when using generic * {@link com.google.gson.internal.bind.TypeAdapters#JSON_ELEMENT} type adapter. * Number is read as string and then wrapped inside {@link LazilyParsedNumber}. This inefficiency * should only occur if reading numbers with generic JSON element API * and not using generated type adapters. * @see LazilyParsedNumber * @see com.google.gson.internal.bind.TypeAdapters#JSON_ELEMENT */ private String scalarToString() { final BsonType type = delegate.getCurrentBsonType(); switch (type) { case STRING: return delegate.readString(); case SYMBOL: return delegate.readSymbol(); case INT32: return Integer.toString(delegate.readInt32()); case INT64: return Long.toString(delegate.readInt64()); case DOUBLE: return Double.toString(delegate.readDouble()); case DECIMAL128: return delegate.readDecimal128().toString(); case REGULAR_EXPRESSION: return delegate.readRegularExpression().getPattern(); case OBJECT_ID: return delegate.readObjectId().toHexString(); default: throw new IllegalStateException("Unknown scalar type to be converted to string: " + type); } }
Example #21
Source File: BsonReader.java From immutables with Apache License 2.0 | 6 votes |
@Override public int nextInt() throws IOException { final BsonType type = delegate.getCurrentBsonType(); switch (type) { case INT32: return delegate.readInt32(); case INT64: return (int) delegate.readInt64(); case DOUBLE: return (int) delegate.readDouble(); case DECIMAL128: return delegate.readDecimal128().bigDecimalValue().intValueExact(); case DATE_TIME: return (int) delegate.readDateTime(); case TIMESTAMP: return (int) delegate.readTimestamp().getValue(); default: throw new IllegalStateException(String.format("Expected numeric bson type (int) but got %s (as json:%s)", type, toGsonToken(type))); } }
Example #22
Source File: BsonReader.java From immutables with Apache License 2.0 | 6 votes |
@Override public double nextDouble() throws IOException { final BsonType type = delegate.getCurrentBsonType(); switch (type) { case DOUBLE: return delegate.readDouble(); case INT32: return delegate.readInt32(); case INT64: return delegate.readInt64(); case DECIMAL128: return delegate.readDecimal128().bigDecimalValue().doubleValue(); case DATE_TIME: return delegate.readDateTime(); case TIMESTAMP: return delegate.readTimestamp().getValue(); default: throw new IllegalStateException(String.format("Expected numeric bson type (double) but got %s (as json:%s)", type, toGsonToken(type))); } }
Example #23
Source File: BsonReader.java From immutables with Apache License 2.0 | 6 votes |
@Override public long nextLong() throws IOException { BsonType type = delegate.getCurrentBsonType(); switch (type) { case INT64: return delegate.readInt64(); case INT32: return delegate.readInt32(); case DOUBLE: return (long) delegate.readDouble(); case DECIMAL128: return delegate.readDecimal128().bigDecimalValue().longValueExact(); case DATE_TIME: return delegate.readDateTime(); case TIMESTAMP: return delegate.readTimestamp().getValue(); default: throw new IllegalStateException(String.format("Expected numeric bson type (long) but got %s (as json:%s)", type, toGsonToken(type))); } }
Example #24
Source File: MorphiaCollectionCodec.java From morphia with Apache License 2.0 | 5 votes |
@Override public Collection<T> decode(final BsonReader reader, final DecoderContext decoderContext) { if (reader.getCurrentBsonType().equals(BsonType.ARRAY)) { return super.decode(reader, decoderContext); } final Collection<T> collection = getInstance(); T value = getCodec().decode(reader, decoderContext); collection.add(value); return collection; }
Example #25
Source File: OptionalProvider.java From immutables with Apache License 2.0 | 5 votes |
@Override public final O decode(BsonReader reader, DecoderContext decoderContext) { if (reader.getCurrentBsonType() == BsonType.NULL) { reader.readNull(); return empty(); } return nullable(delegate.decode(reader, decoderContext)); }
Example #26
Source File: BsonParser.java From immutables with Apache License 2.0 | 5 votes |
private JsonToken toJsonToken(BsonType type) { switch (type) { case END_OF_DOCUMENT: reader.readEndDocument(); return JsonToken.END_OBJECT; case DOCUMENT: reader.readStartDocument(); return JsonToken.START_OBJECT; case ARRAY: reader.readStartArray(); return JsonToken.START_ARRAY; case OBJECT_ID: return JsonToken.VALUE_EMBEDDED_OBJECT; case BOOLEAN: final boolean value = reader.readBoolean(); return value ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE; case DATE_TIME: return JsonToken.VALUE_EMBEDDED_OBJECT; case NULL: reader.readNull(); return JsonToken.VALUE_NULL; case REGULAR_EXPRESSION: return JsonToken.VALUE_EMBEDDED_OBJECT; case SYMBOL: case STRING: return JsonToken.VALUE_STRING; case INT32: case INT64: return JsonToken.VALUE_NUMBER_INT; case DECIMAL128: return JsonToken.VALUE_NUMBER_FLOAT; case DOUBLE: return JsonToken.VALUE_NUMBER_FLOAT; case BINARY: return JsonToken.VALUE_EMBEDDED_OBJECT; default: throw new IllegalStateException(String.format("Unknown type %s", type)); } }
Example #27
Source File: ArrayCodec.java From morphia with Apache License 2.0 | 5 votes |
private Object readValue(final BsonReader reader, final DecoderContext decoderContext) { BsonType bsonType = reader.getCurrentBsonType(); if (bsonType == BsonType.NULL) { reader.readNull(); return null; } else if (bsonType == BsonType.BINARY && BsonBinarySubType.isUuid(reader.peekBinarySubType()) && reader.peekBinarySize() == 16) { return mapper.getCodecRegistry().get(UUID.class).decode(reader, decoderContext); } return mapper.getCodecRegistry().get(type.getComponentType()).decode(reader, decoderContext); }
Example #28
Source File: CollectionCodec.java From morphia with Apache License 2.0 | 5 votes |
@Override public Collection<T> decode(final BsonReader reader, final DecoderContext context) { Collection<T> collection = getInstance(); reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { if (reader.getCurrentBsonType() == BsonType.NULL) { collection.add(null); reader.readNull(); } else { collection.add(codec.decode(reader, context)); } } reader.readEndArray(); return collection; }
Example #29
Source File: ObjectCodec.java From morphia with Apache License 2.0 | 5 votes |
@Override public Object decode(final BsonReader reader, final DecoderContext decoderContext) { BsonType bsonType = reader.getCurrentBsonType(); Class<?> clazz; if (bsonType == BsonType.DOCUMENT) { clazz = Document.class; String discriminatorField = mapper.getOptions().getDiscriminatorKey(); BsonReaderMark mark = reader.getMark(); reader.readStartDocument(); while (clazz.equals(Document.class) && reader.readBsonType() != BsonType.END_OF_DOCUMENT) { if (reader.readName().equals(discriminatorField)) { try { clazz = mapper.getClass(reader.readString()); } catch (CodecConfigurationException e) { throw new MappingException(e.getMessage(), e); } } else { reader.skipValue(); } } mark.reset(); } else { clazz = bsonTypeClassMap.get(bsonType); } return mapper.getCodecRegistry() .get(clazz) .decode(reader, decoderContext); }
Example #30
Source File: DocumentReader.java From morphia with Apache License 2.0 | 5 votes |
BsonType getBsonType(final Object o) { BsonType bsonType = TYPE_MAP.get(o.getClass()); if (bsonType == null) { if (o instanceof List) { bsonType = BsonType.ARRAY; } else { throw new IllegalStateException(Sofia.unknownBsonType(o.getClass())); } } return bsonType; }