javax.ejb.Asynchronous Java Examples

The following examples show how to use javax.ejb.Asynchronous. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AlertsPublisher.java    From hawkular-apm with Apache License 2.0 7 votes vote down vote up
@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);
}
 
Example #2
Source File: NotifierBean.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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);
    }
}
 
Example #3
Source File: ParalellizerWorker.java    From training with MIT License 6 votes vote down vote up
@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
	}
 
Example #4
Source File: BotService.java    From monolith with Apache License 2.0 6 votes vote down vote up
@Asynchronous
public void deleteAll() {
    synchronized (bot) {
        stop();
        // Delete 10 bookings at a time
        while(true) {
            MultivaluedMap<String,String> params = new MultivaluedHashMap<>();
            params.add("maxResults", Integer.toString(10));
            List<Booking> bookings = bookingService.getAll(params);
            for (Booking booking : bookings) {
                bookingService.deleteBooking(booking.getId());
                event.fire("Deleted booking " + booking.getId() + " for "
                        + booking.getContactEmail() + "\n");
            }
            if(bookings.size() < 1) {
                break;
            }
        }
    }
}
 
Example #5
Source File: BotService.java    From monolith with Apache License 2.0 6 votes vote down vote up
@Asynchronous
public void deleteAll() {
    synchronized (bot) {
        stop();
        // Delete 10 bookings at a time
        while(true) {
            MultivaluedMap<String,String> params = new MultivaluedHashMap<>();
            params.add("maxResults", Integer.toString(10));
            List<Booking> bookings = bookingService.getAll(params);
            for (Booking booking : bookings) {
                bookingService.deleteBooking(booking.getId());
                event.fire("Deleted booking " + booking.getId() + " for "
                        + booking.getContactEmail() + "\n");
            }
            if(bookings.size() < 1) {
                break;
            }
        }
    }
}
 
Example #6
Source File: BotService.java    From monolith with Apache License 2.0 6 votes vote down vote up
@Asynchronous
public void deleteAll() {
    synchronized (bot) {
        stop();
        // Delete 10 bookings at a time
        while(true) {
            MultivaluedMap<String,String> params = new MultivaluedHashMap<>();
            params.add("maxResults", Integer.toString(10));
            List<Booking> bookings = bookingService.getAll(params);
            for (Booking booking : bookings) {
                bookingService.deleteBooking(booking.getId());
                event.fire("Deleted booking " + booking.getId() + " for "
                        + booking.getContactEmail() + "\n");
            }
            if(bookings.size() < 1) {
                break;
            }
        }
    }
}
 
Example #7
Source File: HealthServiceImpl.java    From aerogear-unifiedpush-server with Apache License 2.0 6 votes vote down vote up
@Asynchronous
@Override
public Future<HealthDetails> dbStatus() {
    HealthDetails details = new HealthDetails();
    details.setDescription("Database connection");
    details.start();
    try {
        logger.trace("Call the DB if it is online");
        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);
}
 
Example #8
Source File: NotifierBean.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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 admin does not exist anymore as the workspace has been deleted
        sendMessage(admin, "WorkspaceDeletion_title", "WorkspaceDeletion_text", args);
    } catch (MessagingException pMEx) {
        logMessagingException(pMEx);
    }
}
 
Example #9
Source File: ClientInstallationServiceImpl.java    From aerogear-unifiedpush-server with Apache License 2.0 6 votes vote down vote up
@Override
@Asynchronous
public Future<Void>  unsubscribeOldTopics(Installation installation) {
    FCMTopicManager topicManager = new FCMTopicManager((AndroidVariant) installation.getVariant());
    Set<String> oldCategories = topicManager.getSubscribedCategories(installation);
    // Remove current categories from the set of old ones
    oldCategories.removeAll(convertToNames(installation.getCategories()));

    // Remove global variant topic because we don't want to unsubscribe it
    oldCategories.remove(installation.getVariant().getVariantID());

    for (String categoryName : oldCategories) {
        topicManager.unsubscribe(installation, categoryName);
    }
    return new AsyncResult<>(null);
}
 
