com.mongodb.WriteConcern Java Examples

The following examples show how to use com.mongodb.WriteConcern. 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: MongoDBUtil.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 *  Save i.e. INSERT or UPDATE an object to mongodb.
 *  
 * @param query usually the _id of collection, which is byte[] , null means insert a new row
 * @param objectToSave the object to save
 * @param databaseName the database
 * @param namespace the namespace, maybe null
 * @param isSafeWrite whether to enable the SafeWrite mode
 */
public static final void saveToMongo(DBObject query, DBObject objectToSave, 
		String databaseName, String namespace, String collection, boolean isSafeWrite) {

	DBCollection coll = getDBCollection(databaseName, namespace, collection);
	if ( isSafeWrite ) {
		if ( query == null ) {
			coll.insert(objectToSave);
		} else {
			coll.update(query, objectToSave, true, false, WriteConcern.SAFE);
		}
	} else {
		if ( query == null ) {
			coll.insert(objectToSave);
		} else {
			coll.update(query, objectToSave, true, false, WriteConcern.NONE);
		}
	}
}
 
Example #2
Source File: EmbeddedClient.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {

    final IMongodConfig mongodConfig = new MongodConfigBuilder()
            .version(Version.Main.PRODUCTION).build();

    IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder()
            .defaultsWithLogger(Command.MongoD, logger)
            .processOutput(ProcessOutput.getDefaultInstanceSilent())
            .build();

    MongodStarter runtime = MongodStarter.getInstance(runtimeConfig);

    MongodExecutable mongodExecutable = runtime.prepare(mongodConfig);
    mongod = mongodExecutable.start();

    // cluster configuration
    ClusterSettings clusterSettings = ClusterSettings.builder().hosts(Collections.singletonList(new ServerAddress(mongodConfig.net().getServerAddress().getHostName(), mongodConfig.net().getPort()))).build();
    // codec configuration
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings).codecRegistry(pojoCodecRegistry).writeConcern(WriteConcern.ACKNOWLEDGED).build();
    mongoClient = MongoClients.create(settings);
    mongoDatabase = mongoClient.getDatabase(databaseName);
}
 
Example #3
Source File: MongoDB.java    From act with GNU General Public License v3.0 6 votes vote down vote up
private void mergeIntoDB(long id, Chemical c) {
  Chemical oldc = getChemicalFromChemicalUUID(id);
  Chemical mergedc = c.createNewByMerge(oldc);

  if (mergedc == null) {
    // whoa! inconsistent values on unmergables, so recover

    System.err.println("\n\n\n\n\n\n\n\n\n\n");
    System.err.println("---- Conflicting uuid or name or smiles or inchi or inchikey or pubchem_id:");
    System.err.println("---- NEW\t " + c);
    System.err.println("---- OLD\t " + oldc);
    System.err.println("---- Keeping OLD entry");
    System.err.println("\n\n\n\n\n\n\n\n\n\n");

    return;
  }

  BasicDBObject withID = new BasicDBObject();
  withID.put("_id", id);
  this.dbChemicals.remove(withID, WriteConcern.SAFE); // remove the old entry oldc from the collection
  submitToActChemicalDB(mergedc, id); // now that the old entry is removed, we can simply add
}
 
Example #4
Source File: MongoDBConfig.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private MongoDatabase createMongoDatabase(
    Stage.Context context,
    List<Stage.ConfigIssue> issues,
    ReadPreference readPreference,
    WriteConcern writeConcern
) {
  MongoDatabase mongoDatabase = null;
  try {
    if (readPreference != null) {
      mongoDatabase = mongoClient.getDatabase(database).withReadPreference(readPreference);
    } else if (writeConcern != null) {
      mongoDatabase = mongoClient.getDatabase(database).withWriteConcern(writeConcern);
    }
  } catch (MongoClientException e) {
    issues.add(context.createConfigIssue(
        Groups.MONGODB.name(),
        MONGO_CONFIG_PREFIX + "database",
        Errors.MONGODB_02,
        database,
        e.toString()
    ));
  }
  return mongoDatabase;
}
 
