@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"));
    }
  }
  @Override
  public BigDecimal getCurrencyValue(CurrencyForm currencyForm) throws NoCurrenciesException {
    Criteria fromCriteria =
        Criteria.where("timestamp")
            .is(currencyForm.getTimestamp())
            .and("currencyCode")
            .is(currencyForm.getFromCurrencyCode());

    List<MongoCurrency> fromCurrencies = currencyMongoDao.query(fromCriteria);

    Criteria toCriteria =
        Criteria.where("timestamp")
            .is(currencyForm.getTimestamp())
            .and("currencyCode")
            .is(currencyForm.getToCurrencyCode());

    List<MongoCurrency> toCurrencies = currencyMongoDao.query(toCriteria);

    if (fromCurrencies.isEmpty() || toCurrencies.isEmpty()) {
      throw new NoCurrenciesException(
          currencyForm.getFromCurrencyCode(),
          currencyForm.getToCurrencyCode(),
          currencyForm.getTimestamp());
    }

    MongoCurrency fromCurrency = fromCurrencies.get(0);
    MongoCurrency toCurrency = toCurrencies.get(0);

    BigDecimal fromCurrencyInUsd =
        BigDecimal.ONE
            .divide(fromCurrency.getValue(), 10, BigDecimal.ROUND_HALF_UP)
            .multiply(currencyForm.getAmountFrom());

    return fromCurrencyInUsd.multiply(toCurrency.getValue());
  }
  private List<MaintenanceSpendBySupplier> getTruckMaintenanceSpend(
      Truck truck, Date from, Date to) {
    Query truckMaintenanceSpendListQuery = new Query();
    truckMaintenanceSpendListQuery.addCriteria(
        Criteria.where("truckId")
            .is(truck.getId())
            .andOperator(
                Criteria.where("transactionDate").gte(from),
                Criteria.where("transactionDate").lte(to)));

    /*
    * List<MaintenanceSpendBySupplier> maintenanceSpendList = mongoOperation.find(truckMaintenanceSpendListQuery, MaintenanceSpendBySupplier.class);

    System.out.println(" MaintenanceSpendBySupplierRepository - TRUCK QUERY - Start= " + to + " | To= " + to + "  FOR truckId: " + truck.getId());
    if (maintenanceSpendList.isEmpty()) {
    System.out.println("MaintenanceSpendBySupplierRepository  - TRUCK QUERY - NO MATCHING RECORDS FOUND");
    }

    for (MaintenanceSpendBySupplier maintenanceSpend : maintenanceSpendList) {
    System.out.println(" MaintenanceSpendBySupplierRepository - TRUCK QUERY - Date= " + maintenanceSpend.getTransactionDate() + " | Cost= " + maintenanceSpend.getMaintenanceCost() + " | Truck= " + maintenanceSpend.getTruckId() + " | Supplier" + maintenanceSpend.getSupplierId());
    }
    System.out.println("--==--");
    */

    return mongoOperation.find(truckMaintenanceSpendListQuery, MaintenanceSpendBySupplier.class);
  }
  @Override
  public DataGrid<DumpHst> queryDataGird(DumpHst dumpHst, Pageable pageable) {
    DataGrid<DumpHst> dumpHstDataGird = new DataGrid<DumpHst>(0, new ArrayList<DumpHst>());
    if (dumpHst.isSerachFlag()) {
      Criteria expression = where("deleteFlag").is("0");
      if (dumpHst.getFromDate() != null && dumpHst.getToDate() != null) {
        expression.andOperator(
            where("created").gte(dumpHst.getFromDate()),
            where("created").lt(DateUtil.getAfterOrBeforDate(dumpHst.getToDate(), 1)));
      } else {
        if (dumpHst.getFromDate() != null) {
          expression.and("created").gte(dumpHst.getFromDate());
        }
        if (dumpHst.getToDate() != null) {
          expression.and("created").lt(DateUtil.getAfterOrBeforDate(dumpHst.getToDate(), 1));
        }
      }

      long count = mongoTemplate.count(query(expression), DumpHst.class);
      List<DumpHst> list = mongoTemplate.find(query(expression).with(pageable), DumpHst.class);
      dumpHstDataGird.setRows(list);
      dumpHstDataGird.setTotal(count);
    }
    return dumpHstDataGird;
  }
  @Test
  public void testUsingRegexQueryWithOptions() 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);
    PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId();
    p3.setFirstName("Ann");
    p3.setAge(31);
    template.insert(p3);
    PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId();
    p4.setFirstName("samantha");
    p4.setAge(41);
    template.insert(p4);

    Query q1 = new Query(Criteria.where("firstName").regex("S.*"));
    List<PersonWithIdPropertyOfTypeObjectId> results1 =
        template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
    Query q2 = new Query(Criteria.where("firstName").regex("S.*", "i"));
    List<PersonWithIdPropertyOfTypeObjectId> results2 =
        template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(results1.size(), is(1));
    assertThat(results2.size(), is(2));
  }
  @Override
  public List<MaintenanceSpendBySupplier> getMaintenanceSpendBetweenTwoDates(Date from, Date to) {
    Date fromDate = dateTimeFormatHelper.resetTimeAndMonthStart(from);
    Date toDate = dateTimeFormatHelper.resetTimeAndMonthEnd(to);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(toDate);
    // Set time fields to last hour:minute:second:millisecond
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);

    Query maintenanceSpendListQuery = new Query();
    maintenanceSpendListQuery.addCriteria(
        Criteria.where("transactionDate")
            .exists(true)
            .andOperator(
                Criteria.where("transactionDate").gte(fromDate),
                Criteria.where("transactionDate").lte(calendar.getTime())));

    /*
    List<MaintenanceSpendBySupplier> maintenanceSpendList = mongoOperation.find(maintenanceSpendListQuery, MaintenanceSpendBySupplier.class);

    System.out.println(" MaintenanceSpendBySupplierRepository - GENERAL QUERY - Start= " + to + " | To= " + to);
    if (maintenanceSpendList.isEmpty()) {
    System.out.println("MaintenanceSpendBySupplierRepository  - GENERAL QUERY - NO MATCHING RECORDS FOUND");
    }

    for (MaintenanceSpendBySupplier maintenanceSpend : maintenanceSpendList) {
    System.out.println(" MaintenanceSpendBySupplierRepository - GENERAL QUERY - Date= " + maintenanceSpend.getTransactionDate() + " | Cost= " + maintenanceSpend.getMaintenanceCost() + " | Truck= " + maintenanceSpend.getTruckId() + " | Supplier" + maintenanceSpend.getSupplierId());
    }
    System.out.println("--==--");
    */
    return mongoOperation.find(maintenanceSpendListQuery, MaintenanceSpendBySupplier.class);
  }
  @Test
  public void testUsingAnInQueryWithStringId() throws Exception {

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

    PersonWithIdPropertyOfTypeString p1 = new PersonWithIdPropertyOfTypeString();
    p1.setFirstName("Sven");
    p1.setAge(11);
    template.insert(p1);
    PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString();
    p2.setFirstName("Mary");
    p2.setAge(21);
    template.insert(p2);
    PersonWithIdPropertyOfTypeString p3 = new PersonWithIdPropertyOfTypeString();
    p3.setFirstName("Ann");
    p3.setAge(31);
    template.insert(p3);
    PersonWithIdPropertyOfTypeString p4 = new PersonWithIdPropertyOfTypeString();
    p4.setFirstName("John");
    p4.setAge(41);
    template.insert(p4);

    Query q1 = new Query(Criteria.where("age").in(11, 21, 41));
    List<PersonWithIdPropertyOfTypeString> results1 =
        template.find(q1, PersonWithIdPropertyOfTypeString.class);
    Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary"));
    List<PersonWithIdPropertyOfTypeString> results2 =
        template.find(q2, PersonWithIdPropertyOfTypeString.class);
    Query q3 = new Query(Criteria.where("id").in(p3.getId(), p4.getId()));
    List<PersonWithIdPropertyOfTypeString> results3 =
        template.find(q3, PersonWithIdPropertyOfTypeString.class);
    assertThat(results1.size(), is(3));
    assertThat(results2.size(), is(2));
    assertThat(results3.size(), is(2));
  }
 public Pagination getObjectsByStatus(Integer pageNo, Integer pageSize, Integer status) {
   Query query = new Query();
   if (pageNo == null) {
     pageNo = 1;
   }
   if (pageSize == null) {
     pageSize = 20;
   }
   if (status != null) {
     if (status == 888) {
       // 所有状态不是2的任务列表
       // 也就是所有运行中的任务状态
       Criteria criteriaStatus = Criteria.where("taskStatus").ne(2);
       query.addCriteria(criteriaStatus);
     } else {
       Criteria criteriaStatus = Criteria.where("taskStatus").is(status);
       query.addCriteria(criteriaStatus);
     }
   }
   long totalCount =
       this.mongoTemplate.count(query, Task.class, AllCollectionName.ALLFILEINFO_COLLECTIONNAME);
   Pagination page = new Pagination(pageNo, pageSize, totalCount);
   query.with(new Sort(Direction.DESC, "runTime"));
   query.skip(page.getFirstResult());
   query.limit(pageSize);
   page.setList(
       mongoTemplate.find(query, Task.class, AllCollectionName.ALLFILEINFO_COLLECTIONNAME));
   return page;
 }
  @Test
  public void testRemovingDocument() throws Exception {

    PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
    p1.setFirstName("Sven_to_be_removed");
    p1.setAge(51);
    template.insert(p1);

    Query q1 = new Query(Criteria.where("id").is(p1.getId()));
    PersonWithIdPropertyOfTypeObjectId found1 =
        template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(found1, notNullValue());
    Query _q = new Query(Criteria.where("_id").is(p1.getId()));
    template.remove(_q, PersonWithIdPropertyOfTypeObjectId.class);
    PersonWithIdPropertyOfTypeObjectId notFound1 =
        template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(notFound1, nullValue());

    PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
    p2.setFirstName("Bubba_to_be_removed");
    p2.setAge(51);
    template.insert(p2);

    Query q2 = new Query(Criteria.where("id").is(p2.getId()));
    PersonWithIdPropertyOfTypeObjectId found2 =
        template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(found2, notNullValue());
    template.remove(q2, PersonWithIdPropertyOfTypeObjectId.class);
    PersonWithIdPropertyOfTypeObjectId notFound2 =
        template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(notFound2, nullValue());
  }
 protected Query getQueryForIndex(String indexName, Object indexValue) {
   if (FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) {
     return Query.query(Criteria.where(PRINCIPAL_FIELD_NAME).is(indexValue));
   }
   return Query.query(
       Criteria.where(ATTRS_FIELD_NAME + MongoExpiringSession.coverDot(indexName)).is(indexValue));
 }
 public List<Task> getObjectsByRunTime(String date) {
   Query query = new Query();
   Criteria criteria = Criteria.where("runTime").lte(date);
   Criteria criteriaStatus = Criteria.where("taskStatus").is(0);
   query.addCriteria(criteria).addCriteria(criteriaStatus);
   query.with(new Sort(Direction.ASC, "runTime"));
   return mongoTemplate.find(query, Task.class);
 }
  @Override
  public List<ThesisDefence> thesisDefencesBetweenDatesIncludingCommissionParticipants(
      Date startDate, Date endDate, ObjectId commissionParticipantId) {
    Query searchQuery = new Query(Criteria.where("date").gte(startDate).lte(endDate));
    searchQuery.addCriteria(Criteria.where("commissionParticipantIds").is(commissionParticipantId));
    List<ThesisDefence> thesisDefences = mongoTemplate.find(searchQuery, ThesisDefence.class);

    return thesisDefences;
  }
 public List<Account> findBy(String userId, String appId) {
   Criteria criteria = new Criteria();
   if (userId != null) {
     criteria.and("userId").is(userId);
   }
   if (appId != null) {
     criteria.and("appId").is(appId);
   }
   return db.find(Query.query(criteria), Account.class);
 }
