List of usage examples for com.mongodb WriteConcern getW
public int getW()
From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java
License:Apache License
/** * Utility method to configure Mongo connection options * * @param optsBuilder/*from w ww . j a v a2 s . 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.torodb.mongowp.mongoserver.api.toro.ToroLastError.java
License:Open Source License
private void getLastInsertError(WriteConcern writeConcern, LastErrorResult lastErrorResult) throws InterruptedException, ExecutionException { if (futureOperationResponse == null && futureCommitResponse == null) { return;/*from w w w . j av a 2s .c o m*/ } if (writeConcern.getW() > 0) { try { if (futureOperationResponse != null) { if (futureOperationResponse.isDone() || futureOperationResponse.isCancelled()) { InsertResponse insertResponse = (InsertResponse) futureOperationResponse.get(); lastErrorResult.error = !insertResponse.isSuccess(); if (lastErrorResult.error) { lastErrorResult.errorCode = MongoWP.ErrorCode.INTERNAL_ERROR; } else { lastErrorResult.n = insertResponse.getInsertedSize(); } } futureOperationResponse.get(); } } catch (InterruptedException exception) { LOGGER.debug("Exception while last error was calculated", exception); lastErrorResult.error = true; } catch (ExecutionException exception) { LOGGER.debug("Exception while last error was calculated", exception); lastErrorResult.error = true; } } }
From source file:com.torodb.mongowp.mongoserver.api.toro.ToroLastError.java
License:Open Source License
private void getLastUpdateError(WriteConcern writeConcern, LastErrorResult lastErrorResult) throws InterruptedException, ExecutionException { if (futureOperationResponse == null || futureCommitResponse == null) { return;// w w w .j a v a 2 s. c o m } if (writeConcern.getW() > 0) { try { futureOperationResponse.get(); futureCommitResponse.get(); } catch (Exception exception) { lastErrorResult.error = true; } } if (futureOperationResponse.isDone() || futureOperationResponse.isCancelled()) { UpdateResponse updateResponse = (UpdateResponse) futureOperationResponse.get(); lastErrorResult.error = !updateResponse.getErrors().isEmpty(); if (lastErrorResult.error) { lastErrorResult.errorCode = MongoWP.ErrorCode.INTERNAL_ERROR; } else { lastErrorResult.n = updateResponse.getModified(); int modifiedCount = updateResponse.getModified() - updateResponse.getInsertedDocuments().size(); lastErrorResult.updatedExisting = modifiedCount > 0; lastErrorResult.upserted = updateResponse.getInsertedDocuments().size(); } } }
From source file:com.torodb.mongowp.mongoserver.api.toro.ToroLastError.java
License:Open Source License
private void getLastDeleteError(WriteConcern writeConcern, LastErrorResult lastErrorResult) throws InterruptedException, ExecutionException { if (futureOperationResponse == null || futureCommitResponse == null) { return;/*from w w w .ja v a2 s . com*/ } if (writeConcern.getW() > 0) { try { futureOperationResponse.get(); futureCommitResponse.get(); } catch (Exception exception) { lastErrorResult.error = true; } } if (futureOperationResponse.isDone() || futureOperationResponse.isCancelled()) { DeleteResponse deleteResponse = (DeleteResponse) futureOperationResponse.get(); lastErrorResult.error = !deleteResponse.isSuccess(); if (lastErrorResult.error) { lastErrorResult.errorCode = MongoWP.ErrorCode.INTERNAL_ERROR; } else { lastErrorResult.n = deleteResponse.getDeleted(); } } }
From source file:com.torodb.mongowp.mongoserver.api.toro.ToroQueryCommandProcessor.java
License:Open Source License
@Override public com.eightkdata.mongowp.mongoserver.api.pojos.InsertResponse insert(BSONDocument document, AttributeMap attributeMap) throws Exception { ToroConnection connection = attributeMap.attr(ToroRequestProcessor.CONNECTION).get(); String collection = (String) document.getValue("insert"); WriteFailMode writeFailMode = getWriteFailMode(document); WriteConcern writeConcern = getWriteConcern(document); Iterable<?> documents = (Iterable<?>) document.getValue("documents"); List<ToroDocument> inserts = new ArrayList<ToroDocument>(); Iterator<?> documentsIterator = documents.iterator(); while (documentsIterator.hasNext()) { BSONObject object = (BSONObject) documentsIterator.next(); inserts.add(new BSONToroDocument(object)); }//from ww w. j a va 2 s. c o m ToroTransaction transaction = connection.createTransaction(); ToroInsertResponse.Builder responseBuilder = new ToroInsertResponse.Builder(); try { Future<InsertResponse> futureInsertResponse = transaction.insertDocuments(collection, inserts, writeFailMode); Future<?> futureCommitResponse = transaction.commit(); if (writeConcern.getW() > 0) { InsertResponse insertResponse = futureInsertResponse.get(); futureCommitResponse.get(); responseBuilder.setN(insertResponse.getInsertedSize()); } LastError lastError = new ToroLastError(RequestOpCode.OP_QUERY, QueryAndWriteOperationsQueryCommand.delete, futureInsertResponse, futureCommitResponse, false, null); attributeMap.attr(ToroRequestProcessor.LAST_ERROR).set(lastError); responseBuilder.setOk(true); return responseBuilder.build(); } finally { transaction.close(); } }
From source file:com.torodb.mongowp.mongoserver.api.toro.ToroQueryCommandProcessor.java
License:Open Source License
@Override public void update(BSONDocument document, MessageReplier messageReplier) throws Exception { AttributeMap attributeMap = messageReplier.getAttributeMap(); ToroConnection connection = attributeMap.attr(ToroRequestProcessor.CONNECTION).get(); Map<String, Object> keyValues = new HashMap<String, Object>(); String collection = (String) document.getValue("update"); WriteFailMode writeFailMode = getWriteFailMode(document); WriteConcern writeConcern = getWriteConcern(document); Iterable<?> documents = (Iterable<?>) document.getValue("updates"); List<UpdateOperation> updates = new ArrayList<UpdateOperation>(); Iterator<?> documentsIterator = documents.iterator(); while (documentsIterator.hasNext()) { BSONObject object = (BSONObject) documentsIterator.next(); QueryCriteria queryCriteria = queryCriteriaTranslator.translate((BSONObject) object.get("q")); UpdateAction updateAction = UpdateActionTranslator.translate((BSONObject) object.get("u")); boolean upsert = getBoolean(object, "upsert", false); boolean onlyOne = !getBoolean(object, "multi", false); updates.add(new UpdateOperation(queryCriteria, updateAction, upsert, onlyOne)); }//from w w w.ja va 2s .c om ToroTransaction transaction = connection.createTransaction(); try { Future<UpdateResponse> futureUpdateResponse = transaction.update(collection, updates, writeFailMode); Future<?> futureCommitResponse = transaction.commit(); if (writeConcern.getW() > 0) { UpdateResponse updateResponse = futureUpdateResponse.get(); futureCommitResponse.get(); keyValues.put("n", updateResponse.getModified()); } LastError lastError = new ToroLastError(RequestOpCode.OP_QUERY, QueryAndWriteOperationsQueryCommand.update, futureUpdateResponse, futureCommitResponse, false, null); attributeMap.attr(ToroRequestProcessor.LAST_ERROR).set(lastError); } finally { transaction.close(); } keyValues.put("ok", MongoWP.OK); BSONDocument reply = new MongoBSONDocument(keyValues); messageReplier.replyMessageNoCursor(reply); }
From source file:com.torodb.mongowp.mongoserver.api.toro.ToroQueryCommandProcessor.java
License:Open Source License
@Override public void delete(BSONDocument document, MessageReplier messageReplier) throws Exception { AttributeMap attributeMap = messageReplier.getAttributeMap(); ToroConnection connection = attributeMap.attr(ToroRequestProcessor.CONNECTION).get(); Map<String, Object> keyValues = new HashMap<String, Object>(); String collection = (String) document.getValue("delete"); WriteFailMode writeFailMode = getWriteFailMode(document); WriteConcern writeConcern = getWriteConcern(document); Iterable<?> documents = (Iterable<?>) document.getValue("deletes"); List<DeleteOperation> deletes = new ArrayList<DeleteOperation>(); Iterator<?> documentsIterator = documents.iterator(); while (documentsIterator.hasNext()) { BSONObject object = (BSONObject) documentsIterator.next(); QueryCriteria queryCriteria = queryCriteriaTranslator.translate((BSONObject) object.get("q")); boolean singleRemove = getBoolean(object, "limit", false); deletes.add(new DeleteOperation(queryCriteria, singleRemove)); }//from w ww .jav a 2 s .c om ToroTransaction transaction = connection.createTransaction(); try { Future<DeleteResponse> futureDeleteResponse = transaction.delete(collection, deletes, writeFailMode); Future<?> futureCommitResponse = transaction.commit(); if (writeConcern.getW() > 0) { DeleteResponse deleteResponse = futureDeleteResponse.get(); futureCommitResponse.get(); keyValues.put("n", deleteResponse.getDeleted()); } LastError lastError = new ToroLastError(RequestOpCode.OP_QUERY, QueryAndWriteOperationsQueryCommand.delete, futureDeleteResponse, futureCommitResponse, false, null); attributeMap.attr(ToroRequestProcessor.LAST_ERROR).set(lastError); } finally { transaction.close(); } keyValues.put("ok", MongoWP.OK); BSONDocument reply = new MongoBSONDocument(keyValues); messageReplier.replyMessageNoCursor(reply); }
From source file:com.torodb.torod.mongodb.unsafe.ToroQueryCommandProcessor.java
License:Open Source License
@Override public void update(BsonDocument document, MessageReplier messageReplier) throws Exception { ToroConnection connection = getConnection(messageReplier.getAttributeMap()); BsonDocument result = new BsonDocument(); String collection = document.get("update").asString().getValue(); WriteFailMode writeFailMode = getWriteFailMode(document); WriteConcern writeConcern = getWriteConcern(document); Iterable<BsonValue> documents = document.get("updates").asArray(); List<UpdateOperation> updates = Lists.newArrayListWithCapacity(document.size()); Iterator<BsonValue> documentsIterator = documents.iterator(); while (documentsIterator.hasNext()) { BsonDocument object = documentsIterator.next().asDocument(); QueryCriteria queryCriteria = queryCriteriaTranslator.translate(object.get("q").asDocument()); UpdateAction updateAction = UpdateActionTranslator.translate(object.get("u").asDocument()); boolean upsert = BsonReaderTool.getBoolean(object, "upsert", false); boolean onlyOne = !BsonReaderTool.getBoolean(object, "multi", false); updates.add(new UpdateOperation(queryCriteria, updateAction, upsert, onlyOne)); }/* ww w . jav a2 s. c om*/ ToroTransaction transaction = connection.createTransaction(); try { Future<UpdateResponse> futureUpdateResponse = transaction.update(collection, updates, writeFailMode); Future<?> futureCommitResponse = transaction.commit(); if (writeConcern.getW() > 0) { UpdateResponse updateResponse = futureUpdateResponse.get(); futureCommitResponse.get(); result.put("n", new BsonInt64(updateResponse.getModified())); } LOGGER.warn("The current implementation of update command is not registered on GetLastError"); result.put("warn", new BsonString( "The current implementation of update command is not registered on GetLastError")); } finally { transaction.close(); } result.put("ok", MongoWP.BSON_OK); messageReplier.replyMessageNoCursor(result); }