Example usage for org.springframework.data.mongodb.core.query Update Update

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

Introduction

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

Prototype

Update

Source Link

Usage

From source file:org.slc.sli.dal.repository.MongoRepository.java

@Override
public WriteResult updateMulti(NeutralQuery query, Map<String, Object> update, String collectionName) {
    // Enforcing the tenantId query. The rationale for this is all CRUD
    // Operations should be restricted based on tenant.
    this.addDefaultQueryParams(query, collectionName);

    Query convertedQuery = this.queryConverter.convert(collectionName, query);
    Update convertedUpdate = new Update();

    for (Map.Entry<String, Object> entry : update.entrySet()) {
        String operation = entry.getKey();
        @SuppressWarnings("unchecked")
        Map<String, Object> operands = (Map<String, Object>) entry.getValue();

        if (operation.equals("push")) {
            for (Map.Entry<String, Object> fieldValues : operands.entrySet()) {
                convertedUpdate.push(fieldValues.getKey(), fieldValues.getValue());
            }//from   w w  w . j a  va2s  .co  m
        } else if (operation.equals("pushAll")) {
            for (Map.Entry<String, Object> fieldValues : operands.entrySet()) {
                convertedUpdate.pushAll(fieldValues.getKey(), (Object[]) fieldValues.getValue());
            }
        } else if (operation.equals("addToSet")) {
            for (Map.Entry<String, Object> fieldValues : operands.entrySet()) {
                convertedUpdate.addToSet(fieldValues.getKey(), fieldValues.getValue());
            }
        }
    }
    guideIfTenantAgnostic(collectionName);
    return template.updateMulti(convertedQuery, convertedUpdate, collectionName);
}

From source file:org.slc.sli.dal.repository.MongoRepository.java

@Override
public boolean patch(String type, String collectionName, String id, Map<String, Object> newValues) {

    if (id.equals("")) {
        return false;
    }//from   ww w.j  a v  a  2 s  .  c om

    // prepare to find desired record to be patched
    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(idConverter.toDatabaseId(id)));
    query.addCriteria(createTenantCriteria(collectionName));
    // prepare update operation for record to be patched
    Update update = new Update();
    for (Entry<String, Object> patch : newValues.entrySet()) {
        update.set("body." + patch.getKey(), patch.getValue());
    }

    WriteResult result = updateFirst(query, update, collectionName);

    return (result.getN() == 1);
}

From source file:org.slc.sli.ingestion.processors.CommandProcessor.java

private void dumpMongoTrackingStats(String batchId) throws UnknownHostException {
    Map<String, ? extends Map<String, Pair<AtomicLong, AtomicLong>>> stats = Aspects
            .aspectOf(MongoTrackingAspect.class).getStats();

    if (stats != null) {
        String hostName = InetAddress.getLocalHost().getHostName();
        hostName = hostName.replaceAll("\\.", "#");
        Update update = new Update();
        update.set("executionStats." + hostName, stats);

        LOG.info("Dumping runtime stats to db for job {}", batchId);
        LOG.info(stats.toString());/*from  ww w .j a  v  a  2  s.c  om*/

        // TODO: move to BatchJobDAO
        mongo.updateFirst(new Query(Criteria.where(BATCH_JOB_ID).is(batchId)), update, "newBatchJob");
        Aspects.aspectOf(MongoTrackingAspect.class).reset();
    }
}

From source file:org.springframework.integration.mongodb.store.AbstractConfigurableMongoDbMessageStore.java

/**
 * Perform MongoDB {@code INC} operation for the document, which contains the {@link MessageDocument}
 * {@code sequence}, and return the new incremented value for the new {@link MessageDocument}.
 * The {@link #SEQUENCE_NAME} document is created on demand.
 * @return the next sequence value./* www.  j a  v a 2s  .c om*/
 */
protected int getNextId() {
    Query query = Query.query(Criteria.where("_id").is(SEQUENCE_NAME));
    query.fields().include(MessageDocumentFields.SEQUENCE);
    return (Integer) this.mongoTemplate
            .findAndModify(query, new Update().inc(MessageDocumentFields.SEQUENCE, 1),
                    FindAndModifyOptions.options().returnNew(true).upsert(true), Map.class, this.collectionName)
            .get(MessageDocumentFields.SEQUENCE);
}

From source file:piecework.repository.concrete.ProcessInstanceRepositoryCustomImpl.java

