Example usage for javax.ejb AsyncResult AsyncResult

List of usage examples for javax.ejb AsyncResult AsyncResult

Introduction

In this page you can find the example usage for javax.ejb AsyncResult AsyncResult.

Prototype

public AsyncResult(V result) 

Source Link

Document

Creates a AsyncResult instance to wrap the result of an asynchronous method call

Usage

From source file:pl.psnc.synat.wrdz.mdz.integrity.IntegrityProcessorBean.java

@Override
@Asynchronous/*from ww  w .java2 s . c o  m*/
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Future<Void> processAll() {

    if (waitingForIdentifier != null) {
        logger.warn(
                "Processing started, but processor is waiting for an object. This can cause synchronization problems.");
    }

    IntegrityProcessor proxy = ctx.getBusinessObject(IntegrityProcessor.class);

    boolean finished = false;

    while (!ctx.wasCancelCalled() && !finished) {
        IntegrityProcessingResult result = proxy.processOne();
        switch (result) {
        case PROCESSED:
            finished = false;
            break;
        case PAUSED:
            finished = true;
            break;
        case FINISHED:
            finished = true;
            proxy.finishCycle();
            break;
        default:
            throw new WrdzRuntimeException("Unexpected result: " + result);
        }
    }

    return new AsyncResult<Void>(null);
}

