Java Code Examples for org.bson.codecs.configuration.CodecRegistries#fromRegistries()

The following examples show how to use org.bson.codecs.configuration.CodecRegistries#fromRegistries() . 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: PersistenceManager.java    From clouditor with Apache License 2.0 6 votes vote down vote up
private PersistenceManager() {
  var factory = new BsonFactory();

  var module = new SimpleModule();
  // the default Jackson Java 8 time (de)serializer are not compatible with MongoDB
  module.addSerializer(Instant.class, new BsonInstantSerializer());
  module.addDeserializer(Instant.class, new BsonInstantDeserializer());

  var mapper = new ObjectMapper(factory);
  ObjectMapperResolver.configureObjectMapper(mapper);

  mapper.registerModule(module);

  this.codecRegistry =
      CodecRegistries.fromRegistries(
          MongoClient.getDefaultCodecRegistry(), fromProviders(new JacksonCodecProvider(mapper)));
}
 
Example 2
Source File: CoreStitchAuth.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
Source File: ElasticBulkService.java    From mongolastic with MIT License 6 votes vote down vote up
/**
 * Customizations for the document.toJson output.
 * <p>
 * http://mongodb.github.io/mongo-java-driver/3.0/bson/codecs/
 *
 * @return the toJson encoder.
 */
private Encoder<Document> getEncoder() {
    ArrayList<Codec<?>> codecs = new ArrayList<>();

    if (config.getElastic().getDateFormat() != null) {
        // Replace default DateCodec class to use the custom date formatter.
        codecs.add(new CustomDateCodec(config.getElastic().getDateFormat()));
    }

    if (config.getElastic().getLongToString()) {
        // Replace default LongCodec class
        codecs.add(new CustomLongCodec());
    }

    if (codecs.size() > 0) {
        BsonTypeClassMap bsonTypeClassMap = new BsonTypeClassMap();

        CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
                CodecRegistries.fromCodecs(codecs),
                MongoClient.getDefaultCodecRegistry());

        return new DocumentCodec(codecRegistry, bsonTypeClassMap);
    } else {
        return new DocumentCodec();
    }
}
 
Example 4
Source File: CoreRemoteMongoCollectionUnitTests.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithCodecRegistry() {
  final CoreRemoteMongoCollection<Document> coll1 = getCollection();
  final CodecRegistry myReg = CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY);
  final CoreRemoteMongoCollection<Document> coll2 = coll1.withCodecRegistry(myReg);
  assertEquals(myReg, coll2.getCodecRegistry());
  assertNotEquals(myReg, coll1.getCodecRegistry());
}
 
Example 5
Source File: StitchClientConfiguration.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Merges the provided codec registry with the default codec registry.
 *
 * @param codecRegistry the codec registry to merge with the default registry.
 * @return the builder.
 */
public Builder withCodecRegistry(final CodecRegistry codecRegistry) {
  // We can't detect if their codecRegistry has any duplicate providers. There's also a chance
  // that putting ours first may prevent decoding of some of their classes if for example they
  // have their own way of decoding an Integer.
  this.codecRegistry =
      CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);
  return this;
}
 
Example 6
Source File: StitchObjectMapper.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the given codec registry to be used alongside the default codec registry.
 *
 * @param codecRegistry the codec registry to merge in.
 * @return an {@link StitchObjectMapper} with the merged codec registries.
 */
public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) {
  // We can't detect if their codecRegistry has any duplicate providers. There's also a chance
  // that putting ours first may prevent decoding of some of their classes if for example they
  // have their own way of decoding an Integer.
  final CodecRegistry newReg =
      CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);
  return new StitchObjectMapper(this, newReg);
}
 
Example 7
Source File: MongoStorageAdapter.java    From Prism with MIT License 5 votes vote down vote up
/**
 * Establish connections to the database
 *
 * @return Whether we could connect properly
 */
