@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8); message.setTo(to); message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } catch (Exception e) { log.warn("Email could not be sent to user '{}'", to, e); } }
@Async @Override public Future<List<GetPrizeDTO>> scheduleItems(ScheduleItem item) throws InterruptedException { log.info("Start Schedule with : " +item.getRecipientID()); log.info("query Type " + item.getQueryType()); Future<List<GetPrizeDTO>> result = new AsyncResult<>(new ArrayList<>()); if(item.getQueryType() == ConstantUtil.NORMAL_QUERY) { result = new AsyncResult<>(resultService.findPrizeByResultType(item.getLotteryType(), item.getParam().toArray(new String[]{}))); } else if(item.getQueryType() == ConstantUtil.CODE_RANGE_QUERY) { result = new AsyncResult<>(resultService.findPrizesByCode(item.getParam().get(0), item.getParam().get(1), item.getParam().get(2), item.getLotteryType())); } else if(item.getQueryType() == ConstantUtil.POINT_RANGE_QUERY) { result = new AsyncResult<>(resultService.findPrizesByPoints(item.getParam().get(0), item.getParam().get(1), item.getParam().get(2), item.getLotteryType())); } // remove from db after finding result. deleteScheduleItem(item.getRecipientID()); return result; }
@Override @Async @SuppressWarnings("unchecked") public void retrieveStateAndSend(final Identifier id, final Class aClass) { LOGGER.debug("Synchronizing on {} and {}...", id, aClass); synchronized (lockObject) { LOGGER.debug("Thread locked on {} and {}...!", id, aClass); final List<JpaGroup> groups; if (Jvm.class.getName().equals(aClass.getName())) { final JpaJvm jvm = jvmCrudService.getJvm(id); groups = jvm.getGroups(); } else if (WebServer.class.getName().equals(aClass.getName())) { final JpaWebServer webServer = webServerCrudService.getWebServerAndItsGroups(id.getId()); groups = webServer.getGroups(); } else { final String errMsg = "Invalid class parameter: " + aClass.getName() + "!"; LOGGER.error(errMsg); throw new GroupStateNotificationServiceException(errMsg); } fetchStates(groups, true); } LOGGER.debug("Thread locked on {} and {} released!", id, aClass); }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8); message.setTo(to); message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } catch (Exception e) { if (log.isDebugEnabled()) { log.warn("Email could not be sent to user '{}'", to, e); } else { log.warn("Email could not be sent to user '{}': {}", to, e.getMessage()); } } }
/** * {@inheritDoc} */ @Async @Override public void sendMailWithNewPassword( @NotBlank @Email final String email, @NotBlank final String newPassword ) { log.info("Called with e-mail {}, newPassword {}", email, newPassword); try { final JavaMailSenderImpl sender = new JavaMailSenderImpl(); final MimeMessage message = sender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(email); helper.setSubject("Recover password"); helper.setText("Your new password: " + "<b>" + newPassword + "</b>", true); sendMail(message); } catch (MessagingException e) { e.printStackTrace(); } }
/** * Sends an email message asynchronously through SendGrid. * Status Code: 202 - ACCEPTED: Your message is both valid, and queued to be delivered. * * @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 replyTo, String subject, String text) throws IOException { Email emailFrom = new Email(from); String emailSubject = subject; Email emailTo = new Email(recipient); Content emailContent = new Content("text/html", text); Mail mail = new Mail(emailFrom, emailSubject, emailTo, emailContent); if (!replyTo.isEmpty()) { Email emailReplyTo = new Email(replyTo); mail.setReplyTo(emailReplyTo); } SendGrid sg = new SendGrid(sendgridApiKey); Request request = new Request(); request.setMethod(Method.POST); request.setEndpoint("mail/send"); request.setBody(mail.build()); sg.api(request); }
@Async @Override public void addEmployee(EmployeeForm empForm) { Employee emp = new Employee(); emp.setDeptId(empForm.getEmpId()); emp.setFirstName(empForm.getFirstName()); emp.setLastName(empForm.getLastName()); emp.setAge(empForm.getAge()); emp.setBirthday(empForm.getBirthday()); emp.setEmail(empForm.getEmail()); emp.setDeptId(empForm.getDeptId()); emp.setEmpId(empForm.getEmpId()); try { System.out.println("service:addEmployee task executor: " + Thread.currentThread().getName()); System.out.println("processing for 1000 ms"); System.out.println("addEmployee @Async login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } employeeDaoImpl.addEmployeeBySJI(emp); }
@Async @Override public void handleExternalOutputMessage(final ExternalCommunicatorMessage message) { LOG.debug("Received request for external out message [{}]", message); final Long messageFlowId = getMessageFlowId(message.getTransferId()); final Long configId = getActiveConfig(messageFlowId); final Map<String, InternalObject> businessObjects = new HashMap<>(); message.getBusinessObjects().stream().forEachOrdered(bo -> { final Map<String, InternalField> fields = new HashMap<>(); bo.getFields().stream().forEachOrdered(field -> { fields.put(field.getName(), new InternalField(field.getName(), DataType.valueOf(field.getType()), field.getValue())); }); businessObjects.put(bo.getName(), new InternalObject(bo.getName(), fields)); }); composeSupervisorActor.tell(new ComposeMessageCreateCommand(message.getTransferId(), new InternalData(businessObjects), configId), ActorRef.noSender()); }
@Override @Async("selectiejob") public void start() { LOGGER.info("start selectie run service: "); BrpNu.set(); Thread.currentThread().setName("Selectie Job Runner"); final SelectieJobRunStatus status = selectieJobRunStatusService.newStatus(); Selectie selectie = null; try { selectie = selectieService.bepaalSelectie(); status.setStartDatum(new Date()); status.setSelectieRunId(selectie.getSelectierun().getId()); startSelectie(selectie); LOGGER.info("einde selectie run service: " + selectie.getSelectierun().getId()); } finally { status.setEindeDatum(new Date()); if (selectie != null) { selectieService.eindeSelectie(selectie); } } }
@Transactional @Async @Override public Future<List<TaskDTO>> getTasksOfUser(final Long userId) { final CompletableFuture<List<TaskDTO>> future = new CompletableFuture<>(); final TasksOfUserMessage.Request request = new TasksOfUserMessage.Request(userId); PatternsCS.ask(userSupervisorActor, request, Global.TIMEOUT).toCompletableFuture() .whenComplete((msg, exc) -> { if (exc == null) { future.complete(((TasksOfUserMessage.Response) msg).getTasks()); } else { future.completeExceptionally(exc); } }); return future; }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8); message.setTo(to); message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent e-mail to User '{}'", to); } catch (Exception e) { log.warn("E-mail could not be sent to user '{}'", to, e); } }
/** * パスワードリセット案内メールを送信します。 * * @param request パスワードリセット要求 */ @Async void sendPasswordResetMail(PasswordResetRequest request) { SimpleMailMessage message = new SimpleMailMessage(); message.setReplyTo(appReply); message.setTo(request.getMembership().getEmail()); message.setSubject("【パスワードリセット】Java研修 Go研修 OB・OG会"); message.setText(request.getMembership().getName() + " さん\n\n" + "パスワードリセットの要求を受け付けました。\n" + "下記 URL から 24 時間以内にパスワードリセットを行ってください。\n\n" + appUrl + "/#!" + ResetPasswordView.VIEW_NAME + "/" + request.getToken() + "\n" + "※トップページにリダイレクトされてしまう場合は、トップページを開いた画面 (タブ) のアドレス欄に" + "上記 URL を張り付けて移動してください。\n\n" + "本メールに関するお問合せ先: " + appReply + "\n" + "Java研修 Go研修 OB・OG会"); try { mailSender.send(message); } catch (MailException e) { exceptionHandler.accept(e); } }
@Async @Override public void asyncCreateInstance(DeploymentServiceImpl deploymentService, ServiceInstance serviceInstance, Map<String, String> parameters, Plan plan, PlatformService platformService) { progressService.startJob(serviceInstance); try { deploymentService.syncCreateInstance(serviceInstance, parameters, plan, platformService); } catch (Exception e) { progressService.failJob(serviceInstance, "Internal error during Instance creation, please contact our support."); log.error("Exception during Instance creation", e); return; } progressService.succeedProgress(serviceInstance); }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8); message.setTo(to); message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent e-mail to User '{}'", to); } catch (Exception e) { log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage()); } }
@Async public String createThumbnail(UserFile userFile) { String path = userFile.getPath(); Path originalImagePath = Paths.get(properties.getUploadFileRootPath(), path); try { BufferedImage originalImage = ImageIO.read(originalImagePath.toFile()); if (originalImage != null) { BufferedImage thumbnailImage = this.createThumbnailImage(originalImage, 300, 200); String ext = path.substring(path.lastIndexOf(".") + 1); Path thumbNailPath = Paths.get(properties.getUploadFileRootPath(), userFile.getThumbnailPath()); ImageIO.write(thumbnailImage, ext, Files.newOutputStream(thumbNailPath)); return thumbNailPath.toString(); } } catch (IOException e) { logger.error("Failed to create thumbnail of '{}'", path); } return ""; }
@Transactional @Async @Override public Future<ProcessInfoDTO> stopProcess(final Long piId) { final CompletableFuture<ProcessInfoDTO> future = new CompletableFuture<>(); final ProcessStopMessage.Request request = new ProcessStopMessage.Request(piId); PatternsCS.ask(processSupervisorActor, request, Global.TIMEOUT).toCompletableFuture() .whenComplete((msg, exc) -> { if (exc == null) { userSupervisorActor.tell(request, null); future.complete(((ProcessStopMessage.Response) msg).getProcess()); } else { future.completeExceptionally(exc); } }); return future; }
/** * 查询用户在线状态 * * @param fromUserId 用户ID * @param userIdList 查询列表 * @return * @since 1.0 */ @Async public ListenableFuture<List<IMBaseDefine.UserStat>> userStatusReq(Long fromUserId, List<Long> userIdList) { logger.debug("查询用户在线状态, user_cnt={}", userIdList.size()); List<IMBaseDefine.UserStat> userStatList = new ArrayList<>(); for (Long userId: userIdList) { UserClientInfoManager.UserClientInfo userClientInfo = userClientInfoManager.getUserInfo(userId); IMBaseDefine.UserStat.Builder userStatBuiler = IMBaseDefine.UserStat.newBuilder(); userStatBuiler.setUserId(userId); if (userClientInfo != null) { userStatBuiler.setStatus(userClientInfo.getStatus()); } else { userStatBuiler.setStatus(IMBaseDefine.UserStatType.USER_STATUS_OFFLINE); } userStatList.add(userStatBuiler.build()); } AsyncResult<List<IMBaseDefine.UserStat>> result = new AsyncResult<>(userStatList); return result; }
/** * 发送文本邮件 setCc 抄送 setBcc 密送 */ @Async("mailAsync") public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setBcc(from); message.setSubject(subject); message.setText(content); message.setSentDate(new Date()); try { mailSender.send(message); logger.info("简单邮件已经发送。"); } catch (Exception e) { logger.error("发送简单邮件时发生异常!", e); } }
@Async @Transactional public void recoverPasswordBy(String email) throws EmailException { User user = userService.findByEmail(email); if (user != null) { RecoverPassword recoverPassword = new RecoverPassword(user); emailService.send(email, recoverPassword.getToken()); recoverPasswordRepository.save(recoverPassword); } }
/** * Send password reset email. * * @param user object which stores info about user * @param url application url * @param tenantName tenant name * @param rid transaction id (use for logging) */ @Async public void sendPasswordResetMail(User user, String url, String tenantName, String rid) { MDCUtil.putRid(rid); log.info("Sending password reset email to '{}'", user.getEmail()); sendEmailFromTemplate( user, "passwordResetEmail", "email.reset.title", generateFrom(tenantName), user.getEmail(), url, tenantName ); }
@Async public Future<ResponseEntity<Boolean>> importProcessModel( final ImportProcessModelDTO processModelDTO, final HttpHeaderUser headerUser) { URIBuilder uri = null; try { uri = new URIBuilder(gatewayConfig.getProcessModelStorageAddress()).setPath("/import"); } catch (final URISyntaxException e) { LOG.error(e.getMessage()); } final HttpHeaders header = headerUser.getHttpHeaders(); return createRequest(uri, HttpMethod.POST, processModelDTO, Boolean.class, header); }
@Async public void attemptToInitialize() { // count the attempt setInitAttempts(getInitAttempts() + 1); logger.debug("initialization attempt " + getInitAttempts()); // first - get the service information or register service with metadata if(getService() != null) { // if we were able to get the service data we're registered setRegistered(true); // second - invoke any custom initialization method setInitialized(initialize(getServiceId())); } // if both are successful, then we're done if(isRegistered() && isInitialized()) { logger.info("initialization successful."); } else { // otherwise see if we need to keep going if((getInitRetries() == 0) || (getInitAttempts() < getInitRetries())) { logger.debug("initialization unsuccessful. sleeping " + getInitInterval()); try { Thread.sleep(getInitInterval()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // start up the next thread attemptToInitialize(); } else { // here, we've failed and run out of retries, so just be done. logger.info("initialization unsuccessful after " + getInitAttempts() + " attempts. Giving up."); // TODO: what do we do here? exit? Application.exit(-1); } } }
@Async public void sendEmailFromTemplate(User user, String templateName, String titleKey) { Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process(templateName, context); String subject = messageSource.getMessage(titleKey, null, locale); sendEmail(user.getEmail(), subject, content, false, true); }
@Async public Future<ResponseEntity<StateObjectDTO>> getStateObjectOfUserInProcess( final HttpHeaderUser headerUser, final Long piId, final Long userId) throws URISyntaxException { final URIBuilder uri = new URIBuilder(gatewayConfig.getProcessEngineAddress()) .setPath("/processes/task/" + piId + "/" + userId); final HttpHeaders header = headerUser.getHttpHeaders(); return createRequest(uri, HttpMethod.GET, null, StateObjectDTO.class, header); }
@Async public Future<ResponseEntity<Long>> getAmountOfFinishedProcessesInRange(final Long hoursbefore) throws URISyntaxException { final URIBuilder uri = new URIBuilder(gatewayConfig.getProcessEngineAddress()) .setPath("processes/count/finished/" + hoursbefore); return createRequest(uri, HttpMethod.GET, null, Long.class, null); }
@Async("myTaskAsyncPool") public Future<Integer> doAsyncTask(String tableName, List<EventData> dataList, String destination) { try { MDC.put("destination", destination); logger.info("thread: " + Thread.currentThread().getName() + " is doing job :" + tableName); for (EventData eventData : dataList) { SpringUtil.doEvent(eventData.getPath(), eventData.getDbObject()); } } catch (Exception e) { logger.error("thread:" + Thread.currentThread().getName() + " get Exception", e); return new AsyncResult(0); } return new AsyncResult(1); }
/** * saveTokenHistory * * @param token Token to re-verify to obtain Claims Set to Persist as a Token History Element. */ @Async protected void saveTokenHistory(String token) { try { /** * Generate a Token History Entry based upon our Current Supplied Token. */ JWTClaimsSet claimsSet = yourMicroserviceToken.verifyToken(token); if (claimsSet == null) { LOGGER.warn("Unable to Verify Token to retrieve ClaimsSet to Persist Token History, Ignoring."); return; } /** * Instantiate the Token History Entity. */ YourEntityTokenHistory yourEntityTokenHistory = new YourEntityTokenHistory(); yourEntityTokenHistory.setJti(claimsSet.getJWTID()); yourEntityTokenHistory.setSubject(claimsSet.getSubject()); yourEntityTokenHistory.setStatus(YourEntityTokenStatus.ACTIVE); yourEntityTokenHistory.setIssuedAt(claimsSet.getIssueTime()); yourEntityTokenHistory.setExpiration(claimsSet.getExpirationTime()); yourEntityTokenHistory.setNotUsedBefore(claimsSet.getNotBeforeTime()); yourEntityTokenHistory.setLastUsed(claimsSet.getIssueTime()); yourEntityTokenHistory.setUsageCount(1L); /** * Persist the Entity. */ yourEntityTokenHistory = identityProviderEntityManager.createTokenHistory(yourEntityTokenHistory); if (yourEntityTokenHistory == null) { LOGGER.warn("Unable to Persist Token History Entity, Ignoring."); } } catch (YourMicroserviceInvalidTokenException ite) { LOGGER.warn("Invalid Your Microservice Token Exception:'{}', Encountered while attempting " + "to persist Token History Entity.", ite.getMessage(), ite); } }
@Async("register") public CompletableFuture<List<String>> compileGroovy(String path) { logger.info("Start compile groovy file: " + path); List<String> listClassName = DynamicUtil.compileGroovyFile(path); try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("Complete compile groovy file: " + path); return CompletableFuture.completedFuture(listClassName); }
@Async public void attemptToInitialize() { // count the attempt setInitAttempts(getInitAttempts() + 1); logger.debug("initialization attempt " + getInitAttempts()); // first - get the service information or register service with metadata if (getService() != null) { // if we were able to get the service data we're registered setRegistered(true); // second - invoke any custom initialization method setInitialized(initialize(getServiceId())); } // if both are successful, then we're done if (isRegistered() && isInitialized()) { logger.info("initialization successful."); } else { // otherwise see if we need to keep going if ((getInitRetries() == 0) || (getInitAttempts() < getInitRetries())) { logger.debug("initialization unsuccessful. sleeping " + getInitInterval()); try { Thread.sleep(getInitInterval()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // start up the next thread attemptToInitialize(); } else { // here, we've failed and run out of retries, so just be done. logger.info("initialization unsuccessful after " + getInitAttempts() + " attempts. Giving up."); // TODO: what do we do here? exit? Application.exit(-1); } } }
@Async public void attemptToInitialize() { // count the attempt setInitAttempts(getInitAttempts() + 1); logger.debug("initialization attempt " + getInitAttempts()); // first - get the service information or register service with metadata if (getService() != null) { // if we were able to get the service data we're registered setRegistered(true); // second - invoke any custom initialization method setInitialized(initialize(getServiceId())); } // if both are successful, then we're done if (isRegistered() && isInitialized()) { logger.info("initialization successful."); } else { // otherwise see if we need to keep going if ((getInitRetries() == 0) || (getInitAttempts() < getInitRetries())) { logger.debug("initialization unsuccessful. sleeping " + getInitInterval()); try { Thread.sleep(getInitInterval()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // start up the next thread attemptToInitialize(); } else { // here, we've failed and run out of retries, so just be done. logger.info( "initialization unsuccessful after " + getInitAttempts() + " attempts. Giving up."); // TODO: what do we do here? exit? Application.exit(-1); } } }
/** * Send event to kafka. * @param content the event data */ @Async public void send(String content) { if (StringUtils.isNoneBlank(content)) { log.debug("Sending kafka event with data {} to topic {}", content, topicName); template.send(topicName, content); } }
@Async public void sendActivationEmail(User user) { log.debug("Sending activation e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process("activationEmail", context); String subject = messageSource.getMessage("email.activation.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); }