Example #10
Source File: HealthNetworkServiceImpl.java    From aerogear-unifiedpush-server with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: NotifierBean.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@Asynchronous
@Override
public void sendCredential(Account account) {
    String accountDisabledMessage = "";
    if (!account.isEnabled()) {
        switch (platformOptionsManager.getWorkspaceCreationStrategy()) {
            case ADMIN_VALIDATION:
                accountDisabledMessage = getString("SignUp_AccountDisabled_text", account.getLocale());
                break;
        }
    }

    Object[] args = {
            account.getLogin(),
            configManager.getCodebase(),
            accountDisabledMessage
    };

    try {
        sendMessage(account, "SignUp_success_title", "SignUp_success_text", args);
    } catch (MessagingException pMEx) {
        logMessagingException(pMEx);
    }
}
 
Example #12
Source File: QueryExecutorBean.java    From datawave with Apache License 2.0 6 votes vote down vote up
@POST
@Produces("*/*")
@Path("/{logicName}/async/execute")
@GZIP
@Interceptors({ResponseInterceptor.class, RequiredInterceptor.class})
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Asynchronous
@Timed(name = "dw.query.executeQueryAsync", absolute = true)
public void executeAsync(@PathParam("logicName") String logicName, MultivaluedMap<String,String> queryParameters, @Context HttpHeaders httpHeaders,
                @Suspended AsyncResponse asyncResponse) {
    try {
        StreamingOutput output = execute(logicName, queryParameters, httpHeaders);
        asyncResponse.resume(output);
    } catch (Throwable t) {
        asyncResponse.resume(t);
    }
}
 
Example #13
Source File: NotifierBean.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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);
    }
}
 
Example #14
Source File: QueryExecutorBean.java    From datawave with Apache License 2.0 6 votes vote down vote up
@POST
@Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf",
        "application/x-protostuff"})
@Path("/{logicName}/async/createAndNext")
@GZIP
@GenerateQuerySessionId(cookieBasePath = "/DataWave/Query/")
@EnrichQueryMetrics(methodType = MethodType.CREATE_AND_NEXT)
@Interceptors({ResponseInterceptor.class, RequiredInterceptor.class})
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Asynchronous
@Timed(name = "dw.query.createAndNextAsync", absolute = true)
public void createQueryAndNextAsync(@Required("logicName") @PathParam("logicName") String logicName, MultivaluedMap<String,String> queryParameters,
                @Suspended AsyncResponse asyncResponse) {
    try {
        BaseQueryResponse response = createQueryAndNext(logicName, queryParameters);
        asyncResponse.resume(response);
    } catch (Throwable t) {
        asyncResponse.resume(t);
    }
}
 
Example #15
Source File: QueryExecutorBean.java    From datawave with Apache License 2.0 6 votes vote down vote up
@POST
@Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf",
        "application/x-protostuff"})
@Path("/{logicName}/async/create")
@GZIP
@GenerateQuerySessionId(cookieBasePath = "/DataWave/Query/")
@EnrichQueryMetrics(methodType = MethodType.CREATE)
@Interceptors({RequiredInterceptor.class, ResponseInterceptor.class})
@Asynchronous
@Timed(name = "dw.query.createQueryAsync", absolute = true)
public void createQueryAsync(@Required("logicName") @PathParam("logicName") String queryLogicName, MultivaluedMap<String,String> queryParameters,
                @Suspended AsyncResponse asyncResponse) {
    try {
        GenericResponse<String> response = createQuery(queryLogicName, queryParameters);
        asyncResponse.resume(response);
    } catch (Throwable t) {
        asyncResponse.resume(t);
    }
}
 
Example #16
Source File: ThreadExecutorEjb.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@Asynchronous
public void executeTask(Runnable work, Object config) {
    try {
        userTransactions.set(ut);
        if (work instanceof BatchWorkUnit) {
            runningBatchWorkUnits.add((BatchWorkUnit) work);
        }

        work.run();
    } finally {
        if (work instanceof BatchWorkUnit) {
            runningBatchWorkUnits.remove(work);
        }
        userTransactions.remove();
    }
}
 
Example #17
Source File: TaskQueueServiceBean.java    From development with Apache License 2.0 5 votes vote down vote up
@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++;
    }
}
 
Example #18
Source File: AsynchInRoleTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
@Asynchronous
public Future<String> testB(final long callerThreadId) {
    Assert.assertFalse("testB should be executed in asynchronous mode", Thread.currentThread().getId() == callerThreadId);
    lastInvokeMethod = "testB";
    return new AsyncResult<>("testB");
}
 
Example #19
Source File: AsynchInRoleTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
@Asynchronous
public void testD(final long callerThreadId) {
    Assert.assertFalse("testD should be executed in asynchronous mode", Thread.currentThread().getId() == callerThreadId);
    Exception expectedException = null;
    try {
        sessionContext.wasCancelCalled();
    } catch (final IllegalStateException e) {
        expectedException = e;
    }
    Assert.assertNotNull("IllegalStateException should be thrown", expectedException);
    lastInvokeMethod = "testD";
}
 
