Search in sources :

Example 1 with Async

use of org.springframework.scheduling.annotation.Async in project perun by CESNET.

the class DispatcherQueue method sendMessage.

/**
	 * Send message This method does not block. It is going to be executed
	 * asynchronously.
	 * 
	 * @param text
	 */
@Async
public void sendMessage(String text) {
    try {
        // Step 7. Create a Text Message
        TextMessage message = session.createTextMessage("task|" + clientID + "|" + text);
        // Step 8. Send...
        producer.send(message);
        if (log.isDebugEnabled()) {
            log.debug("Sent message (queue:" + queueName + "): " + message.getText());
        }
    } catch (JMSException e) {
        log.error(e.toString(), e);
    } catch (Exception e) {
        log.error(e.toString(), e);
    // TODO:Restart connection...?
    }
}
Also used : JMSException(javax.jms.JMSException) TextMessage(javax.jms.TextMessage) JMSException(javax.jms.JMSException) Async(org.springframework.scheduling.annotation.Async)

Example 2 with Async

use of org.springframework.scheduling.annotation.Async in project c4sg-services by Code4SocialGood.

the class AsyncEmailServiceImpl method send.

/**
     * Sends an email message asynchronously.
     *
     * @param from       email address from which the message will be sent.
     * @param recipient  array of strings containing the recipients of the message.
     * @param subject    subject header field.
     * @param text       content of the message.
     */