@Override
public boolean connect() throws Exception {
    ServerAddress address = new ServerAddress(Prism.getInstance().getConfig().getStorageCategory().getAddress(), ServerAddress.defaultPort());

    MongoCredential credential = MongoCredential.createCredential(
            Prism.getInstance().getConfig().getStorageCategory().getUsername(),
            databaseName,
            Prism.getInstance().getConfig().getStorageCategory().getPassword().toCharArray()
    );

    CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
            MongoClient.getDefaultCodecRegistry(),
            CodecRegistries.fromCodecs(new PrimitiveArrayCodec())
    );

    mongoClient = new MongoClient(address, credential, MongoClientOptions.builder().codecRegistry(codecRegistry).build());

    // @todo support auth: boolean auth = db.authenticate(myUserName, myPassword);

    // Connect to the database
    database = mongoClient.getDatabase(databaseName);

    // Create indexes
    try {
        getCollection(collectionEventRecordsName).createIndex(
                new Document("Location.X", 1).append("Location.Z", 1).append("Location.Y", 1).append("Created", -1));
        getCollection(collectionEventRecordsName).createIndex(new Document("Created", -1).append("EventName", 1));

        // TTL
        IndexOptions options = new IndexOptions().expireAfter(0L, TimeUnit.SECONDS);
        getCollection(collectionEventRecordsName).createIndex(new Document("Expires", 1), options);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 8
Source File: BsonCodecRepoTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Test
public void basic() {
  LocalCodec codecAndStrategy = new LocalCodec();

  CodecRegistry registry = CodecRegistries.fromRegistries(codecAndStrategy,
          MongoClient.getDefaultCodecRegistry());


  RepositorySetup.FieldNamingStrategy strategy = new RepositorySetup.FieldNamingStrategy() {
    @Override
    public String translateName(Member member) {
      return "date".equals(member.getName()) ? "dateChanged" : member.getName();
    }
  };

  RepositorySetup setup = RepositorySetup.builder()
          .executor(MoreExecutors.newDirectExecutorService())
          .database(context.database())
          .codecRegistry(registry, strategy)
          .build();

  SomebodyRepository repository = new SomebodyRepository(setup);

  ImmutableSomebody somebody = ImmutableSomebody.builder().id(new ObjectId()).date(new Date()).prop1("prop1").build();
  repository.insert(somebody)
          .getUnchecked();

  check(repository.findById(somebody.id()).fetchAll().getUnchecked()).hasAll(somebody);
  check(repository.find(repository.criteria().prop1(somebody.prop1())).fetchAll().getUnchecked()).hasAll(somebody);
  check(repository.find(repository.criteria().prop1("unknown")).fetchAll().getUnchecked()).isEmpty();
  check(repository.find(repository.criteria().date(somebody.date())).fetchAll().getUnchecked()).hasAll(somebody);
  check(repository.find(repository.criteria().date(new Date(somebody.date().getTime() + 1)))
          .fetchAll().getUnchecked()).isEmpty();
}
 
Example 9
Source File: BsonModule.java    From immutables with Apache License 2.0 5 votes vote down vote up
private static CodecRegistry defaultRegistry() {
  CodecRegistry standard = CodecRegistries.fromProviders(
          new BsonValueCodecProvider(),
          new Jsr310CodecProvider());

  // avoid codecs for String / Long / Boolean etc. They're already handled by jackson
  // choose the ones which need to be serialized in non-JSON format (BSON)
  CodecRegistry others = CodecRegistries.fromCodecs(new ObjectIdCodec(),
          new DateCodec(), new UuidCodec(), new Decimal128Codec(),
          new PatternCodec(),
          new BigDecimalCodec(), new ByteArrayCodec());

  return CodecRegistries.fromRegistries(standard, others);
}
 
Example 10
Source File: CoreStitchAuthUnitTests.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void testDoAuthenticatedRequestWithCustomCodecRegistry() {
  final StitchRequestClient requestClient = getMockedRequestClient();
  final StitchAuthRoutes routes = new StitchAppRoutes("my_app-12345").getAuthRoutes();
  final StitchAuth auth =
      new StitchAuth(
          requestClient,
          routes,
          new MemoryStorage());
  final CodecRegistry registry = CodecRegistries.fromRegistries(
      BsonUtils.DEFAULT_CODEC_REGISTRY,
      CodecRegistries.fromCodecs(new CustomType.Codec()));
  auth.loginWithCredentialInternal(new AnonymousCredential());

  final StitchAuthDocRequest.Builder reqBuilder = new StitchAuthDocRequest.Builder();
  reqBuilder.withPath("giveMeData");
  reqBuilder.withDocument(new Document());
  reqBuilder.withMethod(Method.POST);

  final String rawInt = "{\"$numberInt\": \"42\"}";
  // Check that primitive return types can be decoded.
  doReturn(new Response(rawInt)).when(requestClient).doRequest(any(StitchRequest.class));
  assertEquals(42, (int) auth.doAuthenticatedRequest(
      reqBuilder.build(),
      Integer.class,
      registry));
  doReturn(new Response(rawInt)).when(requestClient).doRequest(any(StitchRequest.class));
  assertEquals(42, (int) auth.doAuthenticatedRequest(
      reqBuilder.build(),
      new IntegerCodec()));

  final ObjectId expectedObjectId = new ObjectId();
  final String docRaw =
      String.format(
          "{\"_id\": {\"$oid\": \"%s\"}, \"intValue\": {\"$numberInt\": \"42\"}}",
          expectedObjectId.toHexString());

  // Check that BSON documents returned as extended JSON can be decoded into BSON
  // documents.
  doReturn(new Response(docRaw)).when(requestClient).doRequest(any(StitchRequest.class));
  Document doc = auth.doAuthenticatedRequest(reqBuilder.build(), Document.class, registry);
  assertEquals(expectedObjectId, doc.getObjectId("_id"));
  assertEquals(42, (int) doc.getInteger("intValue"));

  doReturn(new Response(docRaw)).when(requestClient).doRequest(any(StitchRequest.class));
  doc = auth.doAuthenticatedRequest(reqBuilder.build(), new DocumentCodec());
  assertEquals(expectedObjectId, doc.getObjectId("_id"));
  assertEquals(42, (int) doc.getInteger("intValue"));

  // Check that a custom type can be decoded without providing a codec, as long as that codec
  // is registered in the CoreStitchAuth's configuration.
  doReturn(new Response(docRaw)).when(requestClient).doRequest(any(StitchRequest.class));
  final CustomType ct = auth.doAuthenticatedRequest(
      reqBuilder.build(),
      CustomType.class,
      registry);
  assertEquals(expectedObjectId, ct.getId());
  assertEquals(42, ct.getIntValue());
}
 
Example 11
Source File: MongoImpl.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
public void initialize() {
    registry = CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), codecs.codecRegistry());
    database = createDatabase(registry);
}
 
