Example usage for org.springframework.data.mongodb.core.query Criteria where

List of usage examples for org.springframework.data.mongodb.core.query Criteria where

Introduction

In this page you can find the example usage for org.springframework.data.mongodb.core.query Criteria where.

Prototype

public static Criteria where(String key) 

Source Link

Document

Static factory method to create a Criteria using the provided key

Usage

From source file:io.cos.cas.adaptors.mongodb.OpenScienceFrameworkAuthenticationHandler.java

/**
 * Authenticates a Open Science Framework credential.
 *
 * @param credential the credential object bearing the username, password, etc...
 *
 * @return HandlerResult resolved from credential on authentication success or null if no principal could be resolved
 * from the credential.//from   www.  j  a  v  a2s .  c  o m
 *
 * @throws GeneralSecurityException On authentication failure.
 * @throws PreventedException On the indeterminate case when authentication is prevented.
 */
protected final HandlerResult authenticateInternal(final OpenScienceFrameworkCredential credential)
        throws GeneralSecurityException, PreventedException {

    final String username = credential.getUsername().toLowerCase();
    final String plainTextPassword = credential.getPassword();
    final String verificationKey = credential.getVerificationKey();
    final String oneTimePassword = credential.getOneTimePassword();

    final OpenScienceFrameworkUser user = this.mongoTemplate.findOne(new Query(new Criteria()
            .orOperator(Criteria.where("emails").is(username), Criteria.where("username").is(username))),
            OpenScienceFrameworkUser.class);

    if (user == null) {
        throw new AccountNotFoundException(username + " not found with query");
    }

    Boolean validPassphrase = Boolean.FALSE;
    if (credential.isRemotePrincipal()) {
        // remote principal's are already verified by a third party (in our case a third party SAML authentication).
        validPassphrase = Boolean.TRUE;
    } else if (verificationKey != null && verificationKey.equals(user.verificationKey)) {
        // verification key can substitute as a temporary password.
        validPassphrase = Boolean.TRUE;
    } else if (BCrypt.checkpw(plainTextPassword, user.password)) {
        validPassphrase = Boolean.TRUE;
    }
    if (!validPassphrase) {
        throw new FailedLoginException(username + " invalid verification key or password");
    }

    final TimeBasedOneTimePassword timeBasedOneTimePassword = this.mongoTemplate.findOne(new Query(Criteria
            .where("owner").is(user.id).and("isConfirmed").is(Boolean.TRUE).and("deleted").is(Boolean.FALSE)),
            TimeBasedOneTimePassword.class);

    if (timeBasedOneTimePassword != null && timeBasedOneTimePassword.totpSecret != null) {
        if (oneTimePassword == null) {
            throw new OneTimePasswordRequiredException("Time-based One Time Password required");
        }
        try {
            final Long longOneTimePassword = Long.valueOf(oneTimePassword);
            if (!TotpUtils.checkCode(timeBasedOneTimePassword.getTotpSecretBase32(), longOneTimePassword,
                    TOTP_INTERVAL, TOTP_WINDOW)) {
                throw new OneTimePasswordFailedLoginException(
                        username + " invalid time-based one time password");
            }
        } catch (final Exception e) {
            throw new OneTimePasswordFailedLoginException(username + " invalid time-based one time password");
        }
    }

    // Validate basic information such as username/password and a potential One-Time Password before
    // providing any indication of account status.
    if (!user.isRegistered) {
        throw new LoginNotAllowedException(username + " is not registered");
    }
    if (!user.isClaimed) {
        throw new LoginNotAllowedException(username + " is not claimed");
    }
    if (user.isMerged()) {
        throw new LoginNotAllowedException("Cannot log in to a merged user " + username);
    }
    if (user.isDisabled()) {
        throw new AccountDisabledException(username + " is disabled");
    }
    if (!user.isActive()) {
        throw new LoginNotAllowedException(username + " is not active");
    }

    final Map<String, Object> attributes = new HashMap<>();
    attributes.put("username", user.username);
    attributes.put("givenName", user.givenName);
    attributes.put("familyName", user.familyName);
    return createHandlerResult(credential, this.principalFactory.createPrincipal(user.id, attributes), null);
}