Example #14
0
 static Criteria buildRegex(Criteria criteria, Object regexValue) {
   if (regexValue instanceof List) {
     return criteria.all(
         ((List<String>) regexValue)
             .stream()
             .map(regex -> Pattern.compile(regex, Pattern.CASE_INSENSITIVE))
             .collect(Collectors.toList()));
   } else {
     return criteria.regex(Pattern.compile((String) regexValue, Pattern.CASE_INSENSITIVE));
   }
 }
Example #15
0
 public Users findAccountById(String useridEmail, String joinPassword) {
   joinPassword = AppUtils.encodePasswordToMD5(joinPassword);
   Query query =
       new Query(Criteria.where("username").is(useridEmail).and("password").is(joinPassword));
   Users user = mongoTemplate.findOne(query, Users.class);
   if (null == user) {
     query = new Query(Criteria.where("email").is(useridEmail).and("password").is(joinPassword));
     user = mongoTemplate.findOne(query, Users.class);
   }
   return user;
 }
  @Override
  public UserSessionActivity findByUserIdAndIPAddressAndSessionId(
      String userId, String ipAddress, String sessionId) {
    Criteria criteria = Criteria.where("user.$id").is(userId);
    criteria =
        criteria.andOperator(
            Criteria.where("ipAddress")
                .is(ipAddress)
                .andOperator(Criteria.where("sessionId").is(sessionId)));
    Query query = new Query(criteria);

    return mongoTemplate.findOne(query, UserSessionActivity.class);
  }
