Example usage for com.mongodb WriteConcern ACKNOWLEDGED

List of usage examples for com.mongodb WriteConcern ACKNOWLEDGED

Introduction

In this page you can find the example usage for com.mongodb WriteConcern ACKNOWLEDGED.

Prototype

WriteConcern ACKNOWLEDGED

To view the source code for com.mongodb WriteConcern ACKNOWLEDGED.

Click Source Link

Document

Write operations that use this write concern will wait for acknowledgement, using the default write concern configured on the server.

Usage

From source file:com.setronica.ucs.storage.MongoListStorage.java

License:LGPL

@Override
public void open() throws IOException {
    DB db = mongoClient.getDB(mongoDbName);
    collection = db.getCollection(mongoCollectionName);
    if (collection == null) {
        collection = db.createCollection(mongoCollectionName, null);
    }/*from   w  w  w.j a v a  2s. com*/
    collection.setWriteConcern(WriteConcern.ACKNOWLEDGED);

    DBCursor cursor = collection.find();
    data = new ArrayList<E>(cursor.size());
    for (DBObject entry : cursor) {
        Integer index = (Integer) entry.get("_id");
        while (index >= data.size()) {
            data.add(null);
        }
        data.set(index, (E) readObject((byte[]) entry.get("element")));
    }
}

From source file:com.setronica.ucs.storage.MongoMapStorage.java

License:LGPL

@Override
public void open() throws IOException {
    DB db = mongoClient.getDB(mongoDbName);
    collection = db.getCollection(mongoCollectionName);
    if (collection == null) {
        collection = db.createCollection(mongoCollectionName, null);
    }/*w ww.j  av a  2  s. com*/
    collection.setWriteConcern(WriteConcern.ACKNOWLEDGED);

    DBCursor cursor = collection.find();
    data = new HashMap<K, E>(cursor.size());
    for (DBObject entry : cursor) {
        data.put((K) readObject(entry.get("_id")), (E) readObject(entry.get("value")));
    }
}

From source file:com.softinstigate.restheart.db.MongoDBClientSingleton.java

License:Open Source License

private void setup() throws UnknownHostException {
    if (initialized) {
        List<ServerAddress> servers = new ArrayList<>();
        List<MongoCredential> credentials = new ArrayList<>();

        for (Map<String, Object> mongoServer : mongoServers) {
            Object mongoHost = mongoServer.get(Configuration.MONGO_HOST_KEY);
            Object mongoPort = mongoServer.get(Configuration.MONGO_PORT_KEY);

            if (mongoHost != null && mongoHost instanceof String && mongoPort != null
                    && mongoPort instanceof Integer) {
                servers.add(new ServerAddress((String) mongoHost, (int) mongoPort));
            }/*from w  w w .ja va2 s  . c om*/
        }

        if (mongoCredentials != null) {
            for (Map<String, Object> mongoCredential : mongoCredentials) {
                Object mongoAuthDb = mongoCredential.get(Configuration.MONGO_AUTH_DB_KEY);
                Object mongoUser = mongoCredential.get(Configuration.MONGO_USER_KEY);
                Object mongoPwd = mongoCredential.get(Configuration.MONGO_PASSWORD_KEY);

                if (mongoAuthDb != null && mongoAuthDb instanceof String && mongoUser != null
                        && mongoUser instanceof String && mongoPwd != null && mongoPwd instanceof String) {
                    credentials.add(MongoCredential.createMongoCRCredential((String) mongoUser,
                            (String) mongoAuthDb, ((String) mongoPwd).toCharArray()));
                }
            }
        }

        MongoClientOptions opts = MongoClientOptions.builder().readPreference(ReadPreference.primaryPreferred())
                .writeConcern(WriteConcern.ACKNOWLEDGED).build();

        mongoClient = new MongoClient(servers, credentials, opts);
    }
}

From source file:com.stratio.connector.mongodb.core.configuration.MongoClientConfiguration.java

License:Apache License

/**
 * Convert the mongo connector string option to the appropriate write concern.
 *
 * @param writeSetting/*from   w  w w . j a v  a  2s  .co  m*/
 *            the write concern string setting
 * @return the write concern
 * @throws MongoValidationException
 *             if the value cannot be parsed to a WriteConcern
 */
private WriteConcern settingToWritePreference(String writeSetting) throws MongoValidationException {

    WriteConcern writeConcern = null;
    switch (writeSetting.trim().toLowerCase()) {
    case "acknowledged":
        writeConcern = WriteConcern.ACKNOWLEDGED;
        break;
    case "unacknowledged":
        writeConcern = WriteConcern.UNACKNOWLEDGED;
        break;
    case "replica_acknowledged":
        writeConcern = WriteConcern.REPLICA_ACKNOWLEDGED;
        break;
    case "journaled":
        writeConcern = WriteConcern.JOURNALED;
        break;
    default:
        throw new MongoValidationException("Write preference " + writeSetting + " is not a legal value");
    }
    return writeConcern;

}