From source file:br.com.ezequieljuliano.argos.persistence.LoggerDAO.java

public List<LoggerEntityCount> groupByEntityUsingUserAndOccurrence(User user, Date startDate, Date endDate) {
    Criteria criteria = Criteria.where("entity._id").in(findEntityObjectIdsByUser(user)).andOperator(
            Criteria.where("occurrence").lte(endDate), Criteria.where("occurrence").gte(startDate));

    GroupByResults<LoggerEntityCount> results = getMongoOperations().group(criteria, Logger.COLLECTION_NAME,
            GroupBy.key("entity").initialDocument("{ count: 0 }")
                    .reduceFunction("function(doc, prev) { prev.count += 1 }"),
            LoggerEntityCount.class);

    List<LoggerEntityCount> counts = new ArrayList<LoggerEntityCount>();
    for (LoggerEntityCount entity : results) {
        counts.add(entity);//www .  j a va  2  s  . co  m
    }

    return counts;
}

From source file:example.springdata.mongodb.aggregation.SpringBooksIntegrationTests.java

/**
 * Run a multi-faceted aggregation to get buckets by price (1-10, 10-50, 50-100 EURO) and by the first letter of the
 * author name.//from www.java2 s  . c o  m
 */
@Test
@SuppressWarnings("unchecked")
public void shouldCategorizeInMultipleFacetsByPriceAndAuthor() {

    Aggregation aggregation = newAggregation( //
            match(Criteria.where("volumeInfo.authors").exists(true).and("volumeInfo.publisher").exists(true)),
            facet() //
                    .and(match(Criteria.where("saleInfo.listPrice").exists(true)), //
                            replaceRoot("saleInfo"), //
                            bucket("listPrice.amount") //
                                    .withBoundaries(1, 10, 50, 100))
                    .as("prices") //

                    .and(unwind("volumeInfo.authors"), //
                            replaceRoot("volumeInfo"), //
                            match(Criteria.where("authors").not().size(0)), //
                            project() //
                                    .andExpression("substrCP(authors, 0, 1)").as("startsWith") //
                                    .and("authors").as("author"), //
                            bucketAuto("startsWith", 10) //
                                    .andOutput("author").push().as("authors") //
                    ).as("authors"));

    AggregationResults<Document> result = operations.aggregate(aggregation, "books", Document.class);

    Document uniqueMappedResult = result.getUniqueMappedResult();

    assertThat((List<Object>) uniqueMappedResult.get("prices")).hasSize(3);
    assertThat((List<Object>) uniqueMappedResult.get("authors")).hasSize(8);
}

From source file:com.gongpingjia.carplay.official.service.impl.OfficialApproveServiceImpl.java

@Override
public List<AuthenticationHistory> buildAuthHistory(String applicationId) {
    LOG.debug("ApplicationId:{}", applicationId);
    return historyDao.find(Query.query(Criteria.where("applicationId").is(applicationId))
            .with(new Sort(new Sort.Order(Sort.Direction.DESC, "authTime"))));
}

From source file:com.gongpingjia.carplay.service.impl.ActivityServiceImpl.java