@Async
public void send(String from, String recipient, String subject, String text) {
    try {
        Properties properties = new Properties();
        properties.load(getClass().getResourceAsStream("/mail.properties"));
        String host = properties.getProperty("mail.smtp.host");
        String port = properties.getProperty("mail.smtp.port");
        String ssl = properties.getProperty("mail.smtp.ssl.enable");
        String username = properties.getProperty("mail.smtp.username");
        String password = properties.getProperty("mail.smtp.password");
        HtmlEmail email = new HtmlEmail();
        email.setHostName(host);
        email.setSmtpPort(Integer.parseInt(port));
        email.setAuthentication(username, password);
        email.setSSLOnConnect(Boolean.parseBoolean(ssl));
        Objects.requireNonNull(from, "Sender's email is incorrect");
        Objects.requireNonNull(recipient, "Recipient's email is incorrect");
        email.setFrom(from);
        email.addTo(recipient);
        email.setSubject(subject);
        email.setHtmlMsg(text);
        email.send();
        System.out.println("Email sent to " + recipient + " successfully");
    } catch (EmailException e) {
        e.printStackTrace();
        System.out.println("Fail: Could not send email to: " + recipient + " !!! ");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : HtmlEmail(org.apache.commons.mail.HtmlEmail) EmailException(org.apache.commons.mail.EmailException) IOException(java.io.IOException) Properties(java.util.Properties) Async(org.springframework.scheduling.annotation.Async)

Example 3 with Async

use of org.springframework.scheduling.annotation.Async in project dhis2-core by dhis2.

the class JdbcAnalyticsManager method getAggregatedDataValues.

// -------------------------------------------------------------------------
// AnalyticsManager implementation
// -------------------------------------------------------------------------
@Override
@Async
public Future<Map<String, Object>> getAggregatedDataValues(DataQueryParams params, int maxLimit) {
    try {
        ListMap<DimensionalItemObject, DimensionalItemObject> dataPeriodAggregationPeriodMap = params.getDataPeriodAggregationPeriodMap();
        if (params.isDisaggregation() && params.hasDataPeriodType()) {
            params = DataQueryParams.newBuilder(params).withDataPeriodsForAggregationPeriods(dataPeriodAggregationPeriodMap).build();
        }
        String sql = getSelectClause(params);
        if (params.spansMultiplePartitions()) {
            sql += getFromWhereClauseMultiplePartitionFilters(params);
        } else {
            sql += getFromWhereClause(params, params.getPartitions().getSinglePartition());
        }
        sql += getGroupByClause(params);
        if (params.isDataType(DataType.NUMERIC) && !params.getMeasureCriteria().isEmpty()) {
            sql += getMeasureCriteriaSql(params);
        }
        log.debug(sql);
        Map<String, Object> map = null;
        try {
            map = getKeyValueMap(params, sql, maxLimit);
        } catch (BadSqlGrammarException ex) {
            log.info("Query failed, likely because the requested analytics table does not exist", ex);
            return new AsyncResult<>(new HashMap<String, Object>());
        }
        replaceDataPeriodsWithAggregationPeriods(map, params, dataPeriodAggregationPeriodMap);
        return new AsyncResult<>(map);
    } catch (RuntimeException ex) {
        log.error(DebugUtils.getStackTrace(ex));
        throw ex;
    }
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) DateUtils.getMediumDateString(org.hisp.dhis.system.util.DateUtils.getMediumDateString) AsyncResult(org.springframework.scheduling.annotation.AsyncResult) Async(org.springframework.scheduling.annotation.Async)

Example 4 with Async

use of org.springframework.scheduling.annotation.Async in project nutch by apache.

the class CrawlServiceImpl method startCrawl.

@Override
@Async
public void startCrawl(Long crawlId, NutchInstance instance) {
    Crawl crawl = null;
    try {
        crawl = crawlDao.queryForId(crawlId);
        if (crawl.getCrawlId() == null) {
            crawl.setCrawlId("crawl-" + crawlId.toString());
        }
        NutchClient client = nutchClientFactory.getClient(instance);
        String seedDirectory = client.createSeed(crawl.getSeedList());
        crawl.setSeedDirectory(seedDirectory);
        List<RemoteCommand> commands = commandFactory.createCommands(crawl);
        RemoteCommandExecutor executor = new RemoteCommandExecutor(client);
        CrawlingCycle cycle = new CrawlingCycle(this, executor, crawl, commands);
        cycle.executeCrawlCycle();
    } catch (Exception e) {
        crawl.setStatus(CrawlStatus.ERROR);
        saveCrawl(crawl);
        LOG.error("exception occured", e);
    }
}
Also used : Crawl(org.apache.nutch.webui.client.model.Crawl) NutchClient(org.apache.nutch.webui.client.NutchClient) RemoteCommand(org.apache.nutch.webui.client.impl.RemoteCommand) RemoteCommandExecutor(org.apache.nutch.webui.client.impl.RemoteCommandExecutor) CrawlingCycle(org.apache.nutch.webui.client.impl.CrawlingCycle) SQLException(java.sql.SQLException) Async(org.springframework.scheduling.annotation.Async)

Example 5 with Async

use of org.springframework.scheduling.annotation.Async in project webanno by webanno.

the class WebhookService method onApplicationEvent.

@TransactionalEventListener(fallbackExecution = true)
@Async
public void onApplicationEvent(ApplicationEvent aEvent) {
    String topic = EVENT_TOPICS.get(aEvent.getClass());
    if (topic == null) {
        return;
    }
    Object message;
    switch(topic) {
        case PROJECT_STATE:
            message = new ProjectStateChangeMessage((ProjectStateChangedEvent) aEvent);
            break;
        case DOCUMENT_STATE:
            message = new DocumentStateChangeMessage((DocumentStateChangedEvent) aEvent);
            break;
        case ANNOTATION_STATE:
            message = new AnnotationStateChangeMessage((AnnotationStateChangeEvent) aEvent);
            break;
        default:
            return;
    }
    for (Webhook hook : configuration.getGlobalHooks()) {
        if (!hook.isEnabled() || !hook.getTopics().contains(topic)) {
            continue;
        }
        try {
            // Configure rest template without SSL certification check if that is disabled.
            RestTemplate restTemplate;
            if (hook.isVerifyCertificates()) {
                restTemplate = restTemplateBuilder.build();
            } else {
                restTemplate = restTemplateBuilder.requestFactory(getNonValidatingRequestFactory()).build();
            }
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            requestHeaders.set(X_AERO_NOTIFICATION, topic);
            // If a secret is set, then add a digest header that allows the client to verify
            // the message integrity
            String json = JSONUtil.toJsonString(message);
            if (isNotBlank(hook.getSecret())) {
                String digest = DigestUtils.shaHex(hook.getSecret() + json);
                requestHeaders.set(X_AERO_SIGNATURE, digest);
            }
            HttpEntity<?> httpEntity = new HttpEntity<Object>(json, requestHeaders);
            restTemplate.postForEntity(hook.getUrl(), httpEntity, Void.class);
        } catch (Exception e) {
            log.error("Unable to invoke webhook [{}]", hook, e);
        }
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) ProjectStateChangedEvent(de.tudarmstadt.ukp.clarin.webanno.api.event.ProjectStateChangedEvent) ProjectStateChangeMessage(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.ProjectStateChangeMessage) DocumentStateChangedEvent(de.tudarmstadt.ukp.clarin.webanno.api.event.DocumentStateChangedEvent) AnnotationStateChangeMessage(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.AnnotationStateChangeMessage) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RestTemplate(org.springframework.web.client.RestTemplate) AnnotationStateChangeEvent(de.tudarmstadt.ukp.clarin.webanno.api.event.AnnotationStateChangeEvent) DocumentStateChangeMessage(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.webhooks.json.DocumentStateChangeMessage) Async(org.springframework.scheduling.annotation.Async) TransactionalEventListener(org.springframework.transaction.event.TransactionalEventListener)

Aggregations

Async (org.springframework.scheduling.annotation.Async)122 Locale (java.util.Locale)21 Context (org.thymeleaf.context.Context)21 MimeMessageHelper (org.springframework.mail.javamail.MimeMessageHelper)19 Subscribe (com.google.common.eventbus.Subscribe)18 MimeMessage (javax.mail.internet.MimeMessage)18 IOException (java.io.IOException)10 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)10 IdentityUser (com.sequenceiq.cloudbreak.common.model.user.IdentityUser)9 List (java.util.List)8 AsyncResult (org.springframework.scheduling.annotation.AsyncResult)8 Map (java.util.Map)6 Collectors (java.util.stream.Collectors)6 Inject (javax.inject.Inject)6 Lists (com.google.common.collect.Lists)5 ArrayList (java.util.ArrayList)5 PublishCascadingScope (org.obiba.mica.core.domain.PublishCascadingScope)5 Component (org.springframework.stereotype.Component)5 DateTime (org.joda.time.DateTime)4