Java 类javax.ejb.Asynchronous 实例源码

项目:eplmp    文件:ImporterBean.java   
@Override
@Asynchronous
@FileImport
public Future<ImportResult> importIntoPathData(String workspaceId, File file, String originalFileName, String revisionNote, boolean autoFreezeAfterUpdate, boolean permissiveUpdate) {
    PathDataImporter selectedImporter = selectPathDataImporter(file);
    Locale userLocale = getUserLocale(workspaceId);
    Properties properties = PropertiesLoader.loadLocalizedProperties(userLocale, I18N_CONF, ImporterBean.class);

    PathDataImporterResult pathDataImporterResult;

    if (selectedImporter != null) {
        pathDataImporterResult = selectedImporter.importFile(getUserLocale(workspaceId), workspaceId, file, autoFreezeAfterUpdate, permissiveUpdate);
    } else {
        List<String> errors = getNoImporterAvailableError(properties);
        pathDataImporterResult = new PathDataImporterResult(file, new ArrayList<>(), errors, null, null, null);
    }

    ImportResult result = doPathDataImport(properties, workspaceId, revisionNote, autoFreezeAfterUpdate, permissiveUpdate, pathDataImporterResult);

    return new AsyncResult<>(result);
}
项目:darceo    文件:PluginExecutor.java   
/**
 * Executes the plugin with the given name. Internal use only.
 * 
 * @param pluginName
 *            plugin name
 * @return execution status
 */
@Asynchronous
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Future<Void> execute(String pluginName) {

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

    boolean finished = false;
    while (!ctx.wasCancelCalled() && !finished) {
        finished = !proxy.executeOnce(pluginName);
        if (finished) {
            proxy.finishCycle(pluginName);
        }

    }

    return new AsyncResult<Void>(null);
}
项目:asw    文件:AsynchronousHelloImpl.java   
/** Un'operazione asincrona (che puo' essere interrotta). */
@Asynchronous
public Future<String> hello(String name) throws HelloException, InterruptedException {
    String result = null;
    logger.info("AsynchronousHello.hello(" + name + ") called");

    if (name==null) {
        throw new HelloException("Invalid parameters for hello()");
    }

    /* diciamo che questa operazione perde un po' di tempo e
     * poi restituisce proprio il saluto desiderato */
    for (int i=0; i<name.length()*10; i++) {
        sleep(40);
        if (ctx.wasCancelCalled()) {
            logger.info("AsynchronousHello.hello(" + name + ") was cancelled");
            /* credo che la cosa giusta da fare qui sia sollevare un'eccezione */
            throw new InterruptedException("Operation AsynchronousHello.hello(" + name + ") was cancelled");
        }
    }
    result = "Hello, " + name.toUpperCase() + "!";
    logger.info("AsynchronousHello.hello(" + name + ") ==> " + result);
    return new AsyncResult<String>(result);
}
项目:JavaEE    文件:OrderProcessorBean.java   
/**
 * Places an order
 */