Example 12
Source File: TestMongoClient.java    From jframe with Apache License 2.0 4 votes vote down vote up
public void testDriverStatus() {
		CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
				CodecRegistries.fromCodecs(new UuidCodec(
						UuidRepresentation.STANDARD)), MongoClient
						.getDefaultCodecRegistry());

		mongoClient.getDatabase("lech_rent").drop();
		MongoDatabase rent = mongoClient.getDatabase("lech_rent")
				.withCodecRegistry(codecRegistry);
		// rent.createCollection("driver_status", new CreateCollectionOptions()
		// .capped(true).sizeInBytes(0x100000));
		MongoCollection<Document> status = rent.getCollection("driver_status");
		status.deleteMany(Filters.eq("mobile", "18616020610"));
		if (status.count() == 0) {

		}
		status.createIndex(new Document("mobile", "text"));
		// status.createIndex(new Document("no", "text"));
		for (final Document index : status.listIndexes()) {
			System.out.println(index.toJson());
		}

		Document doc = new Document("loc",
				new Document("type", "Point").append("coordinates",
						Arrays.asList(-73.97, 40.77))).append("no", "dno")
				.append("usrImg", "/usr/driver.png")
				.append("mobile", "18616020610").append("status", 7)
				.append("car", new Document("no", "A00001"));
		status.insertOne(doc);
		// status.createIndex(keys);
		doc = status.find(Filters.eq("mobile", "18616020610")).first();

		System.out.println(doc.get("loc", Document.class).get("coordinates"));
		System.out.println(doc.get("loc", Document.class).get("coordinates",
				ArrayList.class));
		System.out.println(doc.get("car", Document.class));
		// System.out.println(doc.get("loc", Document.class));