Example #17
0
  @Override
  public License findLicenseById(String licenseId) {

    Criteria c = Criteria.where("licenses").elemMatch(Criteria.where("_id").is(licenseId));
    BasicQuery basicQuery = new BasicQuery(c.getCriteriaObject(), c.getCriteriaObject());

    LicenseGroup lg = this.findOne(basicQuery);
    if (lg != null) {
      License g = lg.getLicenses().get(0);
      g.setGroup(lg);
      return g;
    }
    return null;
  }
 public void deleteByCid(long cid) {
   MongoTemplate mongoTemplate = getMongoTemplate();
   mongoTemplate.remove(
       new Query(Criteria.where(MongoEntityConstants.CAMPAIGN_ID).is(cid)),
       getEntityClass(),
       MongoEntityConstants.BAK_CAMPAIGN);
 }
 public Task getObjectsByFilePath(String filePath) {
   Query query = new Query();
   Criteria criteriaStatus = Criteria.where("filePath").is(filePath);
   query.addCriteria(criteriaStatus);
   query.with(new Sort(Direction.DESC, "runTime"));
   return mongoTemplate.findOne(query, Task.class, AllCollectionName.ALLFILEINFO_COLLECTIONNAME);
 }
Example #20
0
  public Tag getQuestionsSliceByTagId(String tagId, int currentPage, int pageSize) {
    Query q = new Query(Criteria.where("id").is(tagId));
    q.fields().slice("questions", (currentPage - 1) * pageSize, pageSize);
    Tag tag = template.findOne(q, Tag.class);

    return tag;
  }
 @Override
 public List<SystemUserDTO> getAccount() {
   MongoTemplate mongoTemplate = BaseMongoTemplate.getSysMongo();
   return ObjectUtils.convert(
       mongoTemplate.find(Query.query(Criteria.where("state").is(0)), getEntityClass()),
       getDTOClass());
 }
 public void removeById(String id) {
   System.out.println("DAO: Querying data id:" + id);
   Query query = new Query(Criteria.where("_id").is(id));
   System.out.println("DAO: Deleting data id:" + id);
   WriteResult result = this.mongoOps.remove(query, HelloWorld.class, COLLECTION);
   System.out.println("DAO: Deleted!");
 }
 public List<HelloWorld> getManybyName(String name) {
   System.out.println("DAO: Querying all data name:" + name);
   Query query = new Query();
   query.addCriteria(Criteria.where("name").is(name));
   System.out.println("DAO: Return data");
   return mongoOps.find(query, HelloWorld.class, COLLECTION);
 }
 @Override
 public void addTag(String id, TagDAO tag) {
   mongoTemplate.findAndModify(
       new Query(Criteria.where("_id").is(id)),
       new Update().addToSet("tag", tag),
       DocumentDAO.class);
 }
 @Override
 public void removeRequirement(String id, String rid) {
   mongoTemplate.findAndModify(
       new Query(Criteria.where("_id").is(id)),
       new Update().pull("requirements", rid).inc("count", -1),
       DocumentDAO.class);
 }
 @Override
 public List<DocumentDAO> findByProjectId(String id) {
   return mongoTemplate.find(
       new Query(Criteria.where("project_id").is(id))
           .with(new Sort(Sort.Direction.ASC, "position")),
       DocumentDAO.class);
 }
  @Override
  public long countByUserId(String userId) {
    Criteria criteria = Criteria.where("user.$id").is(userId);
    Query query = new Query(criteria);

    return mongoTemplate.count(query, UserSessionActivity.class);
  }
