/**
   * @see DATAMONGO-753
   * @see http
   *     ://stackoverflow.com/questions/18653574/spring-data-mongodb-aggregation-framework-invalid-reference-in-group
   *     -operati
   */
  @Test
  public void allowsNestedFieldReferencesAsGroupIdsInGroupExpressions() {

    mongoTemplate.insert(
        new DATAMONGO753().withPDs(new PD("A", 1), new PD("B", 1), new PD("C", 1)));
    mongoTemplate.insert(
        new DATAMONGO753().withPDs(new PD("B", 1), new PD("B", 1), new PD("C", 1)));

    TypedAggregation<DATAMONGO753> agg =
        newAggregation(
            DATAMONGO753.class, //
            unwind("pd"), //
            group("pd.pDch") // the nested field expression
                .sum("pd.up")
                .as("uplift"), //
            project("_id", "uplift"));

    AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, DBObject.class);
    List<DBObject> stats = result.getMappedResults();

    assertThat(stats.size(), is(3));
    assertThat(stats.get(0).get("_id").toString(), is("C"));
    assertThat((Integer) stats.get(0).get("uplift"), is(2));
    assertThat(stats.get(1).get("_id").toString(), is("B"));
    assertThat((Integer) stats.get(1).get("uplift"), is(3));
    assertThat(stats.get(2).get("_id").toString(), is("A"));
    assertThat((Integer) stats.get(2).get("uplift"), is(1));
  }
  @Before
  public void setUp() {
    // clear all collections
    mongoTemplate.dropCollection("role");
    mongoTemplate.dropCollection("userAccount");
    // see UserAccount.username definition: @Indexed does not work, but this does (sdm
    // 1.1.1.RELEASE)
    // see RepositoryTest.userDuplicate()
    mongoTemplate
        .indexOps(UserAccount.class)
        .ensureIndex(new Index().on("username", Order.DESCENDING).unique(Duplicates.DROP));

    // establish roles
    userRole = new Role();
    userRole.setId("ROLE_USER");
    mongoTemplate.insert(userRole, "role");

    adminRole = new Role();
    adminRole.setId("ROLE_ADMIN");
    mongoTemplate.insert(adminRole, "role");

    superAdminRole = new Role();
    superAdminRole.setId("ROLE_SUPERADMIN");
    mongoTemplate.insert(superAdminRole, "role");
  }