Example #5
Source File: MongoWriteConcernMapper.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private Map<WriteConcern, String> buildWriteConcern() {
    Map<WriteConcern, String> writeConcernMap = new HashMap<WriteConcern, String>();
    for (final Field f : WriteConcern.class.getFields()) {
        if (Modifier.isStatic(f.getModifiers())
                && f.getType().equals(WriteConcern.class)
                && f.getAnnotation(Deprecated.class) == null) {

            String value = f.getName();
            try {
                WriteConcern key = (WriteConcern) f.get(null);
                writeConcernMap.put(key, value);
            } catch (IllegalAccessException e) {
                PLogger logger = PLoggerFactory.getLogger(this.getClass());
                logger.warn("WriteConcern access error Caused by:" + e.getMessage(), e);
            }
        }
    }
    return writeConcernMap;
}
 
Example #6
Source File: MongoEntityPersister.java    From aw-reporting with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T save(T t) {
  T newT = null;
  if (t != null) {
    String jsonObject = gson.toJson(t);
    DBObject dbObject = (DBObject) com.mongodb.util.JSON.parse(jsonObject.toString());
    dbObject.put("safe", "true");

    // Set the proper _id from the MongoEntity RowID
    if (t instanceof MongoEntity) {
      dbObject.put("_id", ((MongoEntity) t).getRowId());
    }

    getCollection(t.getClass()).save(dbObject, WriteConcern.SAFE);
  }
  return newT;
}
 
Example #7
Source File: DenormalizerTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    studentSectionAssociation.put("sectionId", SECTION1);
    studentSectionAssociation.put("studentId", STUDENT1);
    studentSectionAssociation.put("beginDate", BEGINDATE);
    studentSectionAssociation.put("endDate", ENDDATE1);

    WriteResult success = mock(WriteResult.class);
    CommandResult successCR = mock(CommandResult.class);
    CommandResult failCR = mock(CommandResult.class);
    when(success.getLastError()).thenReturn(successCR);
    when(successCR.ok()).thenReturn(true);
    when(successCR.get("value")).thenReturn("updated");
    when(failCR.get("value")).thenReturn(null);
    when(failCR.get("result")).thenReturn(null);
    when(studentCollection.update(any(DBObject.class), any(DBObject.class), eq(false), eq(true), eq(WriteConcern.SAFE))).thenReturn(
            success);
    when(studentCollection.update(any(DBObject.class), any(DBObject.class), eq(true), eq(true), eq(WriteConcern.SAFE))).thenReturn(
            success);
    when(template.getCollection("student")).thenReturn(studentCollection);

    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(SSAID));
    MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation);
    when(template.findOne(eq(query), eq(Entity.class), eq("studentSectionAssociation"))).thenReturn(entity);
}
 
Example #8
Source File: MongoWriteConcernInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args, result, throwable);
    }

    if (args == null) {
        return;
    }

    DatabaseInfo databaseInfo = DatabaseInfoUtils.getDatabaseInfo(target, UnKnownDatabaseInfo.MONGO_INSTANCE);

    String writeConcernStr = MongoUtil.getWriteConcern0((WriteConcern) args[0]);

    databaseInfo = new MongoDatabaseInfo(databaseInfo.getType(), databaseInfo.getExecuteQueryType()
            , databaseInfo.getRealUrl(), databaseInfo.getUrl(), databaseInfo.getHost(), databaseInfo.getDatabaseId()
            , ((MongoDatabaseInfo) databaseInfo).getCollectionName(), ((MongoDatabaseInfo) databaseInfo).getReadPreference(), writeConcernStr);

    if (result instanceof DatabaseInfoAccessor) {
        ((DatabaseInfoAccessor) result)._$PINPOINT$_setDatabaseInfo(databaseInfo);
    }
}
 
Example #9
Source File: MongoWriteConcernMapper.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public String getName(WriteConcern writeConcern) {
    String ret = writeConcernMap.get(writeConcern);
    if (ret == null) {
        return INVALID;
    }
    return ret;
}
 
