Java Code Examples for org.springframework.data.mongodb.core.query.Query

The following examples show how to use org.springframework.data.mongodb.core.query.Query. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: FEBS-Cloud   Source File: BlackListServiceImpl.java    License: Apache License 2.0 7 votes vote down vote up
private Query getQuery(BlackList blackList) {
    Query query = new Query();
    Criteria criteria = new Criteria();
    if (StringUtils.isNotBlank(blackList.getIp())) {
        criteria.and("ip").is(blackList.getIp());
    }
    if (StringUtils.isNotBlank(blackList.getRequestUri())) {
        criteria.and("requestUri").is(blackList.getRequestUri());
    }
    if (StringUtils.isNotBlank(blackList.getRequestMethod())) {
        criteria.and("requestMethod").is(blackList.getRequestMethod());
    }
    if (StringUtils.isNotBlank(blackList.getStatus())) {
        criteria.and("status").is(blackList.getStatus());
    }
    query.addCriteria(criteria);
    return query;
}
 
Example 2
Source Project: secure-data-service   Source File: MongoRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<T> findAll(String collectionName, NeutralQuery origNeutralQuery) {

    NeutralQuery neutralQuery = origNeutralQuery == null ? new NeutralQuery() : origNeutralQuery;

    // Enforcing the tenantId query. The rationale for this is all CRUD
    // Operations should be restricted based on tenant.
    this.addDefaultQueryParams(neutralQuery, collectionName);

    // convert the neutral query into a mongo query
    Query mongoQuery = this.queryConverter.convert(collectionName, neutralQuery);

    // always call guideIfTenantAgnostic - this sets threadlocal flag
    if (!guideIfTenantAgnostic(collectionName) && TenantContext.getTenantId() == null) {

        return findAllAcrossTenants(collectionName, mongoQuery);
    } else {
        // find and return an instance
        return findAll(mongoQuery, collectionName);
    }
}
 
Example 3
Source Project: biliob_backend   Source File: CheckInCreditCalculator.java    License: MIT License 6 votes vote down vote up
@Override
public ResponseEntity execute(User user, ObjectId objectId) {
    Boolean isCheckedIn =
            mongoTemplate.exists(new Query(where("name").is(user.getName())), "check_in");
    String userName = user.getName();
    Double credit = user.getCredit();
    if (isCheckedIn) {
        throw new BusinessException(ExceptionEnum.ALREADY_SIGNED);
    } else {
        // 插入已签到集合
        mongoTemplate.insert(new CheckIn(userName), "check_in");

        // update execute status
        Query query = new Query(where("_id").is(objectId));
        Update update = new Update();
        update.set("isExecuted", true);
        mongoTemplate.updateFirst(query, update, "user_record");
    }
    return null;
}
 
Example 4
Source Project: osiris   Source File: MapRepositoryCustomImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void findByIDAppAndQueryTest() throws Exception{
	
	String idApplication = "1";  
	String queryJSON = "{ geometry:{ $geoWithin:{ $centerSphere:[ [20.05,20.01] , 0.05]} } }";	
	Integer pageIndex=5;
	Integer pageSize= 20;
	int skipElementsValue = pageIndex*pageSize;		 
		
	//Fixture		 	    
    Query querySkip=Mockito.mock(Query.class);
    Query queryLimit=Mockito.mock(Query.class);
	PowerMockito.whenNew(BasicQuery.class).withArguments(queryJSON).thenReturn(basicQuery);				
	Mockito.when(basicQuery.skip(skipElementsValue)).thenReturn(querySkip);
	Mockito.when(querySkip.limit(pageSize)).thenReturn(queryLimit);				
	Mockito.when(mongoTemplate.find(queryLimit, Feature.class, collectionMap+idApplication)).thenReturn(features);
	
	//Experimentation
	Collection<Feature> featuresResponse=mapRepositoryCustomImpl.searchIDAppAndQuery(idApplication, queryJSON, pageIndex, pageSize);
	
	//Expectations
	Mockito.verify(mongoTemplate).find(queryLimit, Feature.class, collectionMap+idApplication);
	Assert.assertEquals("Features must be equals", featuresResponse, features);
	
}
 
