protected void throwOnError(WriteConcern wc, WriteResult wr) {
   if (wc == null && wr.getLastConcern() == null) {
     CommandResult cr = wr.getLastError();
     if (cr != null && cr.getErrorMessage() != null && cr.getErrorMessage().length() > 0)
       cr.throwOnError();
   }
 }
  protected void doBatch() throws KettleException {
    WriteConcern concern = null;

    if (log.getLogLevel().getLevel() >= LogLevel.DETAILED.getLevel()) {
      concern = new WriteConcern(1);
    }
    WriteResult result = null;

    if (concern != null) {
      result = m_data.getCollection().insert(m_batch, concern);
    } else {
      result = m_data.getCollection().insert(m_batch);
    }

    CommandResult cmd = result.getLastError();

    if (cmd != null && !cmd.ok()) {
      String message = cmd.getErrorMessage();
      logError(BaseMessages.getString(PKG, "MongoDbOutput.Messages.Error.MongoReported", message));
      try {
        cmd.throwOnError();
      } catch (MongoException me) {
        throw new KettleException(me.getMessage(), me);
      }
    }

    m_batch.clear();
  }
  @Test
  public void testUsingUpdateWithMultipleSet() throws Exception {

    template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);

    PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
    p1.setFirstName("Sven");
    p1.setAge(11);
    template.insert(p1);
    PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
    p2.setFirstName("Mary");
    p2.setAge(21);
    template.insert(p2);

    Update u = new Update().set("firstName", "Bob").set("age", 10);

    WriteResult wr = template.updateMulti(new Query(), u, PersonWithIdPropertyOfTypeObjectId.class);

    assertThat(wr.getN(), is(2));

    Query q1 = new Query(Criteria.where("age").in(11, 21));
    List<PersonWithIdPropertyOfTypeObjectId> r1 =
        template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(r1.size(), is(0));
    Query q2 = new Query(Criteria.where("age").is(10));
    List<PersonWithIdPropertyOfTypeObjectId> r2 =
        template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(r2.size(), is(2));
    for (PersonWithIdPropertyOfTypeObjectId p : r2) {
      assertThat(p.getAge(), is(10));
      assertThat(p.getFirstName(), is("Bob"));
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
      buffer.append(line);
    }
    String data = buffer.toString();
    System.out.println(data);

    JSONObject params = new JSONObject(data);
    String email = (String) params.get("email");
    String password = (String) params.get("password");

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds011459.mlab.com:11459/farmville");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("logindetails");

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.append("$set", new BasicDBObject().append("password", password));
    BasicDBObject searchQuery = new BasicDBObject().append("email", email);
    WriteResult result = users.update(searchQuery, newDocument);

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

    response.getWriter().write(result.toString());
  }