Example #10
Source File: ContainerDocumentAccessorTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateContainerFields() {
    Query query = Mockito.mock(Query.class);
    DBObject queryObject = Mockito.mock(DBObject.class);
    Map<String, Object> body = entity.getBody();

    Map<String, Object> fields = new HashMap<String, Object>();
    for (Map.Entry<String, Object> entry : body.entrySet()) {
        if(!entry.getKey().equals("attendanceEvent")) {
            fields.put("body." + entry.getKey(), entry.getValue());
        }
    }
    final Map<String, Object> attendanceEvent = new HashMap<String, Object>();
    final List<Map<String, Object>> attendanceEvents = new ArrayList<Map<String, Object>>();
    attendanceEvent.put("event", "Tardy");
    attendanceEvents.add(attendanceEvent);

    DBObject docsToPersist = BasicDBObjectBuilder.start().push("$pushAll").add("body.attendanceEvent", attendanceEvents).get();
    DBObject bodyFields = new BasicDBObject("$set", new BasicDBObject(fields));
    docsToPersist.putAll(bodyFields);

    when(query.getQueryObject()).thenReturn(queryObject);
    when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection);
    when(mockCollection.update(Mockito.eq(queryObject), Mockito.eq(docsToPersist), Mockito.eq(true), Mockito.eq(false), Mockito.eq(WriteConcern.SAFE))).thenReturn(writeResult);

    boolean result = testAccessor.updateContainerDoc(query, body, ATTENDANCE, ATTENDANCE);

    assertTrue(result);
    Mockito.verify(mockCollection, Mockito.times(1)).update(Mockito.eq(queryObject), Mockito.eq(docsToPersist), Mockito.eq(true), Mockito.eq(false), Mockito.eq(WriteConcern.SAFE));
}
 
Example #11
Source File: MongoRelationRosterContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
public MongoRelationRosterContext remove(JID from, JID to) {
	if (MongoUtils.success(this.config.collection().remove(this.buildQuery(from.asStringWithBare(), to.asStringWithBare()), WriteConcern.SAFE)) && MongoUtils.success(this.config.collection().remove(this.buildQuery(to.asStringWithBare(), from.asStringWithBare()), WriteConcern.SAFE))) {
		this.relationCascade.remove(to, from);
	} else {
		this.log.error("Remove warning: " + from.asStringWithBare() + " / " + to.asStringWithBare());
	}
	return this;
}
 
Example #12
Source File: DeleteVo.java    From tangyuan2 with GNU General Public License v3.0 5 votes vote down vote up
public int delete(DBCollection collection, WriteConcern writeConcern) {
	DBObject query = new BasicDBObject();
	if (null != condition) {
		this.condition.setQuery(query, null);
	}

	log(query);

	// WriteResult result = collection.remove(query, WriteConcern.ACKNOWLEDGED);
	WriteResult result = collection.remove(query, writeConcern);
	// collection.remove(query)
	// System.out.println(query.toString());
	return result.getN();
}
 
Example #13
Source File: MongoConfig.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public MongoConfig(DataService dataService, String configId, Map<String, String> properties, boolean odataEnable)
        throws DataServiceFault {
    super(dataService, configId, DBConstants.DataSourceTypes.MONGODB, properties, odataEnable);
    String serversParam = properties.get(DBConstants.MongoDB.SERVERS);
    if (DBUtils.isEmptyString(serversParam)) {
        throw new DataServiceFault("The data source param '" + DBConstants.MongoDB.SERVERS + "' is required");
    }
    this.servers = serversParam.split(",");
    String database = properties.get(DBConstants.MongoDB.DATABASE);
    if (DBUtils.isEmptyString(database)) {
        throw new DataServiceFault("The data source param '" + DBConstants.MongoDB.DATABASE + "' is required");
    }
    try {
        this.mongoClientOptions = extractMongoOptions(properties);
        this.mongoClient = createNewMongo(properties);
        String writeConcern = properties.get(DBConstants.MongoDB.WRITE_CONCERN);
        if (!DBUtils.isEmptyString(writeConcern)) {
            this.getMongoClient().setWriteConcern(WriteConcern.valueOf(writeConcern));
        }
        String readPref = properties.get(DBConstants.MongoDB.READ_PREFERENCE);
        if (!DBUtils.isEmptyString(readPref)) {
            this.getMongoClient().setReadPreference(ReadPreference.valueOf(readPref));
        }
        this.getMongoClient().getDatabase(database);
        this.jongo = new Jongo(this.getMongoClient().getDB(database));
    } catch (Exception e) {
        throw new DataServiceFault(e, DBConstants.FaultCodes.CONNECTION_UNAVAILABLE_ERROR, e.getMessage());
    }

}
 