@Asynchronous
@Remove
@Override
public void placeOrder() {
    Order order = new Order();
    order.setBidder(bidder);
    order.setItem(item);
    order.setShipping(shipping);
    order.setBilling(billing);
    try {
        bill(order);
        notifyBillingSuccess(order);
        order.setStatus(OrderStatus.COMPLETE);
    } catch (BillingException be) {
        notifyBillingFailure(be, order);
        order.setStatus(OrderStatus.BILLING_FAILED);
    } finally {
        saveOrder(order);
    }
}
项目:eplmp    文件:NotifierBean.java   
@Asynchronous
@Override
public void sendPasswordRecovery(Account account, String recoveryUUID) {

    LOGGER.info("Sending recovery message \n\tfor the user which login is " + account.getLogin());

    Object[] args = {
            getRecoveryUrl(recoveryUUID),
            account.getLogin()
    };

    try {
        sendMessage(account, "Recovery_title", "Recovery_text", args);
    } catch (MessagingException pMEx) {
        logMessagingException(pMEx);
    }
}
项目:eplmp    文件:NotifierBean.java   
@Asynchronous
@Override
public void sendWorkspaceDeletionNotification(Account admin, String workspaceId) {

    LOGGER.info("Sending workspace deletion notification message \n\tfor the user which login is " + admin.getLogin());

    Object[] args = {
            workspaceId
    };

    try {
        User adminUser = new User(new Workspace(workspaceId), admin);
        sendMessage(adminUser, "WorkspaceDeletion_title", "WorkspaceDeletion_text", args);
    } catch (MessagingException pMEx) {
        logMessagingException(pMEx);
    }
}
项目:eplmp    文件:NotifierBean.java   
@Asynchronous
@Override
public void sendWorkspaceDeletionErrorNotification(Account admin, String workspaceId) {

    LOGGER.info("Sending workspace deletion error notification message \n\tfor the user which login is " + admin.getLogin());

    Object[] args = {
            workspaceId
    };
    try {
        User adminUser = new User(new Workspace(workspaceId), admin);
        sendMessage(adminUser, "WorkspaceDeletion_title", "WorkspaceDeletionError_text", args);
    } catch (MessagingException pMEx) {
        logMessagingException(pMEx);
    }
}
项目:eplmp    文件:NotifierBean.java   
@Asynchronous
@Override
public void sendWorkspaceIndexationSuccess(Account account, String workspaceId, String extraMessage) {

    Object[] args = {
            workspaceId,
            extraMessage
    };

    try {
        User adminUser = new User(new Workspace(workspaceId), account);
        sendMessage(adminUser, "Indexer_success_title", "Indexer_success_text", args);
    } catch (MessagingException pMEx) {
        logMessagingException(pMEx);
    }
}
项目:eplmp    文件:NotifierBean.java   
@Asynchronous
@Override
public void sendWorkspaceIndexationFailure(Account account, String workspaceId, String extraMessage) {

    Object[] args = {
            workspaceId,
            extraMessage
    };

    try {
        User adminUser = new User(new Workspace(workspaceId), account);
        sendMessage(adminUser, "Indexer_failure_title", "Indexer_failure_text", args);
    } catch (MessagingException pMEx) {
        logMessagingException(pMEx);
    }
}
项目:eplmp    文件:IndexerManagerBean.java   
@Override
@Asynchronous
@RolesAllowed({UserGroupMapping.ADMIN_ROLE_ID, UserGroupMapping.REGULAR_USER_ROLE_ID})
public void indexWorkspaceData(String workspaceId) throws AccountNotFoundException {
    Account account = accountManager.getMyAccount();

    try {
        // Clear workspace if exists, or recreate
        doDeleteWorkspaceIndex(workspaceId);
        Bulk.Builder bb = new Bulk.Builder().defaultIndex(workspaceId);
        bulkWorkspaceRequestBuilder(bb, workspaceId);

        BulkResult result = esClient.execute(bb.build());

        if (result.isSucceeded()) {
            mailer.sendBulkIndexationSuccess(account);
        } else {
            String failureMessage = result.getErrorMessage();
            LOGGER.log(Level.SEVERE, "Failures while bulk indexing workspace [" + workspaceId + "]: \n" + failureMessage);
            mailer.sendBulkIndexationFailure(account, failureMessage);
        }
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Cannot index the whole workspace: The Elasticsearch server does not seem to respond");
        mailer.sendBulkIndexationFailure(account, getString("IndexerNotAvailableForRequest", new Locale(account.getLanguage())));
    }
}
项目:otus-domain-api    文件:EmailNotifierServiceBean.java   
@Override
@Asynchronous
public void sendEmail(StudioEmail email) throws EmailNotificationException {
    GMailer mailer = GMailer.createTLSMailer();

    mailer.setFrom(email.getFrom());
    mailer.addRecipients(email.getRecipients());
    mailer.setSubject(email.getSubject());
    mailer.setContentType(email.getContentType());
    mailer.setContent(mergeTemplate(email.getContentDataMap(), email.getTemplatePath()));

    try {
        mailer.send();
    } catch (Exception e) {
        throw new EmailNotificationException();
    }
}
项目:hawkular-apm    文件:AlertsPublisher.java   
@Asynchronous
public void publish(final Event event) {
    if (BASE_URL == null || BASE_URL.isEmpty()) {
        logger.hawkularServerNotConfigured();
        return;
    }

    if (USERNAME == null || USERNAME.isEmpty()) {
        logger.hawkularServerUsernameNotConfigured();
        return;
    }

    if (PASSWORD == null || PASSWORD.isEmpty()) {
        logger.hawkularServerPasswordNotConfigured();
        return;
    }

    HystrixFeign.builder()
            .requestInterceptor(new BasicAuthRequestInterceptor(USERNAME, PASSWORD))
            .encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder())
            .retryer(new Retryer.Default())
            .target(AlertsService.class, TARGET)
            .addEvent(event);
}
项目:omakase    文件:PipelineExecutor.java   
/**
 * Executes a pipeline, executing each stage in turn until the pipeline completes, fails or halts while waiting for an asynchronous process to complete.
 * <p>
 * Only pipelines that are in their initial state can be executed, if the pipeline is not in it's initial state it is marked as failed.
 * </p>
 *
 * @param pipeline
 *         the pipeline
 */