Example 5
Source Project: konker-platform   Source File: EventSchemaServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ServiceResponse<List<String>> findKnownIncomingChannelsBy(Tenant tenant, Application application, String deviceGuid) {
    ServiceResponse<Device> deviceServiceResponse = deviceRegisterService.getByDeviceGuid(tenant, application, deviceGuid);

    if (deviceServiceResponse.isOk()) {
        List<String> channelList = mongoTemplate.find(Query.query(Criteria.where("deviceGuid").is(deviceGuid)),
                                                      EventSchema.class,
                                                      SchemaType.INCOMING.getCollectionName())
                .stream().map(EventSchema::getChannel).distinct().sorted().collect(Collectors.toList());

        return ServiceResponseBuilder.<List<String>>ok()
            .withResult(channelList).build();
    } else {
        return ServiceResponseBuilder.<List<String>>error()
                .withMessages(deviceServiceResponse.getResponseMessages()).build();
    }
}
 
Example 6
Source Project: attic-rave   Source File: MongoDbRegionRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getAll(){
    String id = "1111L";
    String id2 = "2222L";
    Page page = new PageImpl("1234L");
    List<Page> pages = Lists.newArrayList();
    List<Region> regions = Lists.newArrayList();
    Region region = new RegionImpl(id);
    Region region2 = new RegionImpl(id2);
    regions.add(region);
    regions.add(region2);
    pages.add(page);
    page.setRegions(regions);


    Query q = new Query();
    expect(template.find(q)).andReturn(pages);
    replay(template);

    List<Region> result = repo.getAll();
    assertNotNull(result);
    assertThat(result, is(equalTo(regions)));
    assertThat(result.size(), equalTo(2));
}
 
Example 7
Source Project: attic-rave   Source File: MongoDbRegionWidgetRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<RegionWidget> getAll(){
    Query q = new Query();

    List<Page> allPages = template.find(q);

    List<RegionWidget> regionWidgets = new ArrayList<RegionWidget>();

    for(Page page: allPages){
        List<Region> regions = page.getRegions();
        if(regions != null){
            for(Region region : regions) {
                List<RegionWidget> rws = region.getRegionWidgets();
                if(rws != null){
                    for(RegionWidget rw : rws){
                        regionWidgets.add(rw);
                    }
                }
            }
        }

    }

    return regionWidgets;
}
 
Example 8
Source Project: secure-data-service   Source File: PurgeProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPurgingSystemCollections() throws Exception {

    RangedWorkNote workNote = RangedWorkNote.createSimpleWorkNote(BATCHJOBID);

    Exchange ex = Mockito.mock(Exchange.class);
    Message message = Mockito.mock(Message.class);
    Mockito.when(ex.getIn()).thenReturn(message);
    Mockito.when(message.getBody(RangedWorkNote.class)).thenReturn(workNote);

    NewBatchJob job = new NewBatchJob();
    job.setProperty("tenantId", "SLI");
    Mockito.when(mockBatchJobDAO.findBatchJobById(BATCHJOBID)).thenReturn(job);

    Set<String> collectionNames = new HashSet<String>();
    collectionNames.add("system.js");
    collectionNames.add("system.indexes");

    Mockito.when(mongoTemplate.getCollectionNames()).thenReturn(collectionNames);

    purgeProcessor.process(ex);

    Mockito.verify(mongoTemplate, Mockito.never()).remove(Mockito.any(Query.class), Mockito.eq("system.js"));
}
 
Example 9
@Override
public Page<User> queryPage(SysRole role, UserQueryRequest queryRequest) {
	int start = queryRequest.getStart();
	int limit = queryRequest.getLimit();
	Query query = new Query();
	query.addCriteria(Criteria.where("roles").in(role));
	if (!StringUtils.isEmpty(queryRequest.getUsername())) {
		query.addCriteria(Criteria.where("username").regex(queryRequest.getUsername()));
	}
	query.addCriteria(Criteria.where("deleted").ne(true));

	PageRequest pageable = new PageRequest(start, limit, new Sort(Sort.Direction.DESC, "username"));
	query.with(pageable);
	long count = mongoTemplate.count(query, User.class);
	List<User> list = mongoTemplate.find(query, User.class);

	return new PageImpl<>(list, pageable, count);
}
 