Example #28
0
  public Mother search(String name) {

    Query searchUserQuery = new Query(Criteria.where("name").is(name));

    Mother savedUser = mongo.findOne(searchUserQuery, Mother.class);
    return savedUser;
  }
  @Test
  public void testAddingToList() {
    PersonWithAList p = new PersonWithAList();
    p.setFirstName("Sven");
    p.setAge(22);
    template.insert(p);

    Query q1 = new Query(Criteria.where("id").is(p.getId()));
    PersonWithAList p2 = template.findOne(q1, PersonWithAList.class);
    assertThat(p2, notNullValue());
    assertThat(p2.getWishList().size(), is(0));

    p2.addToWishList("please work!");

    template.save(p2);

    PersonWithAList p3 = template.findOne(q1, PersonWithAList.class);
    assertThat(p3, notNullValue());
    assertThat(p3.getWishList().size(), is(1));

    Friend f = new Friend();
    p.setFirstName("Erik");
    p.setAge(21);

    p3.addFriend(f);
    template.save(p3);

    PersonWithAList p4 = template.findOne(q1, PersonWithAList.class);
    assertThat(p4, notNullValue());
    assertThat(p4.getWishList().size(), is(1));
    assertThat(p4.getFriends().size(), is(1));
  }
Example #30
0
 public User findUser(String username) {
   if (exists(username)) {
     Query query = new Query(Criteria.where("username").is(username));
     return mongoTemplate.findOne(query, User.class, USERS);
   }
   return null;
 }