Example usage for com.mongodb WriteConcern valueOf

List of usage examples for com.mongodb WriteConcern valueOf

Introduction

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

Prototype

public static WriteConcern valueOf(final String name) 

Source Link

Document

Gets the WriteConcern constants by name (matching is done case insensitively).

Usage

From source file:org.apache.camel.component.gridfs.GridFsEndpoint.java

License:Apache License

/**
 * Set the {@link WriteConcern} for write operations on MongoDB using the standard ones.
 * Resolved from the fields of the WriteConcern class by calling the {@link WriteConcern#valueOf(String)} method.
 * /*from w  w w  .  jav a 2 s  .c o  m*/
 * @param writeConcern the standard name of the WriteConcern
 * @see <a href="http://api.mongodb.org/java/current/com/mongodb/WriteConcern.html#valueOf(java.lang.String)">possible options</a>
 */
public void setWriteConcern(String writeConcern) {
    this.writeConcern = WriteConcern.valueOf(writeConcern);
}

From source file:org.apache.camel.component.mongodb.MongoDbProducer.java

License:Apache License

private WriteConcern extractWriteConcern(Exchange exchange) throws CamelMongoDbException {
    Object o = exchange.getIn().getHeader(MongoDbConstants.WRITECONCERN);

    if (o == null) {
        return null;
    } else if (o instanceof WriteConcern) {
        return ObjectHelper.cast(WriteConcern.class, o);
    } else if (o instanceof String) {
        WriteConcern answer = WriteConcern.valueOf(ObjectHelper.cast(String.class, o));
        if (answer == null) {
            throw new CamelMongoDbException("WriteConcern specified in the " + MongoDbConstants.WRITECONCERN
                    + " header, with value " + o + " could not be resolved to a WriteConcern type");
        }//from  w w w  .j a  v  a  2 s  .co m
    }

    // should never get here
    LOG.warn("A problem occurred while resolving the Exchange's Write Concern");
    return null;
}

From source file:org.apache.gora.mongodb.store.MongoStore.java

License:Apache License

/**
 * Retrieve a client connected to the MongoDB server to be used.
 *
 * @param servers/* ww w  .ja  v  a 2  s.  co  m*/
 *          This value should specify the host:port (at least one) for
 *          connecting to remote MongoDB. Multiple values must be separated by
 *          coma.
 * @return a {@link Mongo} instance connected to the server
 * @throws UnknownHostException
 */
private MongoClient getClient(MongoStoreParameters params) throws UnknownHostException {
    // Configure options
    MongoClientOptions.Builder optBuilder = new MongoClientOptions.Builder()
            .dbEncoderFactory(GoraDBEncoder.FACTORY); // Utf8 serialization!
    if (params.getReadPreference() != null) {
        optBuilder.readPreference(ReadPreference.valueOf(params.getReadPreference()));
    }
    if (params.getWriteConcern() != null) {
        optBuilder.writeConcern(WriteConcern.valueOf(params.getWriteConcern()));
    }
    // If configuration contains a login + secret, try to authenticated with DB
    List<MongoCredential> credentials = null;
    if (params.getLogin() != null && params.getSecret() != null) {
        credentials = new ArrayList<MongoCredential>();
        credentials.add(MongoCredential.createCredential(params.getLogin(), params.getDbname(),
                params.getSecret().toCharArray()));
    }
    // Build server address
    List<ServerAddress> addrs = new ArrayList<ServerAddress>();
    Iterable<String> serversArray = Splitter.on(",").split(params.getServers());
    if (serversArray != null) {
        for (String server : serversArray) {
            Iterator<String> paramsIterator = Splitter.on(":").trimResults().split(server).iterator();
            if (!paramsIterator.hasNext()) {
                // No server, use default
                addrs.add(new ServerAddress());
            } else {
                String host = paramsIterator.next();
                if (paramsIterator.hasNext()) {
                    String port = paramsIterator.next();
                    addrs.add(new ServerAddress(host, Integer.parseInt(port)));
                } else {
                    addrs.add(new ServerAddress(host));
                }
            }
        }
    }
    // Connect to the Mongo server
    return new MongoClient(addrs, credentials, optBuilder.build());
}