Example 10
Source Project: hmily   Source File: MongoCompensationServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Boolean updateRetry(final String id, final Integer retry, final String appName) {
    if (StringUtils.isBlank(id) || StringUtils.isBlank(appName) || Objects.isNull(retry)) {
        return Boolean.FALSE;
    }
    final String mongoTableName = RepositoryPathUtils.buildMongoTableName(appName);
    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(id));
    Update update = new Update();
    update.set("lastTime", DateUtils.getCurrentDateTime());
    update.set("retriedCount", retry);
    final UpdateResult updateResult = mongoTemplate.updateFirst(query, update,
            MongoAdapter.class, mongoTableName);
    if (updateResult.getModifiedCount() <= 0) {
        throw new HmilyRuntimeException("更新数据异常!");
    }
    return Boolean.TRUE;
}
 
Example 11
Source Project: attic-rave   Source File: MongoDbWidgetRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getByStatusAndTypeAndFreeTextSearch_null(){
    int offset = 2;
    int pageSize = 10;
    String type = "type";
    String searchTerm = "test" ;
    List<Widget> widgets = Lists.newArrayList();
    Widget w = new WidgetImpl();
    Widget w2 = new WidgetImpl();
    widgets.add(w);
    widgets.add(w2);

    expect(template.find(isA(Query.class))).andReturn(widgets);
    replay(template);

    List<Widget> result = repo.getByStatusAndTypeAndFreeTextSearch(WidgetStatus.PUBLISHED, type, searchTerm, offset, pageSize);
    assertNotNull(result);

}
 
Example 12
@Test
public void testDeleteEntityAndContainerDoc() {
    ContainerDocumentAccessor cda = Mockito.spy(testAccessor);
    Map<String, Object> updateDocCriteria = new HashMap<String, Object>();
    updateDocCriteria.put("event", "Tardy");
    DBObject pullObject = BasicDBObjectBuilder.start().push("$pull").add("body.attendanceEvent", updateDocCriteria).get();
    DBObject resultingAttendanceEvent = createResultAttendance(null);

    NeutralSchema attendanceSchema = createMockAttendanceSchema();

    when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection);
    when(mockCollection.findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(),
            Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false))).thenReturn(resultingAttendanceEvent);
    when(mongoTemplate.findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE))).thenReturn(entity); // just return something non-null
    when(schemaRepo.getSchema(EntityNames.ATTENDANCE)).thenReturn(attendanceSchema);

    boolean result = cda.deleteContainerNonSubDocs(entity);

    Mockito.verify(mockCollection, Mockito.times(1)).findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(),
            Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false));
    Mockito.verify(mongoTemplate, Mockito.times(1)).findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE));
    assertTrue(result);
}
 
Example 13
Source Project: biliob_backend   Source File: AuthorGroupServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public Result<DeleteResult> deleteAuthorList(String objectId) {
    ObjectId userId = UserUtils.getUserId();
    if (userId == null) {
        return new Result<>(ResultEnum.HAS_NOT_LOGGED_IN);
    }
    AuthorGroup authorGroup = this.getAuthorList(objectId);

    if (authorGroup == null) {
        return new Result<>(ResultEnum.LIST_NOT_FOUND);
    }
    if (authorGroup.getMaintainer().getId().toHexString().equals(userId.toHexString())) {
        return new Result<>(ResultEnum.SUCCEED, mongoTemplate.remove(Query.query(Criteria.where("_id").is(objectId)), AuthorGroup.class));
    } else {
        return new Result<>(ResultEnum.EXECUTE_FAILURE);
    }
}
 
Example 14
Source Project: jstarcraft-core   Source File: MongoAccessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> long countIntersection(Class<T> clazz, Map<String, Object> condition) {
	MongoMetadata metadata = metadatas.get(clazz);
	final Iterator<Entry<String, Object>> conditionIterator = condition.entrySet().iterator();
	Criteria criteria = Criteria.where(MongoMetadata.mongoId).exists(true);
	Criteria[] andCriterias = new Criteria[condition.size()];
	int index = 0;
	while (conditionIterator.hasNext()) {
		Entry<String, Object> keyValue = conditionIterator.next();
		String key = keyValue.getKey();
		Object value = keyValue.getValue();
		if (metadata.getPrimaryName().equals(key)) {
			key = MongoMetadata.mongoId;
		}
		andCriterias[index++] = Criteria.where(key).is(value);
	}
	Query query = Query.query(criteria.andOperator(andCriterias));
	return template.count(query, metadata.getOrmName());
}
 