Example #14
Source File: EclipseLinkConfigurationTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testMongoClientOptions() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("eclipselink.nosql.property.mongo.db", "foo");

    // it looks like only the two options below are supported by EclipseLink

    final ReadPreference readPreference = ReadPreference.nearest();
    final WriteConcern writeConcern = WriteConcern.JOURNALED;

    properties.put("eclipselink.nosql.property.mongo.read-preference", readPreference.getName());
    properties.put("eclipselink.nosql.property.mongo.write-concern", "JOURNALED");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final MongoClientOptions clientOptions = configuration.getClientOptions();
    assertThat(clientOptions, notNullValue());
    assertThat(clientOptions.getReadPreference(), equalTo(readPreference));
    assertThat(clientOptions.getWriteConcern(), equalTo(writeConcern));
}
 
Example #15
Source File: MuiltMongoDataSourceManager.java    From tangyuan2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public WriteConcern getDefaultWriteConcern(String dsKey) {
	AbstractMongoDataSource dataSource = realDataSourceMap.get(dsKey);
	if (null == dataSource) {
		throw new DataSourceException("A non-existent mongo data source: " + dsKey);
	}
	return dataSource.getDefaultWriteConcern();
}
 
Example #16
Source File: MongoDB.java    From aion with MIT License 5 votes vote down vote up
@Override
public boolean open() {
    if (isOpen()) {
        return true;
    }

    LOG.info("Initializing MongoDB at {}", mongoClientUri);

    // Get the client and create a session for this instance
    MongoClient mongoClient =
            MongoConnectionManager.inst().getMongoClientInstance(this.mongoClientUri);
    ClientSessionOptions sessionOptions =
            ClientSessionOptions.builder()
                    .causallyConsistent(true)
                    .defaultTransactionOptions(
                            TransactionOptions.builder()
                                    .readConcern(ReadConcern.DEFAULT)
                                    .writeConcern(WriteConcern.MAJORITY)
                                    .readPreference(ReadPreference.nearest())
                                    .build())
                    .build();
    this.clientSession = mongoClient.startSession(sessionOptions);

    // Get the database and our collection. Mongo takes care of creating these if they don't
    // exist
    MongoDatabase mongoDb = mongoClient.getDatabase(MongoConstants.AION_DB_NAME);

    // Gets the collection where we will be saving our values. Mongo creates it if it doesn't
    // yet exist
    this.collection = mongoDb.getCollection(this.name, BsonDocument.class);

    LOG.info("Finished opening the Mongo connection");
    return isOpen();
}
 
Example #17
Source File: MongoConnection.java    From bluima with Apache License 2.0 5 votes vote down vote up
/**
 * @param db_connection
 *            an array {host, dbName, collectionName, user, pw}. Leave user
 *            and pw empty ("") to skip authentication
 */