예제 #3
0
 @Override
 public void create(DocumentDAO document) {
   if (document == null) {
     logger.error("Inserted document must not be null.");
     return;
   }
   mongoTemplate.insert(document);
 }
  @Test
  public void givenUsersExist_whenFindingUserWithAgeLessThan50AndGreateThan20_thenUsersAreFound() {
    User user = new User();
    user.setName("Eric");
    user.setAge(45);
    mongoTemplate.insert(user);
    user = new User();
    user.setName("Antony");
    user.setAge(55);
    mongoTemplate.insert(user);

    Query query = new Query();
    query.addCriteria(Criteria.where("age").lt(50).gt(20));
    List<User> users = mongoTemplate.find(query, User.class);

    assertThat(users.size(), is(1));
  }
 @Override
 public void addProductDetail(ProductDetail productDetail) {
   if (!mongoTemplate.collectionExists(ProductDetail.class)) {
     mongoTemplate.createCollection(ProductDetail.class);
   }
   // insert a document
   logger.info("ProductDetailDAOMongo add productDetail");
   mongoTemplate.insert(productDetail, COLLECTION_NAME);
 }
  /**
   * @see DATAMONGO-753
   * @see http
   *     ://stackoverflow.com/questions/18653574/spring-data-mongodb-aggregation-framework-invalid-reference-in-group
   *     -operati
   */
  @Test
  public void aliasesNestedFieldInProjectionImmediately() {

    mongoTemplate.insert(
        new DATAMONGO753().withPDs(new PD("A", 1), new PD("B", 1), new PD("C", 1)));
    mongoTemplate.insert(
        new DATAMONGO753().withPDs(new PD("B", 1), new PD("B", 1), new PD("C", 1)));

    TypedAggregation<DATAMONGO753> agg =
        newAggregation(
            DATAMONGO753.class, //
            unwind("pd"), //
            project().and("pd.up").as("up"));

    AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, DBObject.class);
    List<DBObject> mappedResults = results.getMappedResults();

    assertThat(mappedResults, hasSize(6));
    for (DBObject element : mappedResults) {
      assertThat(element.get("up"), is((Object) 1));
    }
  }
 private void createUserWithLikesDocuments() {
   mongoTemplate.insert(new UserWithLikes("u1", new Date(), "a", "b", "c"));
   mongoTemplate.insert(new UserWithLikes("u2", new Date(), "a"));
   mongoTemplate.insert(new UserWithLikes("u3", new Date(), "b", "c"));
   mongoTemplate.insert(new UserWithLikes("u4", new Date(), "c", "d", "e"));
   mongoTemplate.insert(new UserWithLikes("u5", new Date(), "a", "e", "c"));
   mongoTemplate.insert(new UserWithLikes("u6", new Date()));
   mongoTemplate.insert(new UserWithLikes("u7", new Date(), "a"));
   mongoTemplate.insert(new UserWithLikes("u8", new Date(), "x", "e"));
   mongoTemplate.insert(new UserWithLikes("u9", new Date(), "y", "d"));
 }
  @Test
  public void givenUsersExist_whenFindingUserWithNameStartWithA_thenUsersAreFound() {
    User user = new User();
    user.setName("Eric");
    user.setAge(45);
    mongoTemplate.insert(user);

    user = new User();
    user.setName("Antony");
    user.setAge(33);
    mongoTemplate.insert(user);

    user = new User();
    user.setName("Alice");
    user.setAge(35);
    mongoTemplate.insert(user);

    Query query = new Query();
    query.addCriteria(Criteria.where("name").regex("^A"));

    List<User> users = mongoTemplate.find(query, User.class);
    assertThat(users.size(), is(2));
  }
  @Test
  public void givenUsersExist_whenFindingUsersAndSortThem_thenUsersAreFoundAndSorted() {
    User user = new User();
    user.setName("Eric");
    user.setAge(45);
    mongoTemplate.insert(user);

    user = new User();
    user.setName("Antony");
    user.setAge(33);
    mongoTemplate.insert(user);

    user = new User();
    user.setName("Alice");
    user.setAge(35);
    mongoTemplate.insert(user);

    Query query = new Query();
    query.with(new Sort(Sort.Direction.ASC, "age"));

    List<User> users = mongoTemplate.find(query, User.class);
    assertThat(users.size(), is(3));
  }
  @Test
  public void givenUsersExist_whenFindingByPage_thenUsersAreFoundByPage() {
    User user = new User();
    user.setName("Eric");
    user.setAge(45);
    mongoTemplate.insert(user);

    user = new User();
    user.setName("Antony");
    user.setAge(33);
    mongoTemplate.insert(user);

    user = new User();
    user.setName("Alice");
    user.setAge(35);
    mongoTemplate.insert(user);

    final Pageable pageableRequest = new PageRequest(0, 2);
    Query query = new Query();
    query.with(pageableRequest);

    List<User> users = mongoTemplate.find(query, User.class);
    assertThat(users.size(), is(2));
  }
  private void processConcurrentConfig(File f) throws IOException, SAXException {

    SlbModelTree slbmodel = readFromFile(f);
    String collectionName = getCollectionName(f, slbmodel);
    synchronized (this) {
      if (!mongoTemplate.collectionExists(collectionName)) {
        createCollection(collectionName);
      }
    }

    DocumentKey key = getDocumentKey(f, slbmodel);
    slbmodel.setTag(key.getTag());
    updateTagGlobalId(collectionName, key.getTag());
    mongoTemplate.insert(slbmodel, collectionName);
  }
  private void addTags(Question question) {
    for (String tagName : question.getTags()) {
      Tag existingTag = tagRepo.findByName(tagName);
      if (existingTag != null) {
        Query q = new Query(Criteria.where("id").is(existingTag.getId()));
        template.updateFirst(
            q, new Update().push("questions", question.getId()).inc("questionCount", 1), Tag.class);
      } else {
        Tag newTag = new Tag();
        newTag.setName(tagName);
        newTag.setCreatedBy(question.getCreatedBy());
        newTag.setCreatedDate(Calendar.getInstance().getTime());
        newTag.setQuestionCount(1);

        List<String> questions = new ArrayList<String>();
        questions.add(question.getId());
        newTag.setQuestions(questions);

        template.insert(newTag);
      }
    }
  }
  @Override
  public void getAdgroupReportData(
      List<AdgroupReportDTO> adgroupReportDTOs, SystemUserDTO systemUser, String dateStr, int i) {
    MongoTemplate mongoTemplate;
    mongoTemplate =
        BaseMongoTemplate.getMongoTemplate(DBNameUtils.getReportDBName(systemUser.getUserName()));

    List<AdgroupReportEntity> adgroupReportEntities =
        new ArrayList<>(ObjectUtils.convert(adgroupReportDTOs, AdgroupReportEntity.class));
    List<AdgroupReportEntity> adgroupReportEntities1;
    if (mongoTemplate.collectionExists(dateStr + "-adgroup")) {
      if (i > 1) {
        adgroupReportEntities1 =
            new ArrayList<>(
                mongoTemplate.find(new Query(), AdgroupReportEntity.class, dateStr + "-adgroup"));
        adgroupReportEntities.addAll(adgroupReportEntities1);
      }
      mongoTemplate.dropCollection(dateStr + "-adgroup");
    }

    mongoTemplate.insert(adgroupReportEntities, dateStr + "-adgroup");
  }