Example 15
@Test
public void save_Null(){
    PageLayout item1 = new MongoDbPageLayout();
    item1.setCode("blah1");
    item1.setNumberOfRegions((long)123);
    item1.setRenderSequence((long)432);
    item1.setUserSelectable(true);
    MongoDbPageLayout toSave = new MongoDbPageLayout();
    expect(template.findOne(new Query(where("code").is(item1.getCode())), pageLayoutRepository.CLASS, CollectionNames.PAGE_LAYOUT_COLLECTION)).andReturn(toSave);
    template.save(isA(MongoDbPageLayout.class), eq(CollectionNames.PAGE_LAYOUT_COLLECTION));
    expectLastCall();
    replay(template);

    PageLayout saved = pageLayoutRepository.save(item1);

    assertThat(saved.getCode(), is(sameInstance(item1.getCode())));
    assertThat(saved.getNumberOfRegions(), is(sameInstance(item1.getNumberOfRegions())));
    assertThat(saved.getRenderSequence(), is(sameInstance(item1.getRenderSequence())));
    assertThat(saved.isUserSelectable(), is(sameInstance(item1.isUserSelectable())));
}
 
Example 16
Source Project: biliob_backend   Source File: UserCommentServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public ResponseEntity<Result<String>> likeComment(String commentId) {

    User user = UserUtils.getUser();
    if (mongoTemplate.exists(Query.query(Criteria.where("likeList").is(user.getId()).and("_id").is(commentId)), Comment.class)) {
        return ResponseEntity.badRequest().body(new Result<>(ResultEnum.ALREADY_LIKE));
    }
    Comment comment = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(commentId)), Comment.class);
    if (comment == null) {
        return ResponseEntity.badRequest().body(new Result<>(ResultEnum.EXECUTE_FAILURE));
    }
    ObjectId commentPublisherId = comment.getUserId();

    User publisher = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(commentPublisherId)), User.class);
    return creditHandle.doCreditOperation(user, CreditConstant.LIKE_COMMENT, () -> {
        mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(commentId)), new Update().addToSet("likeList", user.getId()).inc("like", 1), Comment.class);
        creditHandle.doCreditOperation(publisher, CreditConstant.BE_LIKE_COMMENT, () -> commentId);
        return commentId;
    });

}
 
Example 17
Source Project: hmily   Source File: MongoCoordinatorRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HmilyTransaction findById(final String id) {
    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(id));
    MongoAdapter cache = template.findOne(query, MongoAdapter.class, collectionName);
    return buildByCache(Objects.requireNonNull(cache));
}
 
Example 18
Source Project: microservice-recruit   Source File: IdUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取下一个id并更新表
 * @param collName
 * @param mongo
 * @return
 */
public static Long getNextIdAndUpdate(String collName, MongoTemplate mongo) {
    Query query = new Query(Criteria.where("collName").is(collName));
    Update update = new Update();
    update.inc("seqId", 1);
    FindAndModifyOptions options = new FindAndModifyOptions();
    options.upsert(true);
    options.returnNew(true);
    SeqInfo seq = mongo.findAndModify(query, update, options, SeqInfo.class);
    return seq.getSeqId();
}
 
Example 19
Source Project: biliob_backend   Source File: AuthorAchievementServiceImpl.java    License: MIT License 5 votes vote down vote up
private void insertAchievementIfNotExist(AuthorDailyTrend data, AuthorAchievementEnum achievementEnum, Long value) {
    boolean wasGotten = mongoTemplate.exists(
            Query.query(
                    Criteria.where("author.mid").is(data.getMid())
                            .and("code").is(achievementEnum.getId())
                            .and("date").is(data.getDatetime())), Author.Achievement.class);
    if (!wasGotten) {
        logger.info("添加成就: {} {}", data.getMid(), achievementEnum.getName());
        mongoTemplate.save(new Author.Achievement(achievementEnum, data.getMid(), value, data.getDatetime()));
    }
}
 
Example 20
Source Project: FEBS-Cloud   Source File: PageableExecutionUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static <FEBS> Flux<FEBS> getPages(Query query, QueryRequest request, Class<FEBS> clazz,
                                         ReactiveMongoTemplate template) {
    Sort sort = Sort.by("id").descending();
    if (StringUtils.isNotBlank(request.getField()) && StringUtils.isNotBlank(request.getOrder())) {
        sort = FebsConstant.ORDER_ASC.equals(request.getOrder()) ?
                Sort.by(request.getField()).ascending() :
                Sort.by(request.getField()).descending();
    }
    Pageable pageable = PageRequest.of(request.getPageNum(), request.getPageSize(), sort);
    return template.find(query.with(pageable), clazz);
}
 