public MongoConnection(String[] db_connection, boolean safe)
		throws UnknownHostException, MongoException {

	checkArgument(db_connection.length == 5,
			"Should be: host, dbname, collectionname, user, pw but lengh = "
					+ db_connection.length);

	host = db_connection[0];
	dbName = db_connection[1];
	collectionName = db_connection[2];
	user = db_connection[3];
	pw = db_connection[4];

	checkNotNull(host, "host is NULL");
	checkNotNull(dbName, "dbName is NULL");
	checkNotNull(collectionName, "collectionName is NULL");
	checkNotNull(user, "user is NULL");
	checkNotNull(pw, "pw is NULL");

	m = new Mongo(host, 27017);
	if (safe)
		m.setWriteConcern(WriteConcern.SAFE);
	m.getDatabaseNames();// to test connection
	db = m.getDB(dbName);
	if (user.length() > 0) {
		if (!db.authenticate(user, pw.toCharArray())) {
			throw new MongoException(-1, "cannot login with user " + user);
		}
	}
	coll = db.getCollection(collectionName);
}
 
Example #18
Source File: WriteConcernParserTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdvancedWriteConcern_w_string_only() {
  WriteConcern expected = new WriteConcern("foo");
  JsonObject config = new JsonObject();
  config.put("w", "foo");

  WriteConcern wc = new WriteConcernParser(null, config).writeConcern();
  assertNotNull(wc);
  assertEquals(expected, wc);
}
 
Example #19
Source File: MongoRegisterSubmitContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(JID invoker, JID group, Fields fields) {
	DBObject entity = super.entities(fields, BasicDBObjectBuilder.start());
	try {
		// {"jid":to.bare,"informations.jid":from.bare},{"$set":{"infomrations.$.information":..entity..}}
		this.config.collection().update(BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, group.asStringWithBare()).add(Dictionary.FIELD_INFORMATIONS + "." + Dictionary.FIELD_JID, invoker.asStringWithBare()).get(), BasicDBObjectBuilder.start("$set", BasicDBObjectBuilder.start(Dictionary.FIELD_INFORMATIONS + ".$." + Dictionary.FIELD_INFORMATION, entity).get()).get(), true, false, WriteConcern.SAFE);
	} catch (MongoException e) {
		// {"jid":to.bare},{"$addToSet"{"informations":{"jid":from.bare,"activate":当前时间,"information":...entity...}}}
		this.config.collection().update(BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, group.asStringWithBare()).get(), BasicDBObjectBuilder.start().add("$addToSet", BasicDBObjectBuilder.start(Dictionary.FIELD_INFORMATIONS, BasicDBObjectBuilder.start().add(Dictionary.FIELD_JID, invoker.asStringWithBare()).add(Dictionary.FIELD_ACTIVATE, System.currentTimeMillis()).add(Dictionary.FIELD_INFORMATION, entity).get()).get()).get());
	}
	return true;
}
 
Example #20
Source File: DenormalizerTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreate() {
    MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation);
    entity.getMetaData().put("tenantId", "TEST");
    assertTrue(denormalizer.denormalization("studentSectionAssociation").create(entity));
    verify(studentCollection).update(eq(BasicDBObjectBuilder.start("_id", STUDENT1).get()),
            argThat(new ArgumentMatcher<DBObject>() {

                @Override
                @SuppressWarnings("unchecked")
                public boolean matches(Object argument) {
                    DBObject updateObject = (DBObject) argument;
                    Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll");
                    if (push == null) {
                        return false;
                    }
                    Collection<Object> toPush = push.values();
                    if (toPush.size() != 1) {
                        return false;
                    }
                    Object[] sectionRefsToPush = (Object[]) toPush.iterator().next();
                    List<String> ssaIds = new ArrayList<String>(push.keySet());

                    return ((((Map<String, Object>) sectionRefsToPush[0]).get("_id").equals(SECTION1))
                            && (((Map<String, Object>) sectionRefsToPush[0]).get("endDate").equals(ENDDATE1))
                            && (((Map<String, Object>) sectionRefsToPush[0]).get("beginDate").equals(BEGINDATE))
                            && ssaIds.get(0).equals("section"));
                }
            }), eq(true), eq(true), eq(WriteConcern.SAFE));
}
 