private List<String> buildNearByUsers(User user, String activityId) {
    LOG.debug("Send nearby user message, sendUser:{}", user.getUserId());
    PushInfo pushInfo = pushInfoDao.findOne(Query.query(Criteria.where("sendUserId").is(user.getUserId())));
    if (pushInfo != null) { //??
        LOG.info("User:{} has already send push once today", user.getUserId());
        return new ArrayList<>(0);
    }/*from   w  w w  .j av a  2 s  .  co  m*/

    //??
    Double distance = Double.parseDouble(PropertiesUtil.getProperty("carplay.nearby.distance.limit", "6000")); //??
    Set<String> subUserIdSet = getSubscribeUsers(user);
    LOG.debug("Get nearby users");
    List<User> nearbyUserList = userDao.find(Query.query(Criteria.where("landmark")
            .near(new Point(user.getLandmark().getLongitude(), user.getLandmark().getLatitude()))
            .maxDistance(distance * 180 / DistanceUtil.EARTH_RADIUS).and("deleteFlag").is(false)));
    Map<String, User> userMap = new HashMap<>(nearbyUserList.size());
    for (User item : nearbyUserList) {
        if (item.getUserId().equals(user.getUserId())) {
            continue;//
        }
        if (subUserIdSet.contains(item.getUserId())) {
            continue;//??????
        }
        userMap.put(item.getUserId(), item);
    }

    return buildEmchatNames(user, nearbyUserList, userMap, activityId);
}

From source file:com.traffitruck.service.MongoDAO.java

public void deleteLoadById(String id, String username) {
    Query query = new Query().addCriteria(Criteria.where("_id").is(id))
            .addCriteria(Criteria.where("username").is(username));
    mongoTemplate.remove(query, Load.class);
}

From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogService.java

@Override
public ShsMessage acknowledgeCorrelatedMessages(ShsMessage shsMessage) {

    DataPart dp = shsMessage.getDataParts().get(0);

    ShsManagement shsManagement = null;/*from  ww w . java2  s .c om*/
    try {
        shsManagement = marshaller.unmarshal(dp.getDataHandler().getInputStream());
    } catch (Exception e) {
        throw new RuntimeException("Failed to unmarshal SHS confirm message", e);
    }
    if (shsManagement != null) {
        if (shsManagement.getConfirmation() != null) {
            Criteria criteria = Criteria.where("label.corrId").is(shsManagement.getCorrId())
                    .and("label.content.contentId").is(shsManagement.getContentId()).and("label.sequenceType")
                    .ne(SequenceType.ADM);

            Query query = Query.query(criteria);
            List<ShsMessageEntry> list = mongoTemplate.find(query, ShsMessageEntry.class);
            for (ShsMessageEntry relatedEntry : list) {

                relatedEntry.setAcknowledged(true);
                update(relatedEntry);
            }
        }
    }

    return shsMessage;
}

From source file:br.com.ezequieljuliano.argos.persistence.LoggerDAO.java

public List<LoggerHostCount> groupByHostUsingUserAndOccurrence(User user, Date startDate, Date endDate) {
    Criteria criteria = Criteria.where("entity._id").in(findEntityObjectIdsByUser(user)).andOperator(
            Criteria.where("occurrence").lte(endDate), Criteria.where("occurrence").gte(startDate));

    GroupByResults<LoggerHostCount> results = getMongoOperations().group(criteria, Logger.COLLECTION_NAME,
            GroupBy.key("host").initialDocument("{ count: 0 }")
                    .reduceFunction("function(doc, prev) { prev.count += 1 }"),
            LoggerHostCount.class);

    List<LoggerHostCount> counts = new ArrayList<LoggerHostCount>();
    for (LoggerHostCount host : results) {
        counts.add(host);/*from ww  w .  jav  a 2s  .  c o  m*/
    }

    return counts;
}

From source file:com.traffitruck.service.MongoDAO.java

public void deleteLoadByAdmin(String id) {
    Query query = new Query().addCriteria(Criteria.where("_id").is(id));
    mongoTemplate.remove(query, Load.class);
}

From source file:net.cit.tetrad.rrd.dao.DataAccessObjectForMongoImpl.java

public List<Critical> readCriticalList(int deviceIdx) {
    List<Critical> criticalInfo = null;
    try {//  w w  w . jav a2  s .  c  o  m
        criticalInfo = operations.find(new Query(Criteria.where(ColumnConstent.DEVICECODE).is(deviceIdx)),
                Critical.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return criticalInfo;
}