From source file:com.tensorwrench.testng.mongo.MongoTestDriver.java

License:Apache License

public MongoTestDriver() {
    try {//from   w  w  w . ja  v a2 s  .com
        mongoClient = new MongoClient();
        mongoDB = mongoClient.getDB(dbName);
        mongoDB.setWriteConcern(WriteConcern.ACKNOWLEDGED);
    } catch (UnknownHostException e) {
        Assert.fail("Failed to create Mongo Client", e);
    }
}

From source file:com.torodb.mongowp.mongoserver.api.toro.ToroLastError.java

License:Open Source License

@SuppressFBWarnings("DLS_DEAD_LOCAL_STORE")
private WriteConcern getWriteConcern(Object w, boolean j, boolean fsync, int wtimeout) {
    WriteConcern writeConcern = WriteConcern.ACKNOWLEDGED;

    if (w instanceof Number) {
        if (((Number) w).intValue() <= 1 && wtimeout > 0) {
            throw new IllegalArgumentException("wtimeout cannot be grater than 0 for w <= 1");
        }//from   www  .j  a  v a  2 s  .  co  m

        writeConcern = new WriteConcern(((Number) w).intValue(), wtimeout, fsync, j);
    } else if (w instanceof String && w.equals("majority")) {
        if (wtimeout > 0) {
            throw new IllegalArgumentException("wtimeout cannot be grater than 0 for w <= 1");
        }

        writeConcern = new WriteConcern.Majority(wtimeout, fsync, j);
    } else {
        throw new IllegalArgumentException("w:" + w + " is not supported");
    }

    return writeConcern;
}

From source file:com.torodb.mongowp.mongoserver.api.toro.ToroQueryCommandProcessor.java

License:Open Source License

private WriteConcern getWriteConcern(BSONDocument document) {
    WriteConcern writeConcern = WriteConcern.ACKNOWLEDGED;
    if (document.hasKey("writeConcern")) {
        BSONObject writeConcernObject = (BSONObject) document.getValue("writeConcern");
        Object w = writeConcernObject.get("w");
        int wtimeout = 0;
        boolean fsync = false;
        boolean j = false;
        boolean continueOnError = false;
        Object jObject = writeConcernObject.get("j");
        if (jObject != null && jObject instanceof Boolean && (Boolean) jObject) {
            fsync = true;/*from  ww  w.j  av  a  2  s.  c o m*/
            j = true;
            continueOnError = true;
        }
        Object wtimeoutObject = writeConcernObject.get("wtimneout");
        if (wtimeoutObject != null && wtimeoutObject instanceof Number) {
            wtimeout = ((Number) wtimeoutObject).intValue();
        }
        if (w != null) {
            if (w instanceof Number) {
                if (((Number) w).intValue() <= 1 && wtimeout > 0) {
                    throw new IllegalArgumentException("wtimeout cannot be grater than 0 for w <= 1");
                }

                writeConcern = new WriteConcern(((Number) w).intValue(), wtimeout, fsync, j);
            } else if (w instanceof String && w.equals("majority")) {
                if (wtimeout > 0) {
                    throw new IllegalArgumentException("wtimeout cannot be grater than 0 for w <= 1");
                }

                writeConcern = new WriteConcern.Majority(wtimeout, fsync, j);
            } else {
                throw new IllegalArgumentException("w:" + w + " is not supported");
            }
        }
    }
    return writeConcern;
}

From source file:com.torodb.torod.mongodb.unsafe.ToroQueryCommandProcessor.java

License:Open Source License