Example #21
Source File: MongoDBSnapshotStore.java    From swellrt with Apache License 2.0 5 votes vote down vote up
protected void deleteSnapshot(WaveletName waveletName) throws PersistenceException {

    BasicDBObject criteria = new BasicDBObject();
    criteria.put(WAVE_ID_FIELD, ModernIdSerialiser.INSTANCE.serialiseWaveId(waveletName.waveId));
    criteria.put(WAVELET_ID_FIELD, ModernIdSerialiser.INSTANCE.serialiseWaveletId(waveletName.waveletId));

    try {
      // Using Journaled Write Concern
      // (http://docs.mongodb.org/manual/core/write-concern/#journaled)
      collection.withWriteConcern(WriteConcern.JOURNALED).deleteMany(criteria);
    } catch (MongoException e) {
      throw new PersistenceException(e);
    }
  }
 
Example #22
Source File: MongoDbDeltaCollection.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
public void append(Collection<WaveletDeltaRecord> newDeltas) throws PersistenceException {

  for (WaveletDeltaRecord delta : newDeltas) {
    // Using Journaled Write Concern
    // (http://docs.mongodb.org/manual/core/write-concern/#journaled)
    deltaDbCollection.insert(MongoDbDeltaStoreUtil.serialize(delta,
        waveletName.waveId.serialise(), waveletName.waveletId.serialise()),
        WriteConcern.JOURNALED);
  }
}
 
Example #23
Source File: AbstractMongoProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected WriteConcern getWriteConcern(final ProcessContext context) {
    final String writeConcernProperty = context.getProperty(WRITE_CONCERN).getValue();
    WriteConcern writeConcern = null;
    switch (writeConcernProperty) {
        case WRITE_CONCERN_ACKNOWLEDGED:
            writeConcern = WriteConcern.ACKNOWLEDGED;
            break;
        case WRITE_CONCERN_UNACKNOWLEDGED:
            writeConcern = WriteConcern.UNACKNOWLEDGED;
            break;
        case WRITE_CONCERN_FSYNCED:
            writeConcern = WriteConcern.FSYNCED;
            break;
        case WRITE_CONCERN_JOURNALED:
            writeConcern = WriteConcern.JOURNALED;
            break;
        case WRITE_CONCERN_REPLICA_ACKNOWLEDGED:
            writeConcern = WriteConcern.REPLICA_ACKNOWLEDGED;
            break;
        case WRITE_CONCERN_MAJORITY:
            writeConcern = WriteConcern.MAJORITY;
            break;
        default:
            writeConcern = WriteConcern.ACKNOWLEDGED;
    }
    return writeConcern;
}
 
Example #24
Source File: MongoAddressing.java    From sissi with Apache License 2.0 5 votes vote down vote up
@Override
public Addressing join(JIDContext context) {
	if (MongoUtils.success(this.config.collection().save(this.buildQueryWithNecessaryFields(context), WriteConcern.SAFE))) {
		this.contexts.put(context.index(), context);
	}
	return this;
}
 
Example #25
Source File: WriteConcernParserTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnStringWriteConcern() {
  final ConnectionString connString = new ConnectionString("mongodb://localhost:27017/mydb?replicaSet=myapp&safe=true");
  WriteConcern wc = new WriteConcernParser(connString, new JsonObject()).writeConcern();

  assertNotNull(wc);
  assertEquals(WriteConcern.ACKNOWLEDGED, wc);
}
 
Example #26
Source File: ChronoGraph.java    From epcis with Apache License 2.0 5 votes vote down vote up
public ChronoGraph(String databaseName) {
	setFeatures();
	mongoClient = new MongoClient("localhost", 27017);
	mongoDatabase = mongoClient.getDatabase(databaseName);
	edges = mongoDatabase.getCollection(Tokens.EDGE_COLLECTION, BsonDocument.class)
			.withWriteConcern(WriteConcern.UNACKNOWLEDGED);
	vertices = mongoDatabase.getCollection(Tokens.VERTEX_COLLECTION, BsonDocument.class)
			.withWriteConcern(WriteConcern.UNACKNOWLEDGED);
	edgeEvents = mongoDatabase.getCollection(Tokens.TIMESTAMP_EDGE_EVENT_COLLECTION, BsonDocument.class)
			.withWriteConcern(WriteConcern.UNACKNOWLEDGED);
	vertexEvents = mongoDatabase.getCollection(Tokens.TIMESTAMP_VERTEX_EVENT_COLLECTION, BsonDocument.class)
			.withWriteConcern(WriteConcern.UNACKNOWLEDGED);
	createBasicIndex();
	id = databaseName;
}
 