Exemple #5
0
  @Override
  public void update(KeycloakSession session) {
    BasicDBList orArgs = new BasicDBList();
    orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD));
    orArgs.add(new BasicDBObject("type", UserCredentialModel.PASSWORD_HISTORY));

    BasicDBObject elemMatch = new BasicDBObject("$or", orArgs);
    elemMatch.put("algorithm", new BasicDBObject("$exists", false));

    BasicDBObject query =
        new BasicDBObject("credentials", new BasicDBObject("$elemMatch", elemMatch));

    BasicDBObject update =
        new BasicDBObject(
            "$set", new BasicDBObject("credentials.$.algorithm", Pbkdf2PasswordHashProvider.ID));

    DBCollection users = db.getCollection("users");

    // Not sure how to do in single query
    int countModified = 1;
    while (countModified > 0) {
      WriteResult wr = users.update(query, update, false, true);
      countModified = wr.getN();
      log.debugf(
          "%d credentials modified in current iteration during upgrade to 1.8", countModified);
    }
  }
  @Override // method
  public Role2 add(Role2 roleBaru) {
    final DBObject dbObject = new EntityToDBObject().apply(roleBaru);
    final WriteResult result = rolePersonColl.insert(dbObject);

    log.info("Role '{}' has been added: {}", roleBaru, result.getLastError());
    return roleBaru;
  }
  public static void main(String[] args) throws UnknownHostException {

    MongoClient client = new MongoClient();
    DB database = client.getDB("school");
    DBCollection collection = database.getCollection("students");
    /*
     Hint/spoiler: With the new schema, this problem is a lot harder
     and that is sort of the point. One way is to find the lowest
     homework in code and then update the scores array with the low
     homework pruned. If you are struggling with the Node.js side of
     this, look at the .slice() operator, which can remove an element
     from an array in-place.
    */
    DBCursor cursor = collection.find();

    try {
      while (cursor.hasNext()) {
        BasicDBObject student = (BasicDBObject) cursor.next();

        int studentId = student.getInt("_id");
        String name = student.getString("name");
        BasicDBList scores = (BasicDBList) student.get("scores");
        System.out.printf("_id[%d], name[%s], scores%s %n", studentId, name, scores);

        DBObject scoreToRemove = null;
        double minScoreValue = 100.0;

        for (Object obj : scores) {
          BasicDBObject score = (BasicDBObject) obj;
          String type = score.getString("type");

          if (!"homework".equals(type)) {
            continue;
          }
          double curScoreValue = score.getDouble("score");
          System.out.printf("type[%s], current score value[%f] %n", type, curScoreValue);

          if (curScoreValue < minScoreValue) {
            scoreToRemove = score;
            minScoreValue = curScoreValue;
          }
        }
        System.out.printf("score to remove[%s] %n", scoreToRemove);

        if (scoreToRemove != null) {
          scores.remove(scoreToRemove);

          BasicDBObject query = new BasicDBObject("_id", studentId);
          BasicDBObject scoresUpdate =
              new BasicDBObject("$set", new BasicDBObject("scores", scores));
          WriteResult result = collection.update(query, scoresUpdate);
          System.out.printf("update count[%d] %n", result.getN());
        }
      }
    } finally {
      cursor.close();
    }
  }
Exemple #8
0
 @Test
 public void testUpdateWithObjectIdReturnModifiedDocumentCount() {
   DBCollection collection = newCollection();
   collection.insert(new BasicDBObject("_id", new BasicDBObject("n", 1)));
   DBObject query = new BasicDBObject("_id", new BasicDBObject("n", 1));
   DBObject update = new BasicDBObject("$set", new BasicDBObject("a", 1));
   WriteResult result = collection.update(query, update, false, false);
   assertEquals(1, result.getN());
 }
Exemple #9
0
  @Test
  public void canSaveWithWriteConcern() throws Exception {

    Friend friend = new Friend("John", "22 Wall Street Avenue");

    WriteResult writeResult = collection.withWriteConcern(WriteConcern.SAFE).save(friend);

    assertThat(writeResult.getLastConcern()).isEqualTo(WriteConcern.SAFE);
  }
  @Override
  public boolean removeCharacter(String characterId) {
    Query q = new Query();
    q.addCriteria(Criteria.where("id").is(characterId));

    WriteResult w = mongoOp.remove(q, Character.class);
    if (w.isUpdateOfExisting()) return true;
    else return false;
  }
 @Override
 public int updateActualUserReference(String id, Reference newRef) {
   Query q = new Query();
   q.addCriteria(Criteria.where("id").is(id));
   Update u = new Update();
   u.set("actualUser", newRef);
   WriteResult w = mongoOp.updateFirst(q, u, Character.class);
   return w.getN();
 }
  @Test
  public void testSetState() throws Exception {
    WriteResult response = mock(WriteResult.class);
    when(response.getN()).thenReturn(1);
    when(missedCalls.update(any(DBObject.class), any(DBObject.class))).thenReturn(response);

    assertTrue(missedCallsDAO.setState(new BasicDBObject("state", "Processing"), "Bogus"));
    verify(missedCalls, times(1)).update(any(DBObject.class), any(DBObject.class));
  }
  @SuppressWarnings("unchecked")
  protected void doUpdate(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    List<DBObject> saveObj =
        exchange.getIn().getMandatoryBody((Class<List<DBObject>>) (Class<?>) List.class);
    if (saveObj.size() != 2) {
      throw new CamelMongoDbException(
          "MongoDB operation = insert, failed because body is not a List of DBObject objects with size = 2");
    }

    DBObject updateCriteria = saveObj.get(0);
    DBObject objNew = saveObj.get(1);

    Boolean multi = exchange.getIn().getHeader(MongoDbConstants.MULTIUPDATE, Boolean.class);
    Boolean upsert = exchange.getIn().getHeader(MongoDbConstants.UPSERT, Boolean.class);

    WriteResult result;
    WriteConcern wc = extractWriteConcern(exchange);
    // In API 2.7, the default upsert and multi values of update(DBObject, DBObject) are false,
    // false, so we unconditionally invoke the
    // full-signature method update(DBObject, DBObject, boolean, boolean). However, the default
    // behaviour may change in the future,
    // so it's safer to be explicit at this level for full determinism
    if (multi == null && upsert == null) {
      // for update with no multi nor upsert but with specific WriteConcern there is no update
      // signature without multi and upsert args,
      // so assume defaults
      result =
          wc == null
              ? dbCol.update(updateCriteria, objNew)
              : dbCol.update(updateCriteria, objNew, false, false, wc);
    } else {
      // we calculate the final boolean values so that if any of these
      // parameters is null, it is resolved to false
      result =
          wc == null
              ? dbCol.update(
                  updateCriteria,
                  objNew,
                  calculateBooleanValue(upsert),
                  calculateBooleanValue(multi))
              : dbCol.update(
                  updateCriteria,
                  objNew,
                  calculateBooleanValue(upsert),
                  calculateBooleanValue(multi),
                  wc);
    }

    Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.update);
    // we always return the WriteResult, because whether the getLastError was called or not, the
    // user will have the means to call it or
    // obtain the cached CommandResult
    processAndTransferWriteResult(result, exchange);
    resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN());
  }
 @Override
 public boolean updateSysAccount(String userName, Long state) {
   MongoTemplate mongoTemplate = BaseMongoTemplate.getSysMongo();
   Update update = new Update();
   update.set("acstate", state);
   WriteResult writeResult =
       mongoTemplate.updateFirst(
           Query.query(Criteria.where("userName").is(userName)), update, "sys_user");
   return writeResult.isUpdateOfExisting();
 }