@Override
public boolean update(String id, String engineProcessInstanceId) {
    WriteResult result = mongoOperations
            .updateFirst(new Query(where("_id").is(id)),
                    new Update().set("engineProcessInstanceId", engineProcessInstanceId)
                            .set("lastModifiedTime", new Date()).addToSet("keywords", id),
                    ProcessInstance.class);
    String error = result.getError();
    if (StringUtils.isNotEmpty(error)) {
        LOG.error("Unable to correctly save engineProcessInstanceId " + engineProcessInstanceId + " for " + id
                + ": " + error);
        return false;
    }/*from   ww  w  .  j  a  va2  s .  com*/
    return true;
}

From source file:piecework.repository.concrete.ProcessInstanceRepositoryCustomImpl.java

@Override
public ProcessInstance update(String id, Operation operation, String applicationStatus,
        String applicationStatusExplanation, String processStatus, Set<Task> tasks) {
    Query query = new Query(where("_id").is(id));
    Update update = new Update();

    if (applicationStatus != null)
        update.set("applicationStatus", applicationStatus);
    if (applicationStatusExplanation != null)
        update.set("applicationStatusExplanation", applicationStatusExplanation);
    if (processStatus != null)
        update.set("processStatus", processStatus);

    if (tasks != null) {
        for (Task task : tasks) {
            update.set("tasks." + task.getTaskInstanceId(), task);
        }//  www  .  ja v a 2 s .c o  m
    }

    update.push("operations", operation);
    update.set("lastModifiedTime", new Date());

    FindAndModifyOptions options = new FindAndModifyOptions();
    options.returnNew(true);

    return mongoOperations.findAndModify(query, update, options, ProcessInstance.class);
}

From source file:piecework.repository.concrete.ProcessInstanceRepositoryCustomImpl.java

@Override
public boolean update(String id, Task task) {
    Query query = new Query();
    query.addCriteria(where("processInstanceId").is(id));

    Update update = new Update();
    update.set("tasks." + task.getTaskInstanceId(), task).set("lastModifiedTime", new Date());
    FindAndModifyOptions options = new FindAndModifyOptions();
    options.returnNew(true);//from w  ww  . j  av  a  2s .  c  o  m
    ProcessInstance stored = mongoOperations.findAndModify(query, update, options, ProcessInstance.class);

    return true;
}

From source file:piecework.repository.concrete.ProcessInstanceRepositoryCustomImpl.java

@Override
public ProcessInstance update(String id, String processStatus, String applicationStatus,
        Map<String, List<Value>> data) {
    Update update = new Update().set("endTime", new Date()).set("applicationStatus", applicationStatus)
            .set("processStatus", Constants.ProcessStatuses.COMPLETE).set("lastModifiedTime", new Date());
    include(update, data, id);/*from www  .jav a  2 s  .com*/
    return mongoOperations.findAndModify(new Query(where("_id").is(id)), update, OPTIONS,
            ProcessInstance.class);
}

From source file:piecework.repository.concrete.ProcessInstanceRepositoryCustomImpl.java

private ProcessInstance updateEfficiently(String id, String label, Map<String, List<Value>> data,
        Map<String, List<Message>> messages, List<Attachment> attachments, Submission submission,
        String applicationStatusExplanation) {
    Query query = new Query(where("_id").is(id));
    Update update = new Update();

    if (applicationStatusExplanation != null)
        update.set("applicationStatusExplanation", applicationStatusExplanation);

    include(update, attachments);/*from w w  w .  j  a  v  a 2 s.c om*/
    include(update, data, id);
    include(update, label);
    include(update, submission);
    includeMessages(update, messages);

    update.set("lastModifiedTime", new Date());

    return mongoOperations.findAndModify(query, update, OPTIONS, ProcessInstance.class);
}

From source file:uk.co.jassoft.markets.crawler.CrawlerListener.java

