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

The following examples show how to use org.springframework.data.mongodb.core.query.Query. 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 File: BlackListServiceImpl.java    From FEBS-Cloud with 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 File: MongoDbRegionWidgetRepository.java    From attic-rave with 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 #3
Source File: MongoDbRegionRepositoryTest.java    From attic-rave with 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 #4
Source File: EventSchemaServiceImpl.java    From konker-platform with 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 #5
Source File: MongoDbWidgetRepositoryTest.java    From attic-rave with 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 #6
Source File: ContainerDocumentAccessorTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: MapRepositoryCustomImplTest.java    From osiris with 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 #8
Source File: AuthorGroupServiceImpl.java    From biliob_backend with 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 #9
Source File: MongoCompensationServiceImpl.java    From hmily with 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 #10
Source File: CheckInCreditCalculator.java    From biliob_backend with 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 #11
Source File: MongoAccessor.java    From jstarcraft-core with 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 #12
Source File: MongoDbPageLayoutRepositoryTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: UserRepositoryImpl.java    From spring-backend-boilerplate with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: MongoRepository.java    From secure-data-service with 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 #15
Source File: PurgeProcessorTest.java    From secure-data-service with 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 #16
Source File: UserCommentServiceImpl.java    From biliob_backend with 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 File: TracerScheduler.java    From biliob_backend with MIT License 5 votes vote down vote up
@Scheduled(cron = "0 0/5 * * * ?")
@Async
public void checkDeadTask() {
    logger.info("检查死亡爬虫");
    Date deadDate = getDeadDate();
    mongoTemplate.updateMulti(
            Query.query(
                    Criteria.where("update_time").lt(deadDate).and("status").ne(TracerStatus.FINISHED)),
            Update.update("status", TracerStatus.DEAD).set("msg", "该任务已离线"),
            TracerTask.class);
}
 
Example #18
Source File: TestMongoXMLConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateMulti() {
    final Query query = new Query();
    final Update update = Update.update("title", "Using multi");
    mongoOperations.updateMulti(query, update, Book.class);
    // Calling update using query: { } and update: { "$set" : { "title" : "Using multi"}} in collection: book
}
 
Example #19
Source File: CustomRepositoryQueryImpl.java    From hygieia-core with Apache License 2.0 5 votes vote down vote up
@Override
public List<CollectorItem> findCollectorItemsBySubsetOptions(ObjectId id, Map<String, Object> allOptions, Map<String, Object> uniqueOptions,Map<String, Object> uniqueOptionsFromCollector) {
    Criteria c = Criteria.where("collectorId").is(id);
    uniqueOptions.values().removeIf(d-> d.equals(null) || ((d instanceof String) && StringUtils.isEmpty((String) d)));
    for (Map.Entry<String, Object> e : allOptions.entrySet()) {
        if (uniqueOptionsFromCollector.containsKey(e.getKey())) {
            c = getCriteria(uniqueOptions, c, e);
        }
    }
    List<CollectorItem> items =  template.find(new Query(c), CollectorItem.class);
    return items;
}
 
Example #20
Source File: AuthEventRepositoryImpl.java    From spring-backend-boilerplate with Apache License 2.0 5 votes vote down vote up
private Query buildQuery(AuthEventQueryRequest request) {
	Query query = new Query();

	if (!StringUtils.isEmpty(request.getRealm())) {
		query.addCriteria(Criteria.where("realm").is(request.getRealm()));
	}

	if (!StringUtils.isEmpty(request.getUsername())) {
		query.addCriteria(Criteria.where("username").regex(request.getUsername()));
	}

	if (request.getBeginDate() != null && request.getEndDate() != null) {
		query.addCriteria(new Criteria().andOperator(Criteria.where("loginAt").gte(request.getBeginDate()),
													 Criteria.where("loginAt").lte(request.getEndDate())));
	}
	else if (request.getBeginDate() != null) {
		query.addCriteria(Criteria.where("loginAt").gte(request.getBeginDate()));
	}
	else if (request.getEndDate() != null) {
		query.addCriteria(Criteria.where("loginAt").lte(request.getEndDate()));
	}

	Boolean succeed = request.getSucceed();
	if (succeed != null) {
		query.addCriteria(Criteria.where("succeed").is(succeed.booleanValue()));
	}

	return query;
}
 
