Example usage for com.mongodb WriteConcern WriteConcern

List of usage examples for com.mongodb WriteConcern WriteConcern

Introduction

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

Prototype

@Deprecated
public WriteConcern() 

Source Link

Document

Constructs an instance with all properties initialized to their default values, except for w, which is initialized to 0, making instances constructed this ways equivalent to WriteConcern#UNACKNOWLEDGED

Usage

From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Apache License

/**
 * Utility method to configure Mongo connection options
 *
 * @param optsBuilder/*  w w w. j  av a2s  . c  om*/
 *          an options builder
 * @param connTimeout
 *          the connection timeout to use (can be null)
 * @param socketTimeout
 *          the socket timeout to use (can be null)
 * @param readPreference
 *          the read preference to use (can be null)
 * @param writeConcern
 *          the writeConcern to use (can be null)
 * @param wTimeout
 *          the w timeout to use (can be null)
 * @param journaled
 *          whether to use journaled writes
 * @param tagSet
 *          the tag set to use in conjunction with the read preference (can be null)
 * @param vars
 *          variables to use
 * @param log
 *          for logging
 * @throws KettleException
 *           if a problem occurs
 */
private void configureConnectionOptions(MongoClientOptions.Builder optsBuilder, String connTimeout,
        String socketTimeout, String readPreference, String writeConcern, String wTimeout, boolean journaled,
        List<String> tagSet, VariableSpace vars, LogChannelInterface log) throws KettleException {

    // connection timeout
    if (!Const.isEmpty(connTimeout)) {
        String connS = vars.environmentSubstitute(connTimeout);
        try {
            int cTimeout = Integer.parseInt(connS);
            if (cTimeout > 0) {
                optsBuilder.connectTimeout(cTimeout);
            }
        } catch (NumberFormatException n) {
            throw new KettleException(n);
        }
    }

    // socket timeout
    if (!Const.isEmpty(socketTimeout)) {
        String sockS = vars.environmentSubstitute(socketTimeout);
        try {
            int sockTimeout = Integer.parseInt(sockS);
            if (sockTimeout > 0) {
                optsBuilder.socketTimeout(sockTimeout);
            }
        } catch (NumberFormatException n) {
            throw new KettleException(n);
        }
    }

    if (log != null) {
        String rpLogSetting = NamedReadPreference.PRIMARY.getName();

        if (!Const.isEmpty(readPreference)) {
            rpLogSetting = readPreference;
        }
        log.logBasic(
                BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.UsingReadPreference", rpLogSetting)); //$NON-NLS-1$
    }
    DBObject firstTagSet = null;
    DBObject[] remainingTagSets = new DBObject[0];
    if (tagSet != null && tagSet.size() > 0) {
        if (tagSet.size() > 1) {
            remainingTagSets = new DBObject[tagSet.size() - 1];
        }

        firstTagSet = (DBObject) JSON.parse(tagSet.get(0).trim());
        for (int i = 1; i < tagSet.size(); i++) {
            remainingTagSets[i - 1] = (DBObject) JSON.parse(tagSet.get(i).trim());
        }
        if (log != null && (!Const.isEmpty(readPreference)
                && !readPreference.equalsIgnoreCase(NamedReadPreference.PRIMARY.getName()))) {
            StringBuilder builder = new StringBuilder();
            for (String s : tagSet) {
                builder.append(s).append(" "); //$NON-NLS-1$
            }
            log.logBasic(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.UsingReadPreferenceTagSets", //$NON-NLS-1$
                    builder.toString()));
        }
    } else {
        if (log != null) {
            log.logBasic(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.NoReadPreferenceTagSetsDefined")); //$NON-NLS-1$
        }
    }

    // read preference
    if (!Const.isEmpty(readPreference)) {

        String rp = vars.environmentSubstitute(readPreference);

        NamedReadPreference preference = NamedReadPreference.byName(rp);

        if ((firstTagSet != null) && (preference.getPreference() instanceof TaggableReadPreference)) {
            optsBuilder.readPreference(preference.getTaggableReadPreference(firstTagSet, remainingTagSets));
        } else {
            optsBuilder.readPreference(preference.getPreference());
        }

    }

    // write concern
    writeConcern = vars.environmentSubstitute(writeConcern);
    wTimeout = vars.environmentSubstitute(wTimeout);

    WriteConcern concern = null;

    if (Const.isEmpty(writeConcern) && Const.isEmpty(wTimeout) && !journaled) {
        // all defaults - timeout 0, journal = false, w = 1
        concern = new WriteConcern();
        concern.setWObject(new Integer(1));

        if (log != null) {
            log.logBasic(BaseMessages.getString(PKG,
                    "MongoNoAuthWrapper.Message.ConfiguringWithDefaultWriteConcern")); //$NON-NLS-1$
        }
    } else {
        int wt = 0;
        if (!Const.isEmpty(wTimeout)) {
            try {
                wt = Integer.parseInt(wTimeout);
            } catch (NumberFormatException n) {
                throw new KettleException(n);
            }
        }

        if (!Const.isEmpty(writeConcern)) {
            // try parsing as a number first
            try {
                int wc = Integer.parseInt(writeConcern);
                concern = new WriteConcern(wc, wt, false, journaled);
            } catch (NumberFormatException n) {
                // assume its a valid string - e.g. "majority" or a custom
                // getLastError label associated with a tag set
                concern = new WriteConcern(writeConcern, wt, false, journaled);
            }
        } else {
            concern = new WriteConcern(1, wt, false, journaled);
        }

        if (log != null) {
            String lwc = "w = " + concern.getW() + ", wTimeout = " + concern.getWtimeout() + ", journaled = "
                    + concern.getJ();
            log.logBasic(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.ConfiguringWithWriteConcern", lwc));
        }
    }
    optsBuilder.writeConcern(concern);
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java

License:Apache License

public CompletableFuture<Tuple2<Supplier<List<Object>>, Supplier<Long>>> storeObjects(final List<O> new_objects,
        final boolean replace_if_present) {
    if (replace_if_present) {
        // This is an "illegal arg exception" so throw immediately
        throw new RuntimeException(ErrorUtils.BULK_REPLACE_DUPLICATES_NOT_SUPPORTED);
    }/* w  w  w  . j a  v  a  2s.c om*/
    try {
        final List<DBObject> l = new_objects.stream().map(o -> convertToBson(o)).collect(Collectors.toList());

        final com.mongodb.WriteResult orig_result = _state.orig_coll.insert(l,
                Patterns.match(_state.orig_coll).<InsertOptions>andReturn().when(FongoDBCollection.class,
                        () -> new InsertOptions().continueOnError(true).writeConcern(new WriteConcern()))
                        .otherwise(() -> new InsertOptions().continueOnError(true)));

        return CompletableFuture.completedFuture(
                Tuples._2T(() -> l.stream().map(o -> (Object) _state.coll.convertFromDbId(o.get(_ID)))
                        .collect(Collectors.toList()), () -> {
                            return Patterns.match(_state.orig_coll).<Long>andReturn()
                                    .when(FongoDBCollection.class, () -> (Long) (long) orig_result.getN())
                                    .otherwise(__ -> (long) l.size());
                        }));
    } catch (Exception e) {
        return FutureUtils.<Tuple2<Supplier<List<Object>>, Supplier<Long>>>returnError(e);
    }
}

From source file:joliex.mongodb.MongoDbConnector.java

@RequestResponse
public Value insert(Value request) throws FaultException {
    try {// w w w . jav a2  s . c  o m
        Value v = Value.create();
        String collectionName = request.getFirstChild("collection").strValue();
        BsonDocument bsonDocument = createDocument(request.getFirstChild("document"));
        printlnJson("insert document", bsonDocument);

        if (request.hasChildren("writeConcern")) {
            WriteConcern writeConcern = new WriteConcern();
            if (request.getFirstChild("writeConcern").hasChildren("journal")) {
                writeConcern.withJournal(
                        request.getFirstChild("writeConcern").getFirstChild("journal").boolValue());
            }
            if (request.getFirstChild("writeConcern").hasChildren("w")) {
                if (request.getFirstChild("writeConcern").getFirstChild("w").isInt()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").intValue());
                }
                if (request.getFirstChild("writeConcern").getFirstChild("w").isString()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").strValue());
                }
            }
            if (request.getFirstChild("writeConcern").hasChildren("timeout")) {
                writeConcern.withWTimeout(
                        request.getFirstChild("writeConcern").getFirstChild("timeout").longValue(),
                        TimeUnit.MILLISECONDS);
            }

            db.getCollection(collectionName, BsonDocument.class).withWriteConcern(writeConcern);
        }
        if (request.hasChildren("options")) {
            InsertOneOptions insertOneOptions = new InsertOneOptions();
            insertOneOptions.bypassDocumentValidation(
                    request.getFirstChild("options").getFirstChild("bypassDocumentValidation").boolValue());
            db.getCollection(collectionName, BsonDocument.class).insertOne(bsonDocument, insertOneOptions);
        } else {
            db.getCollection(collectionName, BsonDocument.class).insertOne(bsonDocument);

        }

        bsonDocument.get("_id").asObjectId().getValue().toByteArray();

        String str = new String(bsonDocument.get("_id").asObjectId().getValue().toHexString());
        Value objValue = Value.create(str);
        v.getNewChild("_id").assignValue(objValue);
        v.getFirstChild("_id").getNewChild("@type").assignValue(Value.create("ObjectId"));

        return v;
    } catch (MongoException ex) {
        throw new FaultException("MongoException", ex);
    }

}

From source file:joliex.mongodb.MongoDbConnector.java

@RequestResponse
public Value insertMany(Value request) throws FaultException {
    Value v = Value.create();//from  w  w  w  .ja va  2s. c  o m
    String collectionName = request.getFirstChild("collection").strValue();
    List<BsonDocument> documents = new ArrayList();
    BsonDocument bsonDocument;
    try {

        for (int counterDocuments = 0; counterDocuments < request.getChildren("document")
                .size(); counterDocuments++) {
            bsonDocument = createDocument(request.getChildren("document").get(counterDocuments));
            documents.add(bsonDocument);
        }
        if (request.hasChildren("writeConcern")) {
            WriteConcern writeConcern = new WriteConcern();
            if (request.getFirstChild("writeConcern").hasChildren("journal")) {
                writeConcern.withJournal(
                        request.getFirstChild("writeConcern").getFirstChild("journal").boolValue());
            }
            if (request.getFirstChild("writeConcern").hasChildren("w")) {
                if (request.getFirstChild("writeConcern").getFirstChild("w").isInt()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").intValue());
                }
                if (request.getFirstChild("writeConcern").getFirstChild("w").isString()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").strValue());
                }
            }
            if (request.getFirstChild("writeConcern").hasChildren("timeout")) {
                writeConcern.withWTimeout(
                        request.getFirstChild("writeConcern").getFirstChild("timeout").longValue(),
                        TimeUnit.MILLISECONDS);
            }

            db.getCollection(collectionName, BsonDocument.class).withWriteConcern(writeConcern);
        }
        if (request.hasChildren("options")) {
            InsertManyOptions insertManyOptions = new InsertManyOptions();
            insertManyOptions.ordered(request.getFirstChild("options").getFirstChild("ordered").boolValue());
            insertManyOptions.ordered(request.getFirstChild("options").getFirstChild("ordered").boolValue());
            insertManyOptions.bypassDocumentValidation(
                    request.getFirstChild("options").getFirstChild("bypassDocumentValidation").boolValue());
            db.getCollection(collectionName, BsonDocument.class).insertMany(documents, insertManyOptions);
        } else {
            db.getCollection(collectionName, BsonDocument.class).insertMany(documents);

        }
        ;
        db.getCollection(collectionName, BsonDocument.class).insertMany(documents);
        for (int counterDocuments = 0; counterDocuments < request.getChildren("document")
                .size(); counterDocuments++) {
            String str = new String(Hex.decodeHex(documents.get(counterDocuments).get("_id").asObjectId()
                    .getValue().toHexString().toCharArray()), StandardCharsets.UTF_8);
            Value result = Value.create();
            result.getNewChild("_id").assignValue(Value.create(str));
            result.getFirstChild("_id").getNewChild("@type").assignValue(Value.create("ObjectID"));
            v.getChildren("results").add(result);
        }

    } catch (MongoException ex) {
        throw new FaultException("MongoException", ex);
    } catch (DecoderException ex) {
        Logger.getLogger(MongoDbConnector.class.getName()).log(Level.SEVERE, null, ex);
    }
    return v;
}

From source file:joliex.mongodb.MongoDbConnector.java

@RequestResponse
public Value delete(Value request) throws FaultException {
    try {/*www  .j  a  va  2  s.  c o m*/
        Value v = Value.create();
        String collectionName = request.getFirstChild("collection").strValue();
        BsonDocument bsonQueryDocument = BsonDocument.parse(request.getFirstChild("filter").strValue());
        prepareBsonQueryData(bsonQueryDocument, request.getFirstChild("filter"));
        printlnJson("Delete filter", bsonQueryDocument);
        if (request.hasChildren("writeConcern")) {
            WriteConcern writeConcern = new WriteConcern();
            if (request.getFirstChild("writeConcern").hasChildren("journal")) {
                writeConcern.withJournal(
                        request.getFirstChild("writeConcern").getFirstChild("journal").boolValue());
            }
            if (request.getFirstChild("writeConcern").hasChildren("w")) {
                if (request.getFirstChild("writeConcern").getFirstChild("w").isInt()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").intValue());
                }
                if (request.getFirstChild("writeConcern").getFirstChild("w").isString()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").strValue());
                }
            }
            if (request.getFirstChild("writeConcern").hasChildren("timeout")) {
                writeConcern.withWTimeout(
                        request.getFirstChild("writeConcern").getFirstChild("timeout").longValue(),
                        TimeUnit.MILLISECONDS);
            }

            db.getCollection(collectionName, BsonDocument.class).withWriteConcern(writeConcern);
        }

        DeleteResult resultDelete = db.getCollection(collectionName, BsonDocument.class)
                .deleteOne(bsonQueryDocument);
        v.getNewChild("deleteCount").add(Value.create(resultDelete.getDeletedCount()));
        return v;
    } catch (MongoException ex) {
        throw new FaultException("MongoException", ex);
    } catch (JsonParseException ex) {
        throw new FaultException("JsonParseException", ex);
    }
}

From source file:joliex.mongodb.MongoDbConnector.java

@RequestResponse
public Value deleteMany(Value request) throws FaultException {
    try {//from w  ww  .ja v  a 2  s.co  m
        Value v = Value.create();
        String collectionName = request.getFirstChild("collection").strValue();
        BsonDocument bsonQueryDocument = BsonDocument.parse(request.getFirstChild("filter").strValue());
        prepareBsonQueryData(bsonQueryDocument, request.getFirstChild("filter"));
        printlnJson("Delete filter", bsonQueryDocument);
        if (request.hasChildren("writeConcern")) {
            WriteConcern writeConcern = new WriteConcern();
            if (request.getFirstChild("writeConcern").hasChildren("journal")) {
                writeConcern.withJournal(
                        request.getFirstChild("writeConcern").getFirstChild("journal").boolValue());
            }
            if (request.getFirstChild("writeConcern").hasChildren("w")) {
                if (request.getFirstChild("writeConcern").getFirstChild("w").isInt()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").intValue());
                }
                if (request.getFirstChild("writeConcern").getFirstChild("w").isString()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").strValue());
                }
            }
            if (request.getFirstChild("writeConcern").hasChildren("timeout")) {
                writeConcern.withWTimeout(
                        request.getFirstChild("writeConcern").getFirstChild("timeout").longValue(),
                        TimeUnit.MILLISECONDS);
            }

            db.getCollection(collectionName, BsonDocument.class).withWriteConcern(writeConcern);
        }
        DeleteResult resultDelete = db.getCollection(collectionName, BsonDocument.class)
                .deleteMany(bsonQueryDocument);

        v.getNewChild("deletedCount").add(Value.create(resultDelete.getDeletedCount()));
        return v;
    } catch (MongoException ex) {
        throw new FaultException("MongoException", ex);
    } catch (JsonParseException ex) {
        throw new FaultException("JsonParseException", ex);
    }
}

From source file:joliex.mongodb.MongoDbConnector.java

@RequestResponse

public Value updateMany(Value request) throws FaultException {
    try {/*w  ww.java 2 s  .c om*/
        String collectionName = request.getFirstChild("collection").strValue();
        Value v = Value.create();
        BsonDocument bsonQueryDocument = BsonDocument.parse(request.getFirstChild("filter").strValue());
        prepareBsonQueryData(bsonQueryDocument, request.getFirstChild("filter"));
        printlnJson("Update filter", bsonQueryDocument);
        BsonDocument bsonDocument = BsonDocument.parse(request.getFirstChild("documentUpdate").strValue());
        printlnJson("Update documentUpdate", bsonDocument);
        prepareBsonQueryData(bsonDocument, request.getFirstChild("documentUpdate"));
        printlnJson("Update documentUpdate", bsonDocument);
        if (request.hasChildren("writeConcern")) {
            WriteConcern writeConcern = new WriteConcern();
            if (request.getFirstChild("writeConcern").hasChildren("journal")) {
                writeConcern.withJournal(
                        request.getFirstChild("writeConcern").getFirstChild("journal").boolValue());
            }
            if (request.getFirstChild("writeConcern").hasChildren("w")) {
                if (request.getFirstChild("writeConcern").getFirstChild("w").isInt()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").intValue());
                }
                if (request.getFirstChild("writeConcern").getFirstChild("w").isString()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").strValue());
                }
            }
            if (request.getFirstChild("writeConcern").hasChildren("timeout")) {
                writeConcern.withWTimeout(
                        request.getFirstChild("writeConcern").getFirstChild("timeout").longValue(),
                        TimeUnit.MILLISECONDS);
            }

            db.getCollection(collectionName, BsonDocument.class).withWriteConcern(writeConcern);
        }
        if (request.hasChildren("options")) {
            UpdateOptions updateOptions = new UpdateOptions();
            updateOptions.upsert(request.getFirstChild("options").getFirstChild("upsert").boolValue());
            updateOptions.bypassDocumentValidation(
                    request.getFirstChild("options").getFirstChild("bypassDocumentValidation").boolValue());
            UpdateResult resultUpdate = db.getCollection(collectionName, BsonDocument.class)
                    .updateMany(bsonQueryDocument, bsonDocument, updateOptions);
            v.getNewChild("matchedCount").assignValue(Value.create(resultUpdate.getMatchedCount()));
            v.getNewChild("modifiedCount").assignValue(Value.create(resultUpdate.getModifiedCount()));

        } else {
            UpdateResult resultUpdate = db.getCollection(collectionName, BsonDocument.class)
                    .updateMany(bsonQueryDocument, bsonDocument);
            v.getNewChild("matchedCount").assignValue(Value.create(resultUpdate.getMatchedCount()));
            v.getNewChild("modifiedCount").assignValue(Value.create(resultUpdate.getModifiedCount()));
        }

        return v;

    } catch (MongoException ex) {
        throw new FaultException("MongoException", ex);
    } catch (JsonParseException ex) {
        throw new FaultException("JsonParseException", ex);
    }

}

From source file:joliex.mongodb.MongoDbConnector.java

@RequestResponse
public Value update(Value request) throws FaultException {
    try {/*from   w ww. j  a  v a 2  s.  c om*/
        Value v = Value.create();
        String collectionName = request.getFirstChild("collection").strValue();
        BsonDocument bsonQueryDocument = BsonDocument.parse(request.getFirstChild("filter").strValue());
        prepareBsonQueryData(bsonQueryDocument, request.getFirstChild("filter"));
        printlnJson("Update filter", bsonQueryDocument);
        BsonDocument bsonDocument = BsonDocument.parse(request.getFirstChild("documentUpdate").strValue());
        printlnJson("Update documentUpdate", bsonDocument);
        prepareBsonQueryData(bsonDocument, request.getFirstChild("documentUpdate"));
        printlnJson("Update documentUpdate", bsonDocument);
        showLog();

        if (request.hasChildren("writeConcern")) {
            WriteConcern writeConcern = new WriteConcern();
            if (request.getFirstChild("writeConcern").hasChildren("journal")) {
                writeConcern.withJournal(
                        request.getFirstChild("writeConcern").getFirstChild("journal").boolValue());
            }
            if (request.getFirstChild("writeConcern").hasChildren("w")) {
                if (request.getFirstChild("writeConcern").getFirstChild("w").isInt()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").intValue());
                }
                if (request.getFirstChild("writeConcern").getFirstChild("w").isString()) {
                    writeConcern.withW(request.getFirstChild("writeConcern").getFirstChild("w").strValue());
                }
            }
            if (request.getFirstChild("writeConcern").hasChildren("timeout")) {
                writeConcern.withWTimeout(
                        request.getFirstChild("writeConcern").getFirstChild("timeout").longValue(),
                        TimeUnit.MILLISECONDS);
            }

            db.getCollection(collectionName, BsonDocument.class).withWriteConcern(writeConcern);
        }
        if (request.hasChildren("options")) {
            UpdateOptions updateOptions = new UpdateOptions();
            updateOptions.upsert(request.getFirstChild("options").getFirstChild("upsert").boolValue());
            updateOptions.bypassDocumentValidation(
                    request.getFirstChild("options").getFirstChild("bypassDocumentValidation").boolValue());
            UpdateResult resultUpdate = db.getCollection(collectionName, BsonDocument.class)
                    .updateOne(bsonQueryDocument, bsonDocument, updateOptions);
            v.getNewChild("matchedCount").assignValue(Value.create(resultUpdate.getMatchedCount()));
            v.getNewChild("modifiedCount").assignValue(Value.create(resultUpdate.getModifiedCount()));

        } else {
            UpdateResult resultUpdate = db.getCollection(collectionName, BsonDocument.class)
                    .updateOne(bsonQueryDocument, bsonDocument);
            v.getNewChild("matchedCount").assignValue(Value.create(resultUpdate.getMatchedCount()));
            v.getNewChild("modifiedCount").assignValue(Value.create(resultUpdate.getModifiedCount()));
        }
        return v;

    } catch (MongoException ex) {
        throw new FaultException("MongoException", ex);
    }

}

From source file:org.pentaho.mongo.MongoPropToOption.java

License:Open Source License

public WriteConcern writeConcernValue(final MongoProperties props) throws MongoDbException {
    // write concern
    String writeConcern = props.get(MongoProp.writeConcern);
    String wTimeout = props.get(MongoProp.wTimeout);
    boolean journaled = Boolean.valueOf(props.get(MongoProp.JOURNALED));

    WriteConcern concern;/*from   w w  w .j a  v  a2 s  . co m*/

    if (!Util.isEmpty(writeConcern) && Util.isEmpty(wTimeout) && !journaled) {
        // all defaults - timeout 0, journal = false, w = 1
        concern = new WriteConcern();
        concern.setWObject(1);

        if (log != null) {
            log.info(getString(PKG, "MongoPropToOption.Message.ConfiguringWithDefaultWriteConcern")); //$NON-NLS-1$
        }
    } else {
        int wt = 0;
        if (!Util.isEmpty(wTimeout)) {
            try {
                wt = Integer.parseInt(wTimeout);
            } catch (NumberFormatException n) {
                throw new MongoDbException(n);
            }
        }

        if (!Util.isEmpty(writeConcern)) {
            // try parsing as a number first
            try {
                int wc = Integer.parseInt(writeConcern);
                concern = new WriteConcern(wc, wt, false, journaled);
            } catch (NumberFormatException n) {
                // assume its a valid string - e.g. "majority" or a custom
                // getLastError label associated with a tag set
                concern = new WriteConcern(writeConcern, wt, false, journaled);
            }
        } else {
            concern = new WriteConcern(1, wt, false, journaled);
        }

        if (log != null) {
            String lwc = "w = " + concern.getWString() + ", wTimeout = " + concern.getWtimeout()
                    + ", journaled = " + concern.getJ();
            log.info(getString(PKG, "MongoPropToOption.Message.ConfiguringWithWriteConcern", lwc));
        }
    }
    return concern;
}

From source file:org.pentaho.mongo.MongoUtils.java

License:Open Source License

/**
 * Utility method to configure Mongo connection options
 * /*from  www  .j  ava  2s. com*/
 * @param optsBuilder an options builder
 * @param connTimeout the connection timeout to use (can be null)
 * @param socketTimeout the socket timeout to use (can be null)
 * @param readPreference the read preference to use (can be null)
 * @param writeConcern the writeConcern to use (can be null)
 * @param wTimeout the w timeout to use (can be null)
 * @param journaled whether to use journaled writes
 * @param tagSet the tag set to use in conjunction with the read preference
 *          (can be null)
 * @param vars variables to use
 * @param log for logging
 * @throws KettleException if a problem occurs
 */
public static void configureConnectionOptions(MongoClientOptions.Builder optsBuilder, String connTimeout,
        String socketTimeout, String readPreference, String writeConcern, String wTimeout, boolean journaled,
        List<String> tagSet, VariableSpace vars, LogChannelInterface log) throws KettleException {

    // connection timeout
    if (!Const.isEmpty(connTimeout)) {
        String connS = vars.environmentSubstitute(connTimeout);
        try {
            int cTimeout = Integer.parseInt(connS);
            if (cTimeout > 0) {
                optsBuilder.connectTimeout(cTimeout);
            }
        } catch (NumberFormatException n) {
            throw new KettleException(n);
        }
    }

    // socket timeout
    if (!Const.isEmpty(socketTimeout)) {
        String sockS = vars.environmentSubstitute(socketTimeout);
        try {
            int sockTimeout = Integer.parseInt(sockS);
            if (sockTimeout > 0) {
                optsBuilder.socketTimeout(sockTimeout);
            }
        } catch (NumberFormatException n) {
            throw new KettleException(n);
        }
    }

    if (log != null) {
        String rpLogSetting = NamedReadPreference.PRIMARY.getName();

        if (!Const.isEmpty(readPreference)) {
            rpLogSetting = readPreference;
        }
        log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.UsingReadPreference", rpLogSetting)); //$NON-NLS-1$
    }
    DBObject firstTagSet = null;
    DBObject[] remainingTagSets = new DBObject[0];
    if (tagSet != null && tagSet.size() > 0) {
        if (tagSet.size() > 1) {
            remainingTagSets = new DBObject[tagSet.size() - 1];
        }

        firstTagSet = (DBObject) JSON.parse(tagSet.get(0).trim());
        for (int i = 1; i < tagSet.size(); i++) {
            remainingTagSets[i - 1] = (DBObject) JSON.parse(tagSet.get(i).trim());
        }
        if (log != null && (!Const.isEmpty(readPreference)
                && !readPreference.equalsIgnoreCase(NamedReadPreference.PRIMARY.getName()))) {
            StringBuilder builder = new StringBuilder();
            for (String s : tagSet) {
                builder.append(s).append(" "); //$NON-NLS-1$
            }
            log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.UsingReadPreferenceTagSets", //$NON-NLS-1$
                    builder.toString()));
        }
    } else {
        if (log != null) {
            log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.NoReadPreferenceTagSetsDefined")); //$NON-NLS-1$
        }
    }

    // read preference
    if (!Const.isEmpty(readPreference)) {

        String rp = vars.environmentSubstitute(readPreference);

        NamedReadPreference preference = NamedReadPreference.byName(rp);

        if ((firstTagSet != null) && (preference.getPreference() instanceof TaggableReadPreference)) {
            optsBuilder.readPreference(preference.getTaggableReadPreference(firstTagSet, remainingTagSets));
        } else {
            optsBuilder.readPreference(preference.getPreference());
        }

    }

    // write concern
    writeConcern = vars.environmentSubstitute(writeConcern);
    wTimeout = vars.environmentSubstitute(wTimeout);

    WriteConcern concern = null;

    if (Const.isEmpty(writeConcern) && Const.isEmpty(wTimeout) && !journaled) {
        // all defaults - timeout 0, journal = false, w = 1
        concern = new WriteConcern();
        concern.setWObject(new Integer(1));

        if (log != null) {
            log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.ConfiguringWithDefaultWriteConcern"));
        }
    } else {
        int wt = 0;
        if (!Const.isEmpty(wTimeout)) {
            try {
                wt = Integer.parseInt(wTimeout);
            } catch (NumberFormatException n) {
                throw new KettleException(n);
            }
        }

        if (!Const.isEmpty(writeConcern)) {
            // try parsing as a number first
            try {
                int wc = Integer.parseInt(writeConcern);
                concern = new WriteConcern(wc, wt, false, journaled);

                if (log != null) {
                    String lwc = "w = " + writeConcern + ", wTimeout = " + wt + ", journaled = "
                            + (new Boolean(journaled).toString());
                    log.logBasic(
                            BaseMessages.getString(PKG, "MongoUtils.Message.ConfiguringWithWriteConcern", lwc));
                }
            } catch (NumberFormatException n) {
                // assume its a valid string - e.g. "majority" or a custom
                // getLastError label associated with a tag set
                concern = new WriteConcern(writeConcern, wt, false, journaled);

                if (log != null) {
                    String lwc = "w = " + writeConcern + ", wTimeout = " + wt + ", journaled = "
                            + (new Boolean(journaled).toString());
                    log.logBasic(
                            BaseMessages.getString(PKG, "MongoUtils.Message.ConfiguringWithWriteConcern", lwc));
                }
            }
        } else {
            concern = new WriteConcern(1, wt, false, journaled);

            if (log != null) {
                String lwc = "w = 1" + ", wTimeout = " + wt + ", journaled = "
                        + (new Boolean(journaled).toString());
                log.logBasic(
                        BaseMessages.getString(PKG, "MongoUtils.Message.ConfiguringWithWriteConcern", lwc));
            }
        }
    }
    optsBuilder.writeConcern(concern);
}