Exemple #15
0
  @Test
  public void shouldUseDefaultWriteConcern() throws Exception {

    Friend friend = new Friend("John", "22 Wall Street Avenue");

    WriteResult writeResult = collection.save(friend);

    assertThat(writeResult.getLastConcern())
        .isEqualTo(collection.getDBCollection().getWriteConcern());
  }
 @Override
 public boolean updatePwd(String account, String pwd) {
   MongoTemplate mongoTemplate = BaseMongoTemplate.getSysMongo();
   WriteResult writeResult =
       mongoTemplate.updateFirst(
           Query.query(Criteria.where("userName").is(account)),
           Update.update("password", pwd),
           "sys_user");
   return writeResult.isUpdateOfExisting();
 }
 @Override
 public boolean setCover(String characterId, String coverId) {
   Query q = new Query();
   q.addCriteria(Criteria.where("id").is(characterId));
   Update u = new Update();
   u.set("cover", coverId);
   WriteResult w = mongoOp.updateFirst(q, u, User.class);
   if (w.isUpdateOfExisting()) return true;
   else return false;
 }
 /** Delete a {<span class="referer">@link</span> Task} for a particular id. */
 public boolean deleteObjectById(String id) {
   WriteResult result = mongoTemplate.remove(new Query(Criteria.where("uid").is(id)), Task.class);
   result.getLastError();
   if (null != result) {
     if (result.getN() > 0) {
       return true;
     }
   }
   return false;
 }
 @Override
 public boolean updateBaiDuName(String name, Long baiduId) {
   MongoTemplate mongoTemplate = BaseMongoTemplate.getSysMongo();
   Update update = new Update();
   update.set("bdAccounts.$.baiduRemarkName", name);
   WriteResult writeResult =
       mongoTemplate.updateFirst(
           Query.query(Criteria.where("bdAccounts._id").is(baiduId)), update, "sys_user");
   return writeResult.isUpdateOfExisting();
 }
  @Test
  public void testRenameAttribute() throws Throwable {
    logger.debug("Start testRenameAttribute");
    try {
      logger.debug("Create river {}", getRiver());
      String script = "ctx.document.score2 = ctx.document.score; delete ctx.document.score;";
      super.createRiver(
          "/test/elasticsearch/plugin/river/mongodb/script/test-mongodb-river-with-script.json",
          getRiver(),
          String.valueOf(getMongoPort1()),
          String.valueOf(getMongoPort2()),
          String.valueOf(getMongoPort3()),
          getDatabase(),
          getCollection(),
          script,
          getIndex(),
          getDatabase());

      String mongoDocument =
          copyToStringFromClasspath(
              "/test/elasticsearch/plugin/river/mongodb/script/test-simple-mongodb-document.json");
      DBObject dbObject = (DBObject) JSON.parse(mongoDocument);
      WriteResult result = mongoCollection.insert(dbObject);
      Thread.sleep(wait);
      String id = dbObject.get("_id").toString();
      logger.info("WriteResult: {}", result.toString());
      refreshIndex();

      ActionFuture<IndicesExistsResponse> response =
          getNode().client().admin().indices().exists(new IndicesExistsRequest(getIndex()));
      assertThat(response.actionGet().isExists(), equalTo(true));

      SearchResponse sr =
          getNode()
              .client()
              .prepareSearch(getIndex())
              .setQuery(fieldQuery("_id", id))
              .execute()
              .actionGet();
      logger.debug("SearchResponse {}", sr.toString());
      long totalHits = sr.getHits().getTotalHits();
      logger.debug("TotalHits: {}", totalHits);
      assertThat(totalHits, equalTo(1l));

      assertThat(sr.getHits().getHits()[0].sourceAsMap().containsKey("score2"), equalTo(true));
      mongoCollection.remove(dbObject);
    } catch (Throwable t) {
      logger.error("testRenameAttribute failed.", t);
      t.printStackTrace();
      throw t;
    } finally {
      super.deleteRiver();
      super.deleteIndex();
    }
  }
 @Override
 public boolean deleteObject(Task object) {
   WriteResult result = mongoTemplate.remove(object);
   result.getLastError();
   if (null != result) {
     if (result.getN() > 0) {
       return true;
     }
   }
   return false;
 }
  @Override
  public boolean addPostToCharacter(String id, PostReference postReference) {
    Query q = new Query();
    q.addCriteria(Criteria.where("id").is(id));
    Update u = new Update();
    u.push("posts", postReference);
    WriteResult w = mongoOp.updateFirst(q, u, Character.class);

    if (w.isUpdateOfExisting()) return true;
    else return false;
  }