Example #21
Source File: BatchJobMongoDATest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Test when the last result chunk falls on the limit boundary
 */
@Test
public void testGetBatchJobErrorsLimitAlignedResults() {

    int errorIndex = START_INDEX;
    List<Error> errorsReturnedFirst = createErrorsFromIndex(errorIndex, RESULTLIMIT);
    errorIndex += errorsReturnedFirst.size();
    List<Error> errorsReturnedSecond = createErrorsFromIndex(errorIndex, RESULTLIMIT);
    errorIndex += errorsReturnedSecond.size();

    when(batchJobMongoTemplate.find((Query) any(), eq(Error.class), eq(BATCHJOB_ERROR_COLLECTION)))
            .thenReturn(errorsReturnedFirst)     // return the first time this method call is matched
            .thenReturn(errorsReturnedSecond)    // return the second time this method call is matched
            .thenReturn(Collections.<Error>emptyList()); // return the last time this method call is matched - should NOT be called
    when(batchJobMongoTemplate.getCollection(eq(BATCHJOB_ERROR_COLLECTION))).thenReturn(mockedCollection);
    when(mockedCollection.count(Matchers.isA(DBObject.class))).thenReturn((long) errorIndex);

    Iterable<Error> errorIterable = mockBatchJobMongoDA.getBatchJobErrors(BATCHJOBID, RESOURCEID, FaultType.TYPE_ERROR, RESULTLIMIT);

    int iterationCount = START_INDEX;

    for (Error error : errorIterable) {
        assertOnErrorIterableValues(error, iterationCount);
        iterationCount++;
    }

    // Check we queried the db once.
    verify(batchJobMongoTemplate, times(1)).find((Query) any(), eq(Error.class), eq(BATCHJOB_ERROR_COLLECTION));
}
 
Example #22
Source File: MongoEntityRepository.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * @Deprecated "This is a deprecated method that should only be used by the ingestion ID
 *             Normalization code.
 *             It is not tenant-safe meaning clients of this method must include tenantId in the
 *             metaData block"
 */
@Override
@Deprecated
@MigrateEntityCollection
public Iterable<Entity> findByQuery(String collectionName, Query origQuery, int skip, int max) {
    Query query = origQuery == null ? new Query() : origQuery;

    query.skip(skip).limit(max);

    if (subDocs.isSubDoc(collectionName)) {
        return subDocs.subDoc(collectionName).findAll(query);
    }

    return findByQuery(collectionName, query);
}
 
Example #23
Source File: AuthorGroupServiceImpl.java    From biliob_backend with MIT License 5 votes vote down vote up
@Override
public Result<?> addAuthorToGroup(String gid, Long mid) {
    ObjectId groupId = new ObjectId(gid);
    ObjectId userId = UserUtils.getUserId();
    if (!hasPermission(userId, groupId)) {
        return new Result<>(ResultEnum.PERMISSION_DENIED);
    }
    if (!mongoTemplate.exists(Query.query(Criteria.where("mid").is(mid)), Author.class)) {
        return new Result<>(ResultEnum.NOT_OBSERVING);
    }
    mongoTemplate.upsert(Query.query(Criteria.where("mid").is(mid).and("gid").is(groupId)), Update.update("mid", mid).set("gid", new ObjectId(gid)), AuthorGroupItem.class);
    addUpdateLog(userId, groupId, String.format("添加mid为%s的UP主", mid));
    return new Result<>(ResultEnum.SUCCEED);
}
 