From source file:org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore.java

License:Apache License

@Override
public void setReadWriteMode(String readWriteMode) {
    if (readWriteMode == null || readWriteMode.equals(lastReadWriteMode)) {
        return;/*from  w  w w . jav  a2s  . co  m*/
    }
    lastReadWriteMode = readWriteMode;
    try {
        Map<String, String> map = Splitter.on(", ").withKeyValueSeparator(":").split(readWriteMode);
        String read = map.get("read");
        if (read != null) {
            ReadPreference readPref = ReadPreference.valueOf(read);
            if (!readPref.equals(this.readPreference)) {
                this.readPreference = readPref;
            }
        }
        String write = map.get("write");
        if (write != null) {
            WriteConcern writeConcern = WriteConcern.valueOf(write);
            if (!writeConcern.equals(this.writeConcern)) {
                this.writeConcern = writeConcern;
            }
        }
    } catch (Exception e) {
        // unsupported or parse error - ignore
    }
}

From source file:org.apache.logging.log4j.nosql.appender.mongodb.MongoDbProvider.java

License:Apache License

private static WriteConcern toWriteConcern(final String writeConcernConstant,
        final String writeConcernConstantClassName) {
    WriteConcern writeConcern;/* w w w . j a va 2 s  . c  om*/
    if (Strings.isNotEmpty(writeConcernConstant)) {
        if (Strings.isNotEmpty(writeConcernConstantClassName)) {
            try {
                final Class<?> writeConcernConstantClass = Loader.loadClass(writeConcernConstantClassName);
                final Field field = writeConcernConstantClass.getField(writeConcernConstant);
                writeConcern = (WriteConcern) field.get(null);
            } catch (final Exception e) {
                LOGGER.error("Write concern constant [{}.{}] not found, using default.",
                        writeConcernConstantClassName, writeConcernConstant);
                writeConcern = DEFAULT_WRITE_CONCERN;
            }
        } else {
            writeConcern = WriteConcern.valueOf(writeConcernConstant);
            if (writeConcern == null) {
                LOGGER.warn("Write concern constant [{}] not found, using default.", writeConcernConstant);
                writeConcern = DEFAULT_WRITE_CONCERN;
            }
        }
    } else {
        writeConcern = DEFAULT_WRITE_CONCERN;
    }
    return writeConcern;
}

From source file:org.atlasapi.AtlasModule.java

License:Apache License

public @Bean Mongo mongo() {
    Mongo mongo = new Mongo(mongoHosts());
    mongo.setReadPreference(readPreference());
    if (isProcessing() && processingWriteConcern != null
            && !Strings.isNullOrEmpty(processingWriteConcern.get())) {

        WriteConcern writeConcern = WriteConcern.valueOf(processingWriteConcern.get());
        if (writeConcern == null) {
            throw new IllegalArgumentException(
                    "Could not parse write concern: " + processingWriteConcern.get());
        }//from w ww.j a  v a2  s .  c  o  m
        mongo.setWriteConcern(writeConcern);
    }
    return mongo;
}

From source file:org.craftercms.commons.mongo.MongoClientOptionsFactory.java

License:Open Source License

@Override
protected MongoClientOptions createInstance() throws Exception {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.alwaysUseMBeans(this.alwaysUseMBeans);
    builder.connectionsPerHost(this.connectionsPerHost);
    builder.cursorFinalizerEnabled(this.cursorFinalizerEnabled);
    builder.connectTimeout(this.connectTimeout);
    builder.maxWaitTime(this.maxWaitTime);

    switch (this.readPreference) {
    case PRIMARY_READ_PREFERENCE:
        builder.readPreference(ReadPreference.primary());
        break;/*from   w  w  w . j ava  2s .c o m*/
    case NEAREST_READ_PREFERENCE:
        builder.readPreference(ReadPreference.nearest());
        break;
    case SECONDARY_READ_PREFERENCE:
        builder.readPreference(ReadPreference.secondary());
        break;
    default:
        builder.readPreference(ReadPreference.primary());
        break;
    }
    builder.writeConcern(WriteConcern.valueOf(this.writeConcern));
    builder.threadsAllowedToBlockForConnectionMultiplier(this.threadsAllowedToBlockForConnectionMultiplier);
    return builder.build();

}