Example #27
Source File: ChronoGraph.java    From epcis with Apache License 2.0 5 votes vote down vote up
public ChronoGraph(String host, int port, String databaseName) {
	setFeatures();
	mongoClient = new MongoClient(host, port);
	mongoDatabase = mongoClient.getDatabase(databaseName);
	edges = mongoDatabase.getCollection(Tokens.EDGE_COLLECTION, BsonDocument.class)
			.withWriteConcern(WriteConcern.UNACKNOWLEDGED);
	vertices = mongoDatabase.getCollection(Tokens.VERTEX_COLLECTION, BsonDocument.class)
			.withWriteConcern(WriteConcern.UNACKNOWLEDGED);
	edgeEvents = mongoDatabase.getCollection(Tokens.TIMESTAMP_EDGE_EVENT_COLLECTION, BsonDocument.class)
			.withWriteConcern(WriteConcern.UNACKNOWLEDGED);
	vertexEvents = mongoDatabase.getCollection(Tokens.TIMESTAMP_VERTEX_EVENT_COLLECTION, BsonDocument.class)
			.withWriteConcern(WriteConcern.UNACKNOWLEDGED);
	createBasicIndex();
	id = databaseName;
}
 
Example #28
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
private MongoCollection<JsonObject> getCollection(String name, @Nullable WriteOption writeOption) {
  MongoCollection<JsonObject> coll = holder.db.getCollection(name, JsonObject.class);
  if (coll != null && writeOption != null) {
    coll = coll.withWriteConcern(WriteConcern.valueOf(writeOption.name()));
  }
  return coll;
}
 
Example #29
Source File: WriteConcernParserTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnStringSimpleAndAdvancedWriteConcern() {
  final ConnectionString connString = new ConnectionString("mongodb://localhost:27017/mydb?replicaSet=myapp" +
    "&w=majority&wtimeoutms=20&journal=false");
  WriteConcern expected = new WriteConcern("majority").withWTimeout(20, TimeUnit.MILLISECONDS).withJournal(false);
  WriteConcern wc = new WriteConcernParser(connString, new JsonObject()).writeConcern();
  assertNotNull(wc);
  assertEquals(expected, wc);
}
 
Example #30
Source File: MongoRelationRosterContext.java    From sissi with Apache License 2.0 5 votes vote down vote up
@Override
public MongoRelationRosterContext establish(JID from, Relation relation) {
	// {"$set":{(...relation.plus()...),"nick":relation.name(),"activate":true},"$setOnInsert":{"status":0}}
	// {"$setOnInsert":{"activate":false,"status":0}}
	if (MongoUtils.success(this.config.collection().update(this.buildQuery(from.asStringWithBare(), relation.jid()), BasicDBObjectBuilder.start().add("$set", BasicDBObjectBuilder.start(relation.plus()).add(Dictionary.FIELD_NICK, relation.name()).add(Dictionary.FIELD_ACTIVATE, true).get()).add("$setOnInsert", this.initMaster).get(), true, false, WriteConcern.SAFE)) && MongoUtils.success(this.config.collection().update(this.buildQuery(relation.jid(), from.asStringWithBare()), BasicDBObjectBuilder.start("$setOnInsert", this.initSlave).get(), true, false, WriteConcern.SAFE))) {
		return this;
	}
	this.log.error("Establish warning: " + from.asStringWithBare() + " / " + relation.jid());
	return this;
}