Example 21
private void setFindEachReturn(List<Entity> studentEntities) {
    Mockito.when(repo.findEach(eq(EntityNames.STUDENT), argThat(new BaseMatcher<Query>() {
        @Override
        public boolean matches(Object item) {
            Query q = (Query) item;
            return q.getQueryObject().get(DisciplineIncidentContextResolver.DISCIPLINE_INCIDENT_ID).equals("123_id");
        }

        @Override
        public void describeTo(Description description) {
        }
    }))).thenReturn(studentEntities.iterator());
}
 
Example 22
@Override
public TransactionRecover findById(final String id) {
    Query query = new Query();
    query.addCriteria(new Criteria("transId").is(id));
    MongoAdapter cache = template.findOne(query, MongoAdapter.class, collectionName);
    return buildByCache(cache);
}
 
Example 23
@Test
public void getByUserId() {
    List<MongoDbActivityStreamsEntry> result = Lists.newArrayList();
    expect(template.find(Query.query(Criteria.where("actor._id").is(ID)), ENTITY_CLASS, ACTIVITIES)).andReturn(result);
    replay(template);

    List<ActivityStreamsEntry> entries = repository.getByUserId(ID);
    assertThat((Object)entries, is(sameInstance((Object)result)));
}
 
Example 24
Source Project: scava   Source File: SimilarityManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void deleteRelations(ISimilarityCalculator simCalculator) {
	Query q2 = new Query(Criteria.where("type.name").is(simCalculator.getSimilarityName()));
	List<Relation> arts = mongoOperations.find(q2, Relation.class);
	relationRepository.delete(arts);

}
 
Example 25
Source Project: Almost-Famous   Source File: ActorBagDaoImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void updateActorBag(ActorBag pack) {
    Query query = new Query(Criteria.where("rid").is(pack.getRid()));
    Update update = new Update()
            .set("packages", pack.getPackages())
            .set("buyCount", pack.getBuyCount())
            .set("selectCount", pack.getSelectCount())
            .set("probability", pack.getProbability());
    gameMongoTemplate.findAndModify(query, update, getEntityClass());
}
 
Example 26
@Override
public Page<AuthEvent> queryPage(AuthEventQueryRequest queryRequest) {

	int start = queryRequest.getStart();
	int limit = queryRequest.getLimit();
	Query query = buildQuery(queryRequest);

	PageRequest pageable = new PageRequest(start, limit, new Sort(Sort.Direction.DESC, "loginAt"));
	query.with(pageable);
	long count = mongoTemplate.count(query, AuthEvent.class);
	List<AuthEvent> list = mongoTemplate.find(query, AuthEvent.class);

	return new PageImpl<>(list, pageable, count);
}
 
Example 27
Source Project: attic-rave   Source File: MongoDbPageRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int deletePages(String userId, String pageType) {
    Query query = query(where("pageType").is(pageType).andOperator(where("ownerId").is(userId)));
    int count = (int)template.count(query);
    template.remove(query);
    return count;
}
 
Example 28
@Override
public MongoClientDetails findByClientId(final String clientId) {
    final Query query = Query.query(Criteria.where(ID).is(clientId));
    final MongoClientDetails mongoClientDetails = mongoTemplate.findOne(query, MongoClientDetails.class);
    if (mongoClientDetails == null) {
        throw new IllegalArgumentException("No valid client id");
    }
    return mongoClientDetails;
}
 
Example 29
Source Project: tutorials   Source File: MongoTemplateQueryLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenSavingUserWithoutSettingAge_thenAgeIsSetByDefault() {
    final User user = new User();
    user.setName("Alex");
    mongoTemplate.insert(user);

    assertThat(mongoTemplate.findOne(Query.query(Criteria.where("name").is("Alex")), User.class).getAge(), is(0));
}
 
Example 30
Source Project: biliob_backend   Source File: SiteServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public Map<String, Long> getVideoCount() {
    Long videoFocusCount =
            mongoTemplate.count(new Query(Criteria.where("focus").is(true)), "video");
    Long videoNotFocusCount =
            mongoTemplate.count(new Query(Criteria.where("focus").is(false)), "video");
    Map<String, Long> videoResult = new HashMap<>(2);
    videoResult.put("focusCount", videoFocusCount);
    videoResult.put("count", videoFocusCount + videoNotFocusCount);
    return videoResult;
}