Example #24
Source File: MongoAccessor.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> void iterateIntersection(StorageIterator<T> iterator, Class<T> clazz, Map<String, Object> condition, StoragePagination pagination) {
	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));
	if (pagination != null) {
		query.skip(pagination.getFirst());
		query.limit(pagination.getSize());
	}
	try (CloseableIterator<T> stream = template.stream(query, clazz, metadata.getOrmName())) {
		while (stream.hasNext()) {
			try {
				// TODO 需要考虑中断
				final T object = stream.next();
				iterator.iterate(object);
			} catch (Throwable throwable) {
				throw new StorageQueryException(throwable);
			}
		}
	}
}
 
Example #25
Source File: MongoQueryConverterTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testIncludeFieldConvert() {
    NeutralQuery neutralQuery = new NeutralQuery();
    neutralQuery.setIncludeFieldString("populationServed,uniqueSectionCode");

    Query query = mongoQueryConverter.convert("section", neutralQuery);
    assertNotNull("Should not be null", query);
    DBObject obj = query.getFieldsObject();
    assertNotNull("Should not be null", obj);
    assertEquals("Should match", 1, obj.get("body.populationServed"));
    assertEquals("Should match", 1, obj.get("body.uniqueSectionCode"));
}
 
Example #26
Source File: AuthorUtil.java    From biliob_backend with MIT License 5 votes vote down vote up
public AuthorRankData getRankData(Author author) {
    Long archiveViewRank = null != author.getcArchiveView() && author.getcArchiveView() != 0 ? mongoTemplate.count(Query.query(Criteria.where("cArchive_view").gte(author.getcArchiveView())), "author") : -1;
    Long articleViewRank = null != author.getcArticleView() && author.getcArticleView() != 0 ? mongoTemplate.count(Query.query(Criteria.where("cArticle_view").gte(author.getcArticleView())), "author") : -1;
    Long likeRank = null != author.getcLike() && author.getcLike() != 0 ? mongoTemplate.count(Query.query(Criteria.where("cLike").gte(author.getcLike())), "author") : -1;
    Long fansRank = null != author.getcFans() && author.getcFans() != 0 ? mongoTemplate.count(Query.query(Criteria.where("cFans").gte(author.getcFans())), "author") : -1;
    return new AuthorRankData(archiveViewRank, articleViewRank, likeRank, fansRank);
}
 
Example #27
Source File: MongoClientDetailsRepositoryImpl.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Override
public boolean updateClientSecret(final String clientId,
                                  final String newSecret) {
    final Query query = Query.query(Criteria.where(ID).is(clientId));

    final Update update = Update.update(CLIENT_SECRET, newSecret);

    final UpdateResult updateResult = mongoTemplate.updateFirst(query, update, MongoClientDetails.class);

    return updateResult.wasAcknowledged();
}
 
Example #28
Source File: UserItemPreferenceUpdateListener.java    From AppStash with Apache License 2.0 5 votes vote down vote up
@Override
public void onAfterSave(Order order, DBObject dbo) {
    ObjectId userId = order.getUserId();
    for (OrderItem item : order.getOrderItems()) {
        String articleId = item.getProduct().getArticleId();

        Criteria criteria = Criteria.where("userId").is(userId)
                .and("articleId").is(articleId);
        Update update = Update.update("created_at", new Date()).inc("preference", 1);

        mongoOperations.upsert(Query.query(criteria), update, UserItemPreference.class);
    }
}
 
Example #29
Source File: MongoGenericDaoUtil.java    From howsun-javaee-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 定制字段
 * @param query
 * @param fields 指定的字段,多个须以逗号隔开,支持*号
 */
public static void bindFields(Query query, String fields){
	if(Strings.hasLengthBytrim(fields) && !"*".equals(fields)){
		String[] fs = fields.split(",");
		for(String f : fs){
			query.fields().include(f);
		}
	}
}
 
Example #30
Source File: FlowUserDaoImpl.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String flowId, Set<String> emails) {
    Query q = Query.query(Criteria.where("_id").is(flowId));

    Update u = new Update();
    u.pullAll("users", emails.toArray());

    mongoOps.updateFirst(q, u, FlowUsers.class);
}