Exemple #23
0
 @Test
 public void testUpdateWithIdInMultiReturnModifiedDocumentCount() {
   DBCollection collection = newCollection();
   collection.insert(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2));
   WriteResult result =
       collection.update(
           new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(1, 2))),
           new BasicDBObject("$set", new BasicDBObject("n", 1)),
           false,
           true);
   assertEquals(2, result.getN());
 }
  @Test
  @Ignore("Really slow on the delete, not a good unit tests atm")
  public void deleteBatchTest() throws Exception {

    DB db = getDb();

    int count = (int) (OpDelete.BATCH_SIZE * 1.5);

    List<DBObject> docs = new ArrayList<DBObject>(count);

    for (int i = 0; i < count; i++) {
      BasicDBObject doc = new BasicDBObject();

      doc.put("index", i);

      docs.add(doc);
    }

    WriteResult result = db.getCollection("deletebatchtests").insert(docs);

    assertNull(result.getLastError().getErrorMessage());

    // iterate over all the data to make sure it's been inserted

    DBCursor cursor = db.getCollection("deletebatchtests").find();

    for (int i = 0; i < count && cursor.hasNext(); i++) {
      int index = new BasicDBObject(cursor.next().toMap()).getInt("index");

      assertEquals(i, index);
    }

    BasicDBObject query = new BasicDBObject();
    query.put("index", new BasicDBObject("$lte", count));

    // now delete the objects
    db.getCollection("deletebatchtests").remove(query, WriteConcern.SAFE);

    // now  try and iterate, there should be no results
    cursor = db.getCollection("deletebatchtests").find();

    assertFalse(cursor.hasNext());

    // check it has been deleted
    UUID appId = emf.lookupApplication("test-organization/test-app");
    EntityManager em = emf.getEntityManager(appId);

    Results results =
        em.searchCollection(
            new SimpleEntityRef("application", appId), "deletebatchtests", new Query());

    assertEquals(0, results.size());
  }
 @Override
 public int updateAccountStruts(String userName) {
   MongoTemplate mongoTemplate = BaseMongoTemplate.getSysMongo();
   WriteResult writeResult =
       mongoTemplate.updateFirst(
           Query.query(Criteria.where("userName").is(userName)),
           Update.update("state", 1),
           "sys_user");
   int i = 0;
   if (writeResult.isUpdateOfExisting()) i = 1;
   return i;
 }