@Asynchronous
public void executePipeline(@Observes(during = TransactionPhase.AFTER_SUCCESS) Pipeline pipeline) {
    Throwables.voidInstance(() -> OmakaseSecurity.doAsSystem(() -> {
        if (!pipeline.isFirstPipelineStage() && !PipelineStageStatus.QUEUED.equals(pipeline.getStatusOfCurrentStage())) {
            LOGGER.error("Pipeline " + pipeline.getId() + " is not in it's initial state");
            updatePipeline(PipelineStageResult.builder(pipeline.getId(), PipelineStageStatus.FAILED).addMessages(ImmutableSet.of("The pipeline is not in it's initial state")).build());
        }

        // the first stage is executed outside of recursion as, the recursion relies on the the previous stage
        // being complete before executing the next one which is not the case for the first stage.
        PipelineContext pipelineContext = createPipelineContext(pipeline);
        PipelineStageResult pipelineStageResult = pipelineStageExecutor.execute(pipelineContext, pipeline.getCurrentPipelineStage());

        executePipelineFailureStage(pipelineStageResult);

        Pipeline updatedPipeline = updatePipeline(pipelineStageResult);
        // execute subsequent stages until the pipeline is halted or completed.
        executePipelineStages(updatedPipeline);
        return true;
    }));

}
项目:darceo    文件:FileFormatProcessorBean.java   
@Override
@Asynchronous
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Future<Void> processAll() {
    logger.info("Format processing started");

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

    int count = 0;
    boolean finished = false;

    while (!ctx.wasCancelCalled() && !finished) {
        boolean processed = proxy.processOne();
        if (processed) {
            count++;
        }
        finished = !processed;
    }

    logger.info("Format processing stopped: checked {} format(s)", count);

    return new AsyncResult<Void>(null);
}
项目:editor-backend    文件:AsciidoctorEndpoint.java   
@POST
@Path("/convert/{backend}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@Asynchronous
public void convert(@PathParam("backend") String backend, 
        String asciidocContent, @Suspended AsyncResponse response) {
    Converter converter;
    switch (backend) {
        case "pdf":
            converter = Converter.pdf;
            break;
        case "dzslides":
            converter = Converter.dzslides;
            break;
        default:
            converter = Converter.html5;
    }

    OutputMessage out = new OutputMessage(converter);
    out.setContent(processor.convertToDocument(asciidocContent, converter));
    response.resume(out);
}
项目:editor-backend    文件:ProcessorEventConsumer.java   
@Asynchronous
@Lock(LockType.READ)
public void consumeEvent(@Observes ProcessorEvent processorEvent) throws InterruptedException {
    final String filename = getRandomFilename(processorEvent.filename);
    logger.info("Receiving event : " + asciidoctorBackendsDir + templateDZSlides + filename + processorEvent.converter.getFilenameExtension());

    try {
        File templateDir = null;
        if (processorEvent.converter.name().equals(Converter.dzslides.name())) {
            templateDir = new File(asciidoctorBackendsDir + templateDZSlides);
        }

        asciidoctor.convertToBinaryDocument(processorEvent.asciidoc, processorEvent.converter, templateDir, "all",
                filename);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Processing error for filename : " + filename, e);
    }
}
项目:training    文件:ParalellizerWorker.java   
@Asynchronous // SOLUTION
    //public Integer executeWorkItem(String workItem) { // INITIAL
    public Future<Integer> executeWorkItem(String workItem) { // SOLUTION
        int result = workItem.length();
        System.out.println("Worker " + workerId + ": Start processing item '" + workItem + "'");

        System.out.println("Worker " + workerId + ": " + Thread.currentThread().getName());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Worker " + workerId + ": Item '" + workItem + "' done.");

        return new AsyncResult<Integer>(result); // SOLUTION
//      return result; // INITIAL
    }
项目:facshop    文件:DeliveryHandler.java   
@Override
@Asynchronous
public void onNewOrder(@Observes @Paid OrderEvent event) {

    logger.log(Level.FINEST, "{0} Event being processed by DeliveryHandler", Thread.currentThread().getName());

    try {
        logger.log(Level.INFO, "Order #{0} has been paid in the amount of {1}. Order is now ready for delivery!", new Object[]{event.getOrderID(), event.getAmount()});

        orderBean.setOrderStatus(event.getOrderID(), String.valueOf(OrderBean.Status.READY_TO_SHIP.getStatus()));
        CustomerOrder order = orderBean.getOrderById(event.getOrderID());
        if (order != null) {
            orderPublisher.sendMessage(order);

        } else {
            throw new Exception("The order does not exist");
        }
    } catch (Exception jex) {
        logger.log(Level.SEVERE, null, jex);
    }
}
项目:facshop    文件:PaymentHandler.java   
@Override
@Asynchronous
public void onNewOrder(@Observes @New OrderEvent event) {

    logger.log(Level.FINEST, "{0} Event being processed by PaymentHandler",
            Thread.currentThread().getName());

    if (processPayment(event)) {
        orderBean.setOrderStatus(event.getOrderID(),
                String.valueOf(OrderBean.Status.PENDING_PAYMENT.getStatus()));
        logger.info("Payment Approved");
        eventManager.fire(event);
    } else {
        orderBean.setOrderStatus(event.getOrderID(),
                String.valueOf(OrderBean.Status.CANCELLED_PAYMENT.getStatus()));
        logger.info("Payment Denied");
    }
}
项目:hopsworks    文件:EmailBean.java   
@Asynchronous
public void sendEmail(String to, Message.RecipientType recipientType,
    String subject, String body) throws
    MessagingException, SendFailedException {

  MimeMessage message = new MimeMessage(mailSession);
  message.setFrom(new InternetAddress(mailSession.getProperty("mail.from")));
  InternetAddress[] address = {new InternetAddress(to)};
  message.setRecipients(recipientType, address);
  message.setSubject(subject);
  message.setContent(body, "text/html");

  // set the timestamp
  message.setSentDate(new Date());

  message.setText(body);
  try {
    Transport.send(message);
  } catch (MessagingException ex) {
    LOG.log(Level.SEVERE, ex.getMessage(), ex);
  }
}
项目:hopsworks    文件:YarnExecutionFinalizer.java   
@Asynchronous
public void finalize(Execution exec, JobState jobState) {
  long executionStop = System.currentTimeMillis();
  exec = executionFacade.updateExecutionStop(exec, executionStop);
  updateJobHistoryApp(exec.getExecutionDuration(), exec);
  try {
    // TODO(Antonis) In the future this call should be async as well
    // Network traffic in a transaction is not good
    removeAllNecessary(exec);
  } catch (IOException ex) {
    LOG.log(Level.WARNING,
        "Exception while cleaning after job:{0}, with appId:{1}, some cleanning is probably needed {2}", new Object[]{
          exec.getJob().getName(), exec.getAppId(), ex.getMessage()});
  }
  if (exec.getJob().getJobType().equals(JobType.FLINK)) {
    cleanCerts(exec);
  }
  updateState(jobState, exec);
}
项目:actionbazaar    文件:OrderProcessorBean.java   
/**
 * Places an order
 */
@Asynchronous
@Remove
@Override
public void placeOrder() {
    Order order = new Order();
    order.setBidder(bidder);
    order.setItem(item);
    order.setShipping(shipping);
    order.setBilling(billing);
    try {
        bill(order);
        notifyBillingSuccess(order);
        order.setStatus(OrderStatus.COMPLETE);
    } catch (BillingException be) {
        notifyBillingFailure(be, order);
        order.setStatus(OrderStatus.BILLING_FAILED);
    } finally {
        saveOrder(order);
    }
}
项目:actionbazaar    文件:OrderProcessorBean.java   
/**
 * Places an order
 */
@Asynchronous
@Remove
@Override
public void placeOrder() {
    Order order = new Order();
    order.setBidder(bidder);
    order.setItem(item);
    order.setShipping(shipping);
    order.setBilling(billing);
    try {
        bill(order);
        notifyBillingSuccess(order);
        order.setStatus(OrderStatus.COMPLETE);
    } catch (BillingException be) {
        notifyBillingFailure(be, order);
        order.setStatus(OrderStatus.BILLING_FAILED);
    } finally {
        saveOrder(order);
    }
}
项目:wicket-quickstart-cdi-async    文件:WorkflowBean.java   
/**
 * Does actually not work
 */
@Override
@Asynchronous
public void startAsynchronous(final IWorkflowListener listener)
{
    try
    {
        CdiContextAwareRunnable runnable = new CdiContextAwareRunnable(this.newWorkflowRunnable(listener));
        // runnable.addContext(RequestScoped.class);
        runnable.addContext(SessionScoped.class);
        // runnable.addContext(ApplicationScoped.class);
        runnable.addContext(ConversationScoped.class);

        runnable.run();
    }
    catch (WorkflowException e)
    {
        LOG.error(e.getMessage(), e);
    }
}
项目:web-budget    文件:Postman.java   
/**
 * Escuta por eventos de envio de e-mail
 * 
 * @param mailMessage a mensagem a ser enviada
 * @throws Exception caso haja problemas, dispara exception
 */
@Asynchronous
public void send(@Observes MailMessage mailMessage) throws Exception {

    final MimeMessage message = new MimeMessage(this.mailSession);

    // header da mensagem
    message.setFrom(mailMessage.getFrom());
    message.setSubject(mailMessage.getTitle());
    message.setRecipients(Message.RecipientType.TO, mailMessage.getAddressees());
    message.setRecipients(Message.RecipientType.CC, mailMessage.getCcs());

    // a mensagem
    message.setText(mailMessage.getContent(), "UTF-8", "html");
    message.setSentDate(new Date());

    // envia
    Transport.send(message);
}
项目:appformer    文件:IncrementalBuilderExecutorManager.java   
@Asynchronous
public void execute(final AsyncIncrementalBuilder incrementalBuilder) {
    if (useExecService.get()) {
        getExecutorService().execute(new DescriptiveRunnable() {
            @Override
            public void run() {
                incrementalBuilder.execute(projectService,
                                           buildService,
                                           incrementalBuildResultsEvent,
                                           buildResultsEvent);
            }

            @Override
            public String getDescription() {
                return incrementalBuilder.getDescription();
            }
        });
    } else {
        incrementalBuilder.execute(projectService,
                                   buildService,
                                   incrementalBuildResultsEvent,
                                   buildResultsEvent);
    }
}
项目:Hotel-Reservation-Tool    文件:ReservationBackendHandler.java   
@Asynchronous
public void handleNewReservations(@Observes NewReservationEvent newReservation) {
    int duration = rand.nextInt(6) + 5;
    LOGGER.log(INFO, "Incoming new reservation...{0}", newReservation);

    try {
        LOGGER.log(INFO, "delaying {0} secs before accepting", duration);
        sleep(duration * 1000L);

        bookingService.confirmReservation(newReservation.getReservationNumber());

        LOGGER.log(INFO, "Sending Email to guest about confirmation for {0}",
                newReservation.getReservationNumber());
    } catch (InterruptedException ex) {
        LOGGER.log(SEVERE, "Cannot sleep", ex);
        currentThread().interrupt();
    }
}
项目:send-mail-server    文件:SendMailBean.java   
@Asynchronous
public void send(@Observes Email email) {
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setHeader("Content-Type", "text/html;charset=UTF-8");
        msg.setSubject(email.getSubject(), defaultEncoding);
        msg.setContent(email.getBody(), MediaType.TEXT_HTML);

        Address[] internetAdress;
        if (email.getAddress() != null) {
            internetAdress = new Address[email.getAddress().size()];
            for (int i = 0; i < email.getAddress().size(); i++) {
                internetAdress[i] = new InternetAddress(email.getAddress()
                        .get(i));
            }
            msg.setRecipients(RecipientType.TO, internetAdress);
        }

        Transport.send(msg);
    } catch (MessagingException e) {
        System.out.println(e);
    }
}
项目:oracle-samples    文件:DeliveryHandler.java   
@Override
@Asynchronous
public void onNewOrder(@Observes @Paid OrderEvent event) {

    logger.log(Level.FINEST, "{0} Event being processed by DeliveryHandler", Thread.currentThread().getName());

    try {           
        logger.log(Level.INFO, "Order #{0} has been paid in the amount of {1}. Order is now ready for delivery!", new Object[]{event.getOrderID(), event.getAmount()});

        orderBean.setOrderStatus(event.getOrderID(), String.valueOf(OrderBean.Status.READY_TO_SHIP.getStatus()));
        CustomerOrder order = orderBean.getOrderById(event.getOrderID());
        if (order != null) {
            orderPublisher.sendMessage(order);

        } else {
            throw new Exception("The order does not exist");
        }
    } catch (Exception jex) {
        logger.log(Level.SEVERE, null, jex);
    }
}
项目:oracle-samples    文件:PaymentHandler.java   
@Override
@Asynchronous
public void onNewOrder(@Observes @New OrderEvent event) {

    logger.log(Level.FINEST, "{0} Event being processed by PaymentHandler",
            Thread.currentThread().getName());

    if (processPayment(event)) {
        orderBean.setOrderStatus(event.getOrderID(),
                String.valueOf(OrderBean.Status.PENDING_PAYMENT.getStatus()));
        logger.info("Payment Approved");
        eventManager.fire(event);
    } else {
        orderBean.setOrderStatus(event.getOrderID(),
                String.valueOf(OrderBean.Status.CANCELLED_PAYMENT.getStatus()));
        logger.info("Payment Denied");
    }
}
项目:web-budget    文件:Postman.java   
/**
 * Escuta por eventos de envio de e-mail
 * 
 * @param mailMessage a mensagem a ser enviada
 * @throws Exception caso haja problemas, dispara exception
 */