@Override
@JmsListener(destination = "Crawler", concurrency = "5")
public void onMessage(final Message message) {
    if (message instanceof TextMessage) {
        final TextMessage textMessage = (TextMessage) message;
        try {//from  ww w  . j  av a2s  .  co m
            message.acknowledge();

            final Story story = mapper.readValue(textMessage.getText(), Story.class);

            Source source = sourceRepository.findOne(story.getParentSource());

            if (source.isDisabled()) {
                LOG.info("Source [{}] is Disabled", source.getName());
                final Link link = linkService.findOneByLink(story.getUrl().toString());
                if (link != null) {
                    linkService.delete(link);
                }
                return;
            }

            if (SourceUtils.matchesExclusion(source.getExclusionList(), story.getUrl().toString())) {
                LOG.info("Story Link Matches Exclusion for Source [{}]", source.getName());

                final Link link = linkService.findOneByLink(story.getUrl().toString());
                if (link != null) {
                    linkService.delete(link);
                }

                return;
            }

            if (isbaseURL(source.getUrls(), story.getUrl().toString())) {

                SourceUrl currentSourceUrl = source.getUrls().parallelStream()
                        .filter(sourceUrl -> sourceUrl.getUrl().equals(story.getUrl().toString())).findFirst()
                        .get();

                if (!currentSourceUrl.isEnabled() || (currentSourceUrl.getDisabledUntil() != null
                        && currentSourceUrl.getDisabledUntil().after(new Date()))) {
                    LOG.info("Source URL [{}] is Disabled", currentSourceUrl.getUrl());
                    final Link link = linkService.findOneByLink(story.getUrl().toString());
                    if (link != null) {
                        linkService.delete(link);
                    }
                    return;
                }
            }

            try (InputStream inputStream = network.read(story.getUrl().toString(), "GET",
                    !isbaseURL(source.getUrls(), story.getUrl().toString()))) {

                Document doc = Jsoup.parse(inputStream, "UTF-8", story.getUrl().toString());

                Elements links = doc.select("a[href]");

                doc = null;

                LOG.debug("Found [{}] Links in [{}]", links.size(), story.getUrl().toString());

                AtomicInteger newLinkCount = new AtomicInteger(0);

                links.stream().map(link -> {
                    String linkHref = link.attr("abs:href");

                    if (linkHref.contains("#"))
                        linkHref = linkHref.substring(0, linkHref.indexOf("#"));

                    return new ImmutablePair<String, Element>(linkHref, link);

                }).filter(isNotGlobalExclusion()).filter(isValidUrl(source))
                        .filter(doesNotMatchExclusion(source)).filter(isNewLink(linkService, storyRepository))
                        .forEach(link -> {

                            try {
                                LOG.debug("{} - {}", link.getKey(), link.getValue().text());

                                Story storyFound = new Story(link.getValue().text(), new URL(link.getKey()),
                                        new Date(), story.getParentSource());

                                crawlLink(storyFound);

                                newLinkCount.incrementAndGet();

                                Story existingStory = storyRepository
                                        .findOneByUrl(storyFound.getUrl().toString());

                                if (existingStory != null)
                                    return;

                                if (link.getKey().getBytes().length < 1000) {

                                    storyRepository.save(storyFound);

                                    collectStory(storyFound.getId());

                                    linkService.save(new Link(link.getKey()));
                                } else {
                                    LOG.warn("Link too long to persist. Not Persisting. {} - {}", link.getKey(),
                                            link.getValue().text());
                                }

                            } catch (final Exception exception) {
                                LOG.error("Error found with Link {} - {}", link.getKey(),
                                        link.getValue().text() + ": " + exception.getLocalizedMessage());
                            }
                        });

                if (newLinkCount.get() > 0) {
                    LOG.info("Found [{}] New Links in [{}]", newLinkCount.get(), story.getUrl().toString());
                }

                links = null;
            } catch (IOException exception) {
                LOG.warn("IOException Crawling Link [{}] - [{}]", story.getUrl().toString(),
                        exception.getMessage());
                sourceErrorRepository.save(new SourceError(source.getId(), new Date(),
                        story.getUrl().toString(), null, exception.getMessage()));
                return;
            }

            if (isbaseURL(source.getUrls(), story.getUrl().toString())) {

                SourceUrl currentSourceUrl = source.getUrls().parallelStream()
                        .filter(sourceUrl -> sourceUrl.getUrl().equals(story.getUrl().toString())).findFirst()
                        .get();

                currentSourceUrl.setLastCrawled(new Date());
                currentSourceUrl.setPendingCrawl(false);

                if (currentSourceUrl.getCrawlInterval() == null) {
                    currentSourceUrl.setCrawlInterval(60);
                }

                mongoTemplate.updateFirst(
                        Query.query(Criteria.where("id").is(source.getId()).and("urls.url")
                                .is(story.getUrl().toString())),
                        new Update().set("urls.$", currentSourceUrl), Source.class);
            }

        } catch (IOException exception) {
            LOG.warn(exception.getLocalizedMessage());
            return;
        } catch (final Exception exception) {
            LOG.error(exception.getLocalizedMessage(), exception);

            throw new RuntimeException(exception);
        }
    }
}