Exemple #26
0
 @Test
 public void testUpsertExisting() {
   DBCollection collection = newCollection();
   collection.insert(new BasicDBObject("_id", 1));
   WriteResult result =
       collection.update(
           new BasicDBObject("_id", 1),
           new BasicDBObject("$inc", new BasicDBObject("a", 1)),
           true,
           false);
   assertEquals(new BasicDBObject("_id", 1).append("a", 1), collection.findOne());
   assertTrue(result.getLastError().getBoolean("updatedExisting"));
 }
  protected void doRemove(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    DBObject removeObj = exchange.getIn().getMandatoryBody(DBObject.class);

    WriteConcern wc = extractWriteConcern(exchange);
    WriteResult result = wc == null ? dbCol.remove(removeObj) : dbCol.remove(removeObj, wc);

    Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.remove);
    // we always return the WriteResult, because whether the getLastError was called or not,
    // the user will have the means to call it or obtain the cached CommandResult
    processAndTransferWriteResult(result, exchange);
    resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN());
  }
  public int update() throws Exception {
    if (optimistic) {
      where.put("__version", store.mcnv.toMongo(store.versions.get(optimisticDocument)));
    }
    inc("__version", 1);

    WriteResult result = store.collection.update(where, update, false, !optimistic);
    store.error(result);
    if (optimistic && result.getN() == 0) {
      throw new ConcurrentModificationException("Document was modified after obtention");
    }
    return result.getN();
  }
 @Override
 public boolean saveEmailTemplate(final String context, final String type, final String template)
     throws SocialException {
   try {
     String findQ = getQueryFor("social.system.preferences.byContextAndTemplateType");
     String updateQ = getQueryFor("social.system.preferences.updateContextTemplateType");
     final WriteResult r =
         getCollection().update(findQ, context, type.toUpperCase()).with(updateQ, template);
     checkCommandResult(r);
     return r.getN() == 1;
   } catch (MongoException | MongoDataException ex) {
     throw new SocialException("Unable to update Email template", ex);
   }
 }
 /**
  * submit a command to the database
  *
  * @param database - databse name
  * @param collection - collection name
  * @param query - query for doc search
  * @param operation - operation to be done in DB (insert, remove or update)
  * @param command - command
  * @param all - if true, all docs will be affected by the command
  * @return
  */
 public String submitDBCommand(
     String database,
     String collection,
     String query,
     String operation,
     String command,
     Boolean all) {
   WriteResult result = null;
   try {
     DBCollection DBCollection = getCollection(database, collection);
     if (operation.equals("insert")) {
       JSONObject teste = new JSONObject(command);
       Object teste1 = JSON.parse(teste.toString());
       DBObject doc = (DBObject) teste1;
       result = DBCollection.save(doc);
     } else if (operation.equals("update")) {
       DBObject queryDB = (DBObject) JSON.parse(query);
       DBObject doc = (DBObject) JSON.parse(command);
       if (all) {
         result = DBCollection.update(queryDB, doc, false, true);
       } else {
         result = DBCollection.update(queryDB, doc);
       }
     } else if (operation.equals("remove")) {
       DBObject queryDB = (DBObject) JSON.parse(query);
       DBObject doc = (DBObject) JSON.parse(command);
       if (all) {
         result = DBCollection.update(queryDB, doc, false, true);
       } else {
         result = DBCollection.update(queryDB, doc);
       }
     }
     return "Result: " + result.toString();
   } catch (Exception e) {
     logger.logp(
         Level.SEVERE,
         TAG,
         "executeDBCommand",
         e.getMessage()
             + " database:"
             + database
             + " collection: "
             + collection
             + ", result: "
             + result.toString());
     e.printStackTrace();
   }
   return null;
 } // database, collection, query, operation, command, all