@Asynchronous
public void send(@Observes MailMessage mailMessage) throws Exception {

    final MimeMessage message = new MimeMessage(this.mailSession);

    // header da mensagem
    message.setFrom(mailMessage.getFrom());
    message.setSubject(mailMessage.getTitle());
    message.setRecipients(Message.RecipientType.TO, mailMessage.getAddressees());
    message.setRecipients(Message.RecipientType.CC, mailMessage.getCcs());

    // a mensagem
    message.setText(mailMessage.getContent(), "UTF-8", "html");
    message.setSentDate(new Date());

    // envia
    Transport.send(message);
}
项目:aerogear-unifiedpush-server    文件:HealthServiceImpl.java   
@Asynchronous
@Override
public Future<HealthDetails> dbStatus() {
    HealthDetails details = new HealthDetails();
    details.setDescription("Database connection");
    details.start();
    try {
        healthDao.dbCheck();
        details.setTestStatus(Status.OK);
        details.setResult("connected");
    } catch (Exception e) {
        details.setTestStatus(Status.CRIT);
        details.setResult(e.getMessage());
    }
    details.stop();
    return new AsyncResult<>(details);
}
项目:aerogear-unifiedpush-server    文件:HealthNetworkServiceImpl.java   
@Asynchronous
@Override
public Future<List<HealthDetails>> networkStatus() {
    final List<HealthDetails> results = new ArrayList<>(PUSH_NETWORKS.size());

    PUSH_NETWORKS.forEach(pushNetwork -> {
        HealthDetails details = new HealthDetails();
        details.start();
        details.setDescription(pushNetwork.getName());
        if (Ping.isReachable(pushNetwork.getHost(), pushNetwork.getPort())) {
            details.setTestStatus(Status.OK);
            details.setResult("online");
        } else {
            details.setResult(String.format("Network not reachable '%s'", pushNetwork.getName()));
            details.setTestStatus(Status.WARN);
        }

        results.add(details);
        details.stop();
    });

    return new AsyncResult<>(results);
}
项目:tomee    文件:AnnotationDeployer.java   
private void processAsynchronous(final EnterpriseBean bean, final AnnotationFinder annotationFinder) {
    if (!(bean instanceof SessionBean)) {
        return;
    }

    final SessionBean sessionBean = (SessionBean) bean;

    for (final Annotated<Method> method : annotationFinder.findMetaAnnotatedMethods(Asynchronous.class)) {
        sessionBean.getAsyncMethod().add(new AsyncMethod(method.get()));
    }

    //Spec 4.5.1 @Asynchronous could be used at the class level of a bean-class ( or superclass ).
    //Seems that it should not be used on the any interface view

    for (final Annotated<Class<?>> clazz : annotationFinder.findMetaAnnotatedClasses(Asynchronous.class)) {
        if (!clazz.get().isInterface()) {
            sessionBean.getAsynchronousClasses().add(clazz.get().getName());
        }
    }
}
项目:eap-6.1-quickstarts    文件:LongRunningService.java   
/**
* The use of {@link Asynchronous} causes this EJB method to be executed
* asynchronously, by a different thread from a dedicated, container managed
* thread pool.
* 
* @param asyncContext
*          the context for a suspended Servlet request that this EJB will
*          complete later.
*/
@Asynchronous
public void readData(AsyncContext asyncContext) {
    try {
        // This is just to simulate a long running operation for demonstration purposes.
        Thread.sleep(5000);

        PrintWriter writer = asyncContext.getResponse().getWriter();
        writer.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
        writer.close();

        asyncContext.complete();
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
}
项目:jboss-as-quickstart    文件:LongRunningService.java   
/**
 * The use of {@link Asynchronous} causes this EJB method to be executed asynchronously, by a different thread from a
 * dedicated, container managed thread pool.
 * 
 * @param asyncContext the context for a suspended Servlet request that this EJB will complete later.
 */
@Asynchronous
public void readData(AsyncContext asyncContext) {
    try {
        // This is just to simulate a long running operation for demonstration purposes.
        Thread.sleep(5000);

        PrintWriter writer = asyncContext.getResponse().getWriter();
        writer.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
        writer.close();

        asyncContext.complete();
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
}
项目:JEECQRS-JCommonDomain-Integration    文件:CommandLoggerService.java   
@Override
@Asynchronous
public void log(Command<?> command, Map<String, String> metadata) {
    Validate.notNull(command, "command must not be null");
    Validate.notNull(metadata, "metadata must not be null");
    String commandId = command.id().toString();
    WritableEventStream stream = streamFor(command);
    CommandLogEnvelope<Command<?>> envelope = new CommandLogEnvelope<Command<?>>(command,
            new HashMap<>(metadata));
    log.log(Level.FINE, "Logging command: {0}", envelope);
    stream.append(envelope);
    try {
        stream.commit(commandId);
    } catch (DuplicateCommitException | ConcurrencyException e) {
        throw new RuntimeException(e);
    }
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:BusyOperator.java   
@Asynchronous
public Future<Object> stayBusy(CountDownLatch ready) {
    ready.countDown();

    try {
        count = new CountDownLatch(1);
        count.await();
    } catch (InterruptedException e) {
        interrupted();
    }

    return null;
}
项目:oscm    文件:AuditLogServiceBeanIT.java   
public void log_isAsynchronous() throws Exception {
    // given
    Method method = AuditLogServiceBean.class.getMethod("log");

    // when
    boolean isAsynchronous = method.isAnnotationPresent(Asynchronous.class);

    // then
    assertTrue(isAsynchronous);
}
项目:oscm    文件:TaskQueueServiceBean.java   
@Override
@Asynchronous
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void sendAllMessages(List<TaskMessage> messages) {
    validateMessages(messages);
    double msgSize = Math.ceil(messages.size()/1000.0);
    int counter = 0;
    while(counter < msgSize) {
        int fromIndex = counter * 1000;
        int toIndex = Math.min(fromIndex + 1000, messages.size());
        sendObjectMessage(messages.subList(fromIndex, toIndex));
        counter++;
    }
}