//		UpdateResult updateResult = status.updateOne(Filters.eq("mobile",
//				"18616020610"), new Document("$set", new Document("car",
//				new Document("no", "A00002"))));
		doc = status.find(Filters.eq("mobile", "18616020610")).first();
		System.out.println(doc.get("car", Document.class));

		// updateResult = status.updateMany(Filters.lt("i", 100), new Document(
		// "$inc", new Document("i", 100)));
		// System.out.println(updateResult.getModifiedCount());
		// DeleteResult deleteResult = status.deleteOne(Filters.eq("i", 110));
		// System.out.println(deleteResult.getDeletedCount());

		// 2. Ordered bulk operation - order is guarenteed
		// status.bulkWrite(Arrays.asList(new InsertOneModel<>(new
		// Document("_id",
		// 4)), new InsertOneModel<>(new Document("_id", 5)),
		// new InsertOneModel<>(new Document("_id", 6)),
		// new UpdateOneModel<>(new Document("_id", 1), new Document(
		// "$set", new Document("x", 2))), new DeleteOneModel<>(
		// new Document("_id", 2)),
		// new ReplaceOneModel<>(new Document("_id", 3), new Document(
		// "_id", 3).append("x", 4))));

		// 2. Unordered bulk operation - no guarantee of order of operation
		// status.bulkWrite(Arrays.asList(new InsertOneModel<>(new
		// Document("_id",
		// 4)), new InsertOneModel<>(new Document("_id", 5)),
		// new InsertOneModel<>(new Document("_id", 6)),
		// new UpdateOneModel<>(new Document("_id", 1), new Document(
		// "$set", new Document("x", 2))), new DeleteOneModel<>(
		// new Document("_id", 2)),
		// new ReplaceOneModel<>(new Document("_id", 3), new Document(
		// "_id", 3).append("x", 4))), new BulkWriteOptions()
		// .ordered(false));

	}
 
Example 13
Source File: JacksonCodecs.java    From immutables with Apache License 2.0 4 votes vote down vote up
/**
 * Create {@link CodecRegistry} adapter on the top of existing mapper instance
 */
public static CodecRegistry registryFromMapper(final ObjectMapper mapper) {
  Objects.requireNonNull(mapper, "mapper");
  return CodecRegistries.fromRegistries(new NativeCodecRegistry(mapper), JacksonCodecRegistry.of(mapper));
}
 
Example 14
Source File: BsonUtils.java    From stitch-android-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Parses the provided extended JSON string and decodes it into a T value as specified by the
 * provided class type. The type will decoded using the codec found for the type in the provided
 * codec registry. If the provided type is not supported by the provided codec registry, the
 * method will throw a {@link org.bson.codecs.configuration.CodecConfigurationException}.
 *
 * @param json the JSON string to parse.
 * @param valueClass the class that the JSON string should be decoded into.
 * @param codecRegistry the codec registry to use to find the codec for the provided class.
 * @param <T> the type into which the JSON string is decoded.
 * @return the decoded value.
 */
public static <T> T parseValue(
    final String json, final Class<T> valueClass, final CodecRegistry codecRegistry) {
  final JsonReader bsonReader = new JsonReader(json);
  bsonReader.readBsonType();
  // We can't detect if their codecRegistry has any duplicate providers. There's also a chance
  // that putting ours first may prevent decoding of some of their classes if for example they
  // have their own way of decoding an Integer.
  final CodecRegistry newReg =
      CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);
  return newReg.get(valueClass).decode(bsonReader, DecoderContext.builder().build());
}