예제 #14
0
 @Test
 public void test() throws Throwable {
   TestMethodInvocation invocation = new TestMethodInvocation();
   CountObj anobj = new CountObj();
   invocation.setThis(anobj);
   Method method = CountObj.class.getDeclaredMethod("count", First.class);
   invocation.setMethod(method);
   invocation.setArguments(new Object[] {new First()});
   Object res = executerInterceptor.invoke(invocation);
   Assert.assertNotNull(res);
   Assert.assertEquals(Long.class, res.getClass());
   long resFirst = (Long) res;
   Assert.assertEquals(0, resFirst);
   // 然后,插入5个
   for (int i = 1; i <= 5; i++) {
     First first = new First();
     first.setName("name" + i);
     template.insert(first);
     long myres = (Long) executerInterceptor.invoke(invocation);
     Assert.assertEquals(i, myres);
   }
 }
예제 #15
0
  @Test
  public void testGeoLocation() {
    GeoLocation geo = new GeoLocation(new double[] {40.714346, -74.005966});
    template.insert(geo);

    boolean hasIndex =
        template.execute(
            "geolocation",
            new CollectionCallback<Boolean>() {
              public Boolean doInCollection(DBCollection collection)
                  throws MongoException, DataAccessException {
                List<DBObject> indexes = collection.getIndexInfo();
                for (DBObject dbo : indexes) {
                  if ("location".equals(dbo.get("name"))) {
                    return true;
                  }
                }
                return false;
              }
            });

    assertTrue(hasIndex);
  }
  @Override
  public void getAccountReportData(
      List<AccountReportDTO> accountReportDTOs,
      SystemUserDTO systemUser,
      String dateStr,
      String baiduUserName) {
    MongoTemplate mongoTemplate;
    mongoTemplate =
        BaseMongoTemplate.getMongoTemplate(DBNameUtils.getReportDBName(systemUser.getUserName()));

    List<AccountReportEntity> accountReportEntities =
        ObjectUtils.convert(accountReportDTOs, AccountReportEntity.class);
    Date date = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = df.format(date);

    List<AccountReportEntity> entities = null;
    if (!dateStr.equals(dateString)) {
      try {
        entities =
            mongoTemplate.find(
                Query.query(
                    Criteria.where("date")
                        .is(new SimpleDateFormat("yyyy-MM-dd").parse(dateStr))
                        .and("acna")
                        .is(baiduUserName)),
                AccountReportEntity.class);
      } catch (ParseException e) {
        e.printStackTrace();
      }

      if (entities == null || entities.size() == 0) {
        mongoTemplate.insert(accountReportEntities, TBL_ACCOUNT_REPORT);
      }
    }
  }
 public void saveObject(Task task, String collectionName) {
   mongoTemplate.insert(task, collectionName);
 }