private WriteConcern getWriteConcern(BsonDocument document) {
    WriteConcern writeConcern = WriteConcern.ACKNOWLEDGED;
    if (document.containsKey("writeConcern")) {
        BsonDocument writeConcernObject = document.get("writeConcern").asDocument();
        BsonValue w = writeConcernObject.get("w");
        int wtimeout = 0;
        boolean fsync = false;
        boolean j = false;
        boolean continueOnError;
        BsonValue jObject = writeConcernObject.get("j");
        if (jObject != null && jObject.isBoolean() && jObject.asBoolean().getValue()) {
            fsync = true;/* w  ww. ja  v  a  2  s .  c o m*/
            j = true;
            continueOnError = true;
        }
        BsonValue wtimeoutObject = writeConcernObject.get("wtimneout");
        if (wtimeoutObject != null && wtimeoutObject.isNumber()) {
            wtimeout = wtimeoutObject.asNumber().intValue();
        }
        if (w != null) {
            if (w.isNumber()) {
                if (w.asNumber().intValue() <= 1 && wtimeout > 0) {
                    throw new IllegalArgumentException("wtimeout cannot be grater than 0 for w <= 1");
                }

                writeConcern = new WriteConcern(w.asNumber().intValue(), wtimeout, fsync, j);
            } else if (w.isString() && w.asString().getValue().equals("majority")) {
                if (wtimeout > 0) {
                    throw new IllegalArgumentException("wtimeout cannot be grater than 0 for w <= 1");
                }

                writeConcern = new WriteConcern.Majority(wtimeout, fsync, j);
            } else {
                throw new IllegalArgumentException("w:" + w + " is not supported");
            }
        }
    }
    return writeConcern;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

private MongoClient client() {
    mutex.lock();/*  w w  w  . j a  v a 2  s  .  c o  m*/
    try {
        if (__client == null) {
            final MongoClientOptions options = MongoClientOptions.builder()
                    .readPreference(ReadPreference.nearest()).writeConcern(WriteConcern.ACKNOWLEDGED).build();
            final Splitter splitter = on(':').trimResults().omitEmptyStrings().limit(2);
            final List<ServerAddress> seeds = from(CONFIG_MANAGER.getDbHosts())
                    .transform(new Function<String, ServerAddress>() {
                        @Override
                        public ServerAddress apply(final String entry) {
                            ServerAddress seed = null;
                            try {
                                final List<String> tokens = splitter.splitToList(entry);
                                switch (tokens.size()) {
                                case 1:
                                    seed = new ServerAddress(tokens.get(0), 27017);
                                    break;
                                case 2:
                                    int port = parseInt(tokens.get(1));
                                    seed = new ServerAddress(tokens.get(0), port);
                                    break;
                                default:
                                    break;
                                }
                            } catch (Exception e) {
                                LOGGER.error("Invalid host", e);
                            }
                            return seed;
                        }
                    }).filter(notNull()).toList();
            // enable/disable authentication (requires MongoDB server to be configured to support authentication)
            final List<MongoCredential> credentials = newArrayList();
            if (!CONFIG_MANAGER.isAnonymousDbAccess()) {
                credentials.add(createMongoCRCredential(CONFIG_MANAGER.getDbUsername(),
                        CONFIG_MANAGER.getDbName(), CONFIG_MANAGER.getDbPassword().toCharArray()));
            }
            __client = new MongoClient(seeds, credentials, options);
            // check class attributes accessed by reflection
            try {
                final Field metadataField = BaseFile.class.getDeclaredField(METADATA_ATTR);
                checkNotNull(metadataField, "Metadata property (" + METADATA_ATTR + ") not found in file base: "
                        + BaseFile.class.getCanonicalName());
                final Class<?> metadataType = metadataField.getType();
                checkState(Versionable.class.isAssignableFrom(metadataType),
                        "Metadata does not implements versionable: " + metadataType.getCanonicalName());
                checkNotNull(Versionable.class.getDeclaredField(IS_LATEST_VERSION_ATTR),
                        "Version property (" + IS_LATEST_VERSION_ATTR + ") not found in versionable: "
                                + Versionable.class.getCanonicalName());
                checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_LINK_ATTR),
                        "Open access link property (" + OPEN_ACCESS_LINK_ATTR + ") not found in metadata: "
                                + metadataType.getCanonicalName());
                checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_DATE_ATTR),
                        "Open access date property (" + OPEN_ACCESS_DATE_ATTR + ") not found in metadata: "
                                + metadataType.getCanonicalName());
            } catch (Exception e) {
                throw new IllegalStateException(
                        "Object versioning needs a compatible version of the LVL core library, but none is available",
                        e);
            }
        }
        return __client;
    } finally {
        mutex.unlock();
    }
}

From source file:eu.project.ttc.models.occstore.MongoDBOccurrenceStore.java

License:Apache License

public MongoDBOccurrenceStore(String mongoDbUri, State state) {
    super();//from  w w w .  j  av  a  2  s . c om

    Preconditions.checkNotNull(mongoDbUri, "MongoDB dadabase's URI must not be null");
    Preconditions.checkState(state != State.INDEXING, "Invalid occ store state for constructor. Only "
            + State.COLLECTING + " and " + State.INDEXED + " allowed");

    this.mongoDBUri = getMongoDBUri(mongoDbUri);
    this.state = state;

    initThreadExecutor();

    MongoClientURI connectionString = new MongoClientURI(mongoDbUri);
    this.mongoClient = new MongoClient(connectionString);
    MongoDatabase db = mongoClient.getDatabase(this.mongoDBUri.getDatabase())
            .withWriteConcern(WriteConcern.ACKNOWLEDGED);
    db.runCommand(new org.bson.Document("profile", 1));

    if (state == State.COLLECTING)
        db.drop();

    this.termCollection = db.getCollection("terms");
    this.occurrenceCollection = db.getCollection("occurrences");
    this.documentUrlCollection = db.getCollection("documents");

    resetBuffers();
}