Example #20
Source File: ClientInstallationServiceImpl.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Override
@Asynchronous
public Future<Void>  removeInstallationsForVariantByDeviceTokens(String variantID, Set<String> deviceTokens) {
    // collect inactive installations for the given variant:
    List<Installation> inactiveInstallations = installationDao.findInstallationsForVariantByDeviceTokens(variantID, deviceTokens);
    // get rid of them
    this.removeInstallations(inactiveInstallations);
    return new AsyncResult<>(null);
}
 
Example #21
Source File: BusyBee.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Asynchronous
public Future stayBusy(CountDownLatch ready) {
    ready.countDown();

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

    return null;
}
 
Example #22
Source File: JobProcessor.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Asynchronous
@Lock(READ)
@AccessTimeout(-1)
public Future<String> addJob(String jobName) {

    // Pretend this job takes a while
    doSomeHeavyLifting();

    // Return our result
    return new AsyncResult<String>(jobName);
}
 
Example #23
Source File: BusyBee.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Asynchronous
public Future stayBusy(CountDownLatch ready) {
    ready.countDown();

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

    return null;
}
 
Example #24
Source File: TheSlowWork.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Asynchronous
public void waitAndShowResult(Future<Integer> value){
   try {
      LOG.info("Result="+value.get());
   } catch (InterruptedException | ExecutionException e) {
      LOG.log(Level.INFO,"Error!",e);
   }
}
 
Example #25
Source File: IdentityServiceBean.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
@Asynchronous
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void notifySubscriptionsAboutUserUpdate(PlatformUser existingUser) {

    // 2. notify all products the user is subscribed to
    List<Subscription> subscriptions = sm
            .getSubscriptionsForUserInt(existingUser);
    List<TaskMessage> messages = new ArrayList<>();
    for (Subscription subscription : subscriptions) {
        SubscriptionStatus status = subscription.getStatus();
        // in these states the product instance is not existing
        if (status != SubscriptionStatus.PENDING
                && status != SubscriptionStatus.INVALID) {
            UsageLicense license = getUsgeLicenseForUserAndSubscription(
                    existingUser, subscription);
            if (license != null) {
                UpdateUserPayload payload = new UpdateUserPayload(
                        subscription.getKey(), license.getKey());
                TaskMessage message = new TaskMessage(
                        UpdateUserHandler.class, payload);
                messages.add(message);
            }
        }
    }
    tqs.sendAllMessages(messages);

}
 
Example #26
Source File: GCMSenderBean.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Asynchronous
public void sendIterationNotification(GCMAccount[] pGCGcmAccounts, DocumentRevision documentRevision) {
    for(GCMAccount gcmAccount:pGCGcmAccounts){
        sendIterationNotification(gcmAccount, documentRevision);
    }
}
 
Example #27
Source File: AsynchInRoleTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
@Asynchronous
public Future<String> testB(final long callerThreadId) {
    Assert.assertFalse("testB should be executed in asynchronous mode", Thread.currentThread().getId() == callerThreadId);
    lastInvokeMethod = "testB";
    return new AsyncResult<>("testB");
}
 
Example #28
Source File: AsynchTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
@Asynchronous
public Future<String> testB(final long callerThreadId) {
    Assert.assertFalse("testB should be executed in asynchronous mode", Thread.currentThread().getId() == callerThreadId);
    lastInvokeMethod = "testB";
    return new AsyncResult<>("testB");
}
 
Example #29
Source File: EjbAsyncResource.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@GET
@Asynchronous
public void getAsync(final @Suspended AsyncResponse res) {

    //perform long run operations.
    try {
        LOG.log(Level.INFO, " execute long run task in EjbAsyncResource");
        Thread.sleep(500);
    } catch (InterruptedException ex) {
        LOG.log(Level.SEVERE, "error :" +ex.getMessage());
    }

    res.resume(Response.ok("Asynchronus EJB resource").build());
}
 
Example #30
Source File: GCMSenderBean.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Asynchronous
public void sendStateNotification(GCMAccount[] pGCGcmAccounts, DocumentRevision documentRevision) {
    for(GCMAccount gcmAccount:pGCGcmAccounts){
        sendStateNotification(gcmAccount,documentRevision);
    }
}