예제 #18
0
 @Override
 public RoomDTO insert(RoomDTO room) {
   logger.info("Room insert");
   mongoTemplate.insert(room, COLLECTION_NAME);
   return room;
 }
 @Override
 public void save(List<CardCdr> cardCdrs) {
   mongoTemplate.insert(cardCdrs, CardCdr.class);
 }
  @Test
  public void arithmenticOperatorsInProjectionExample() {

    double taxRate = 0.19;
    double netPrice = 1.99;
    double discountRate = 0.05;
    int spaceUnits = 3;
    String productId = "P1";
    String productName = "A";
    mongoTemplate.insert(
        new Product(productId, productName, netPrice, spaceUnits, discountRate, taxRate));

    TypedAggregation<Product> agg =
        newAggregation(
            Product.class, //
            project("name", "netPrice") //
                .and("netPrice")
                .plus(1)
                .as("netPricePlus1") //
                .and("netPrice")
                .minus(1)
                .as("netPriceMinus1") //
                .and("netPrice")
                .multiply(2)
                .as("netPriceMul2") //
                .and("netPrice")
                .divide(1.19)
                .as("netPriceDiv119") //
                .and("spaceUnits")
                .mod(2)
                .as("spaceUnitsMod2") //
                .and("spaceUnits")
                .plus("spaceUnits")
                .as("spaceUnitsPlusSpaceUnits") //
                .and("spaceUnits")
                .minus("spaceUnits")
                .as("spaceUnitsMinusSpaceUnits") //
                .and("spaceUnits")
                .multiply("spaceUnits")
                .as("spaceUnitsMultiplySpaceUnits") //
                .and("spaceUnits")
                .divide("spaceUnits")
                .as("spaceUnitsDivideSpaceUnits") //
                .and("spaceUnits")
                .mod("spaceUnits")
                .as("spaceUnitsModSpaceUnits") //
            );

    AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, DBObject.class);
    List<DBObject> resultList = result.getMappedResults();

    assertThat(resultList, is(notNullValue()));
    assertThat((String) resultList.get(0).get("_id"), is(productId));
    assertThat((String) resultList.get(0).get("name"), is(productName));
    assertThat((Double) resultList.get(0).get("netPricePlus1"), is(netPrice + 1));
    assertThat((Double) resultList.get(0).get("netPriceMinus1"), is(netPrice - 1));
    assertThat((Double) resultList.get(0).get("netPriceMul2"), is(netPrice * 2));
    assertThat((Double) resultList.get(0).get("netPriceDiv119"), is(netPrice / 1.19));
    assertThat((Integer) resultList.get(0).get("spaceUnitsMod2"), is(spaceUnits % 2));
    assertThat(
        (Integer) resultList.get(0).get("spaceUnitsPlusSpaceUnits"), is(spaceUnits + spaceUnits));
    assertThat(
        (Integer) resultList.get(0).get("spaceUnitsMinusSpaceUnits"), is(spaceUnits - spaceUnits));
    assertThat(
        (Integer) resultList.get(0).get("spaceUnitsMultiplySpaceUnits"),
        is(spaceUnits * spaceUnits));
    assertThat(
        (Double) resultList.get(0).get("spaceUnitsDivideSpaceUnits"),
        is((double) (spaceUnits / spaceUnits)));
    assertThat(
        (Integer) resultList.get(0).get("spaceUnitsModSpaceUnits"), is(spaceUnits % spaceUnits));
  }
예제 #21
0
 // Creating an user in the repository.
 public void createUsuario(UsuarioSiar usuarioSiar) {
   if (!siarmongoTemplate.collectionExists(UsuarioSiar.class)) {
     siarmongoTemplate.createCollection(UsuarioSiar.class);
   }
   siarmongoTemplate.insert(usuarioSiar, "usuarioSiarTable");
 }
예제 #22
0
 @Override
 public void save(Person thePerson) {
   template.insert(thePerson);
 }
 public void insertInventory() {
   Inventory Inv = new Inventory("book", "I1", "GirlChildToSchool", 100.00);
   mongoTemplate.insert(Inv);
 }
 /** Saves a {<span class="referer">@link</span> Task}. */
 public void saveObject(Task task) {
   mongoTemplate.insert(task);
 }