From source file:org.craftercms.studio.impl.repository.mongodb.data.ClientOptionsFactory.java

License:Open Source License

public void init() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.alwaysUseMBeans(this.alwaysUseMBeans);
    builder.autoConnectRetry(this.autoConnectRetry);
    builder.connectionsPerHost(this.connectionsPerHost);
    builder.cursorFinalizerEnabled(this.cursorFinalizerEnabled);
    builder.connectTimeout(this.connectTimeout);
    builder.maxAutoConnectRetryTime(this.maxAutoConnectRetryTime);
    builder.maxWaitTime(this.maxWaitTime);

    switch (this.readPreference) {
    case PRIMARY_READ_PREFERENCE:
        builder.readPreference(ReadPreference.primary());
        break;/*w w  w.ja  v a  2 s  .  c om*/
    case NEAREST_READ_PREFERENCE:
        builder.readPreference(ReadPreference.nearest());
        break;
    case SECONDARY_READ_PREFERENCE:
        builder.readPreference(ReadPreference.secondary());
        break;
    default:
        builder.readPreference(ReadPreference.primary());
        break;
    }
    builder.socketKeepAlive(this.socketKeepAlive);
    builder.writeConcern(WriteConcern.valueOf(this.writeConcern));
    builder.threadsAllowedToBlockForConnectionMultiplier(this.threadsAllowedToBlockForConnectionMultiplier);
    this.clientOptions = builder.build();
}

From source file:org.iternine.jeppetto.dao.mongodb.MongoDBQueryModelDAO.java

License:Apache License

@SuppressWarnings({ "unchecked" })
protected MongoDBQueryModelDAO(Class<T> entityClass, Map<String, Object> daoProperties,
        AccessControlContextProvider accessControlContextProvider) {
    this.dbCollection = ((DB) daoProperties.get("db")).getCollection(entityClass.getSimpleName());
    this.enhancer = EnhancerHelper.getDirtyableDBObjectEnhancer(entityClass);

    dbCollection.setObjectClass(enhancer.getEnhancedClass());

    DBCallback.FACTORY = new DBCallback.Factory() {
        @Override/*w w  w.  ja  v a 2s.  c  om*/
        public DBCallback create(DBCollection dbCollection) {
            return new MongoDBCallback(dbCollection);
        }
    };

    this.accessControlContextProvider = accessControlContextProvider;
    this.uniqueIndexes = ensureIndexes((List<String>) daoProperties.get("uniqueIndexes"), true);
    ensureIndexes((List<String>) daoProperties.get("nonUniqueIndexes"), false);
    this.optimisticLockEnabled = Boolean.parseBoolean((String) daoProperties.get("optimisticLockEnabled"));
    this.shardKeys = extractShardKeys((String) daoProperties.get("shardKeyPattern"));
    this.saveNulls = Boolean.parseBoolean((String) daoProperties.get("saveNulls"));

    if (daoProperties.containsKey("writeConcern")) {
        this.defaultWriteConcern = WriteConcern.valueOf((String) daoProperties.get("writeConcern"));
    } else {
        this.defaultWriteConcern = WriteConcern.SAFE;
    }

    if (Boolean.parseBoolean((String) daoProperties.get("showQueries"))) {
        queryLogger = LoggerFactory.getLogger(getClass());
    }
}

From source file:org.jmingo.mongo.MongoDBFactory.java

License:Apache License

private Mongo create(MongoConfig config) {
    Mongo mongo;//from   w ww.  j a  va 2s .  co m
    try {
        MongoClientOptions options = createOptions(config);
        mongo = new MongoClient(new ServerAddress(config.getDatabaseHost(), config.getDatabasePort()), options);
        WriteConcern writeConcern = WriteConcern.valueOf(config.getWriteConcern());
        mongo.setWriteConcern(writeConcern);
        LOGGER.debug("set '{}' write concern", writeConcern);
    } catch (UnknownHostException e) {
        throw new MongoConfigurationException(e);
    }
    return mongo;
}