From source file:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * /*from www . j  a v  a  2  s . co  m*/
 * @param fromAddress
 * @param ccRe
 * @param toRecipient
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @return status message
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String toRecipient,
        final String subject, final String body, final String messageType) throws IllegalArgumentException {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipient == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipient");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;

    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) toRecipient;
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address toAddress = new InternetAddress(toRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

From source file:dk.dma.msinm.lucene.AbstractLuceneIndex.java

/**
 * Call this to re-index the entity index completely
 * @throws IOException/*w w  w  .  j a  v a 2s. c  om*/
 */
@Asynchronous
public Future<Integer> recreateIndexAsync() throws IOException {
    int updateCount = recreateIndex();
    return new AsyncResult<>(updateCount);
}

From source file:io.hops.hopsworks.common.util.WebCommunication.java

@Asynchronous
public Future<String> asyncServiceOp(String operation, String hostAddress, String agentPassword, String cluster,
        String group, String service) throws GenericException {
    String url = createUrl(operation, hostAddress, cluster, group, service);
    return new AsyncResult<>(fetchContent(url, agentPassword));
}

From source file:io.hops.hopsworks.common.jobs.yarn.YarnExecutionFinalizer.java

@Asynchronous
public Future<Execution> copyLogs(Execution exec) {
    DistributedFileSystemOps udfso = dfs.getDfsOps(exec.getHdfsUser());
    ApplicationId applicationId = ApplicationId.fromString(exec.getAppId());
    YarnClientWrapper yarnClientWrapper = ycs.getYarnClientSuper(settings.getConfiguration());
    YarnMonitor monitor = new YarnMonitor(applicationId, yarnClientWrapper, ycs);
    try {// w  w w  .j  a  v a2 s  . c o m
        String defaultOutputPath;
        switch (exec.getJob().getJobType()) {
        case SPARK:
        case PYSPARK:
            defaultOutputPath = Settings.SPARK_DEFAULT_OUTPUT_PATH;
            break;
        case FLINK:
            defaultOutputPath = Settings.FLINK_DEFAULT_OUTPUT_PATH;
            break;
        case YARN:
            defaultOutputPath = Settings.YARN_DEFAULT_OUTPUT_PATH;
        default:
            defaultOutputPath = "Logs/";
        }
        String stdOutFinalDestination = Utils.getHdfsRootPath(exec.getJob().getProject().getName())
                + defaultOutputPath;
        String stdErrFinalDestination = Utils.getHdfsRootPath(exec.getJob().getProject().getName())
                + defaultOutputPath;

        String stdOutPath = settings.getAggregatedLogPath(exec.getHdfsUser(), exec.getAppId());
        try {
            if (stdOutFinalDestination != null && !stdOutFinalDestination.isEmpty()) {
                stdOutFinalDestination = stdOutFinalDestination + exec.getAppId() + File.separator
                        + "stdout.log";
                String[] desiredLogTypes = { "out" };
                YarnLogUtil.copyAggregatedYarnLogs(udfso, stdOutPath, stdOutFinalDestination, desiredLogTypes,
                        monitor);
            }
            if (stdErrFinalDestination != null && !stdErrFinalDestination.isEmpty()) {
                stdErrFinalDestination = stdErrFinalDestination + exec.getAppId() + File.separator
                        + "stderr.log";
                String[] desiredLogTypes = { "err", ".log" };
                YarnLogUtil.copyAggregatedYarnLogs(udfso, stdOutPath, stdErrFinalDestination, desiredLogTypes,
                        monitor);
            }
        } catch (IOException | InterruptedException | YarnException ex) {
            LOG.severe("error while aggregation logs" + ex.toString());
        }
        Execution execution = updateExecutionSTDPaths(stdOutFinalDestination, stdErrFinalDestination, exec);
        return new AsyncResult<>(execution);
    } finally {
        dfs.closeDfsClient(udfso);
        monitor.close();
    }
}

From source file:net.maxgigapop.mrs.driver.GenericRESTDriver.java

@Override
@Asynchronous/*  w  w  w  .j  a v a  2s  .  co  m*/
public Future<String> commitDelta(DriverSystemDelta aDelta) {
    DriverInstance driverInstance = aDelta.getDriverInstance();
    if (driverInstance == null) {
        throw new EJBException(String.format("commitDelta see null driverInance for %s", aDelta));
    }
    String subsystemBaseUrl = driverInstance.getProperty("subsystemBaseUrl");
    if (subsystemBaseUrl == null) {
        throw new EJBException(String.format("%s has no property key=subsystemBaseUrl", driverInstance));
    }
    // commit through PUT
    try {
        URL url = new URL(String.format("%s/delta/%s/%d/commit", subsystemBaseUrl,
                aDelta.getReferenceVersionItem().getReferenceUUID(), aDelta.getId()));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        String status = this.executeHttpMethod(url, conn, "PUT", null);
        //$$  if status == FAILED and raise exception
    } catch (IOException ex) {
        throw new EJBException(
                String.format("%s failed to connect to subsystem with exception (%s)", driverInstance, ex));
    }
    // query through GET
    boolean doPoll = true;
    int maxNumPolls = 10; // timeout after 5 minutes -> ? make configurable
    while (doPoll && (maxNumPolls--) > 0) {
        try {
            sleep(30000L); // poll every 30 minutes -> ? make configurable
            // pull model from REST API
            URL url = new URL(String.format("%s/delta/%s/%d", subsystemBaseUrl,
                    aDelta.getReferenceVersionItem().getReferenceUUID(), aDelta.getId()));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            String status = this.executeHttpMethod(url, conn, "GET", null);
            if (status.toUpperCase().equals("ACTIVE")) {
                doPoll = false; // committed successfully
            } else if (status.toUpperCase().contains("FAILED")) {
                throw new EJBException(
                        String.format("%s failed to commit %s with status=%s", driverInstance, aDelta, status));
            }
        } catch (InterruptedException ex) {
            throw new EJBException(String.format("%s poll for commit status is interrupted", driverInstance));
        } catch (IOException ex) {
            throw new EJBException(String.format("%s failed to communicate with subsystem with exception (%s)",
                    driverInstance, ex));
        }
    }
    return new AsyncResult<>("SUCCESS");
}

From source file:pl.psnc.synat.wrdz.zmkd.plan.MigrationPlanProcessorBean.java

@Override
@Asynchronous/*from www  .j av a 2s  . c o  m*/
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Future<Void> processAll(long planId) {
    MigrationPlanProcessor proxy = ctx.getBusinessObject(MigrationPlanProcessor.class);

    boolean finished = false;

    List<TransformationInfo> path = null;
    try {
        path = planExecutionParser.parseTransformationPath(migrationPathRetriever.retrieveActivePath(planId));
    } catch (InconsistentServiceDescriptionException e) {
        logger.error(e.getMessage(), e);
        finished = true;
    }

    while (!ctx.wasCancelCalled() && !finished) {
        try {
            MigrationProcessingResult migrationProcessingResult = proxy.processOne(planId, path);
            switch (migrationProcessingResult) {
            case PROCESSED:
                finished = false;
                break;
            case PAUSED:
                finished = true;
                break;
            case FINISHED:
                finished = true;
                migrationPlanManager.logFinished(planId);
                break;
            default:
                throw new WrdzRuntimeException("Unexpected result: " + migrationProcessingResult);
            }
        } catch (MigrationProcessingException e) {
            logger.error(e.getMessage(), e);
        } catch (MigrationPlanNotFoundException nfe) {
            throw new WrdzRuntimeException("Plan not found", nfe);
        }
    }

    return new AsyncResult<Void>(null);
}

From source file:net.maxgigapop.mrs.driver.GenericRESTDriver.java

@Override
@Asynchronous// w  w  w.j ava  2  s . com
@SuppressWarnings("empty-statement")
public Future<String> pullModel(Long driverInstanceId) {
    DriverInstance driverInstance = DriverInstancePersistenceManager.findById(driverInstanceId);
    if (driverInstance == null) {
        throw new EJBException(String.format("pullModel cannot find driverInance(id=%d)", driverInstanceId));
    }
    String subsystemBaseUrl = driverInstance.getProperty("subsystemBaseUrl");
    if (subsystemBaseUrl == null) {
        throw new EJBException(String.format("%s has no property key=subsystemBaseUrl", driverInstance));
    }
    if (DriverInstancePersistenceManager.getDriverInstanceByTopologyMap() == null
            || !DriverInstancePersistenceManager.getDriverInstanceByTopologyMap()
                    .containsKey(driverInstance.getTopologyUri())) {
        return new AsyncResult<>("INITIALIZING");
    }
    // sync on cached DriverInstance object = once per driverInstance to avoid write multiple vi of same version 
    DriverInstance syncOnDriverInstance = DriverInstancePersistenceManager.getDriverInstanceByTopologyMap()
            .get(driverInstance.getTopologyUri());
    synchronized (syncOnDriverInstance) {
        String version = null;
        String ttlModel = null;
        String creationTimestamp = null;
        try {
            if (driverInstance.getHeadVersionItem() != null) {
                URL url = new URL(
                        subsystemBaseUrl + "/model/" + driverInstance.getHeadVersionItem().getReferenceUUID());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                String status = this.executeHttpMethod(url, conn, "GET", null);
                if (status.toUpperCase().equals("LATEST")) {
                    return new AsyncResult<>("SUCCESS");
                }
            }
            // pull model from REST API
            URL url = new URL(subsystemBaseUrl + "/model");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            String responseStr = this.executeHttpMethod(url, conn, "GET", null);
            JSONObject responseJSON = (JSONObject) JSONValue.parseWithException(responseStr);
            version = responseJSON.get("version").toString();
            if (version == null || version.isEmpty()) {
                throw new EJBException(String.format("%s pulled model from subsystem with null/empty version",
                        driverInstance));
            }
            ttlModel = responseJSON.get("ttlModel").toString();
            if (ttlModel == null || ttlModel.isEmpty()) {
                throw new EJBException(String.format(
                        "%s pulled model from subsystem with null/empty ttlModel content", driverInstance));
            }
            creationTimestamp = responseJSON.get("creationTime").toString();
            if (creationTimestamp == null || creationTimestamp.isEmpty()) {
                throw new EJBException(String
                        .format("%s pulled model from subsystem with null/empty creationTime", driverInstance));
            }
        } catch (IOException ex) {
            throw new EJBException(
                    String.format("%s failed to connect to subsystem with exception (%s)", driverInstance, ex));
        } catch (ParseException ex) {
            throw new EJBException(
                    String.format("%s failed to parse pulled information from subsystem with exception (%s)",
                            driverInstance, ex));
        }
        VersionItem vi = null;
        DriverModel dm = null;
        try {
            // check if this version has been pulled before
            vi = VersionItemPersistenceManager.findByReferenceUUID(version);
            if (vi != null) {
                return new AsyncResult<>("SUCCESS");
            }
            // create new driverDelta and versioItem
            OntModel ontModel = ModelUtil.unmarshalOntModel(ttlModel);
            dm = new DriverModel();
            dm.setCommitted(true);
            dm.setOntModel(ontModel);
            Date creationTime = new Date(Long.parseLong(creationTimestamp));
            dm.setCreationTime(creationTime);
            ModelPersistenceManager.save(dm);
            vi = new VersionItem();
            vi.setModelRef(dm);
            vi.setReferenceUUID(version);
            vi.setDriverInstance(driverInstance);
            VersionItemPersistenceManager.save(vi);
            driverInstance.setHeadVersionItem(vi);
            VersionItemPersistenceManager.save(vi);
            logger.info(String.format("persisted %s", vi));
        } catch (Exception e) {
            try {
                if (dm != null) {
                    ModelPersistenceManager.delete(dm);
                }
                if (vi != null) {
                    VersionItemPersistenceManager.delete(vi);
                }
            } catch (Exception ex) {
                ; // do nothing (logging?)
            }
            throw new EJBException(
                    String.format("pullModel on %s raised exception[%s]", driverInstance, e.getMessage()));
        }
    }
    return new AsyncResult<>("SUCCESS");
}

From source file:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * /*from  w ww.  j  a va 2s. co m*/
 * @param fromAddress
 * @param recipients
 *            - fully qualified recipient address
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient,
        final String[] toRecipients, final String subject, final String body, final String messageType) {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipients == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipients");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) StringUtils.join(toRecipients);
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address[] toAddresses = new Address[toRecipients.length];
        for (int i = 0; i < toAddresses.length; i++) {
            toAddresses[i] = new InternetAddress(toRecipients[i]);
        }
        message.addRecipients(Message.RecipientType.TO, toAddresses);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

From source file:org.jboss.ejb3.examples.ch05.encryption.EncryptionBean.java

/**
 * {@inheritDoc}//from w w w  .j a va 2s.  co m
 * @see org.jboss.ejb3.examples.ch05.encryption.EncryptionCommonBusiness#hashAsync(java.lang.String)
 */
@Asynchronous
@Override
public Future<String> hashAsync(final String input) throws IllegalArgumentException, EncryptionException {
    // Get the real hash
    final String hash = this.hash(input);

    // Wrap and return
    return new AsyncResult<String>(hash);
}