List of usage examples for org.apache.commons.lang3.time DateUtils addMinutes
public static Date addMinutes(final Date date, final int amount)
From source file:io.lavagna.service.NotificationServiceTest.java
@Test public void sendEmailTest() { Date creationDate = DateUtils.addMinutes(new Date(), -3); labelService.addLabelValueToCard(assignedLabel.getId(), card1.getId(), new CardLabelValue.LabelValue(null, null, null, null, user.getId(), null), user, creationDate); labelService.addLabelValueToCard(watchedLabel.getId(), card2.getId(), new CardLabelValue.LabelValue(null, null, null, null, user.getId(), null), user, creationDate); cardDataService.createComment(card1.getId(), "first comment", creationDate, user.getId()); cardDataService.createComment(card2.getId(), "first comment on card 2", creationDate, user.getId()); MailConfig mc = mock(MailConfig.class); when(mc.isMinimalConfigurationPresent()).thenReturn(true); when(mc.getFrom()).thenReturn("from@lavagna.io"); notificationService.notifyUser(user.getId(), new Date(), true, mc); verify(mc).send(eq("test@test.test"), eq("Lavagna: TEST-BRD-1, TEST-BRD-2"), any(String.class), any(String.class)); }
From source file:com.nridge.examples.oss.datatable.DataTableTask.java
private DataTable createPopulateTable() { int rowValue; String textValue;// w w w .ja v a2 s. co m // Create our field definitions for the data table. DataTable dataTable = new DataTable("Data Table"); dataTable.add(new DataLongField("long_field", "Long Field")); dataTable.add(new DataTextField("text_field", "Text Field")); dataTable.add(new DataFloatField("float_field", "Float Field")); dataTable.add(new DataDoubleField("double_field", "Double Field")); dataTable.add(new DataIntegerField("integer_field", "Integer Field")); dataTable.add(new DataBooleanField("boolean_field", "Boolean Field")); dataTable.add(new DataDateTimeField("datetime_field", "Date/Time Field")); Date nowDate = new Date(); for (int row = 0; row < TOTAL_ROW_COUNT; row++) { dataTable.newRow(); rowValue = row + 1; dataTable.setValueByName("integer_field", rowValue); dataTable.setValueByName("long_field", (long) rowValue); dataTable.setValueByName("float_field", (float) rowValue); dataTable.setValueByName("double_field", (double) rowValue); dataTable.setValueByName("boolean_field", NumUtl.isOdd(rowValue)); dataTable.setValueByName("datetime_field", DateUtils.addMinutes(nowDate, rowValue)); dataTable.setValueByName("datetime_field", DateUtils.addMinutes(nowDate, rowValue), Field.FORMAT_DATETIME_DEFAULT); textValue = String.format("This is a test sentence %d of %d rows.", rowValue, TOTAL_ROW_COUNT); dataTable.setValueByName("text_field", textValue); dataTable.addRow(); } return dataTable; }
From source file:alfio.controller.api.user.RestEventApiController.java
@RequestMapping(value = "events/{shortName}/reserve-tickets", method = RequestMethod.POST) public ResponseEntity<Result<String>> reserveTickets(@PathVariable("shortName") String shortName, @RequestBody ReservationForm reservation, BindingResult bindingResult, Locale locale) { return eventRepository.findOptionalByShortName(shortName).map(event -> { Optional<String> reservationUrl = reservation.validate(bindingResult, ticketReservationManager, additionalServiceRepository, eventManager, event).flatMap(selected -> { Date expiration = DateUtils.addMinutes(new Date(), ticketReservationManager.getReservationTimeout(event)); try { String reservationId = ticketReservationManager.createTicketReservation(event, selected.getLeft(), selected.getRight(), expiration, Optional.ofNullable(reservation.getPromoCode()), //FIXME check Optional.ofNullable(reservation.getPromoCode()), //FIXME check locale, false); return Optional.of("/event/" + shortName + "/reservation/" + reservationId + "/book"); } catch (TicketReservationManager.NotEnoughTicketsException nete) { bindingResult.reject(ErrorsCode.STEP_1_NOT_ENOUGH_TICKETS); } catch (TicketReservationManager.MissingSpecialPriceTokenException missing) { bindingResult.reject(ErrorsCode.STEP_1_ACCESS_RESTRICTED); } catch (TicketReservationManager.InvalidSpecialPriceTokenException invalid) { bindingResult.reject(ErrorsCode.STEP_1_CODE_NOT_FOUND); }//from w w w .ja v a2 s . c o m return Optional.empty(); }); Result<String> result = reservationUrl.map(url -> Result.success(url)) .orElseGet(() -> Result.validationError(bindingResult.getAllErrors())); return new ResponseEntity<>(result, HttpStatus.OK); }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); }
From source file:com.nridge.core.app.mgr.ServiceTimer.java
private Date getNextTS(String aFieldName, Date aTS) { String timeString = getAppString(aFieldName); if (StringUtils.isNotEmpty(timeString)) { if (StringUtils.endsWithIgnoreCase(timeString, "m")) { String minuteString = StringUtils.stripEnd(timeString, "m"); if ((StringUtils.isNotEmpty(minuteString)) && (StringUtils.isNumeric(minuteString))) { int minuteAmount = Integer.parseInt(minuteString); return DateUtils.addMinutes(aTS, minuteAmount); }/* w w w. j a v a2 s .c om*/ } else if (StringUtils.endsWithIgnoreCase(timeString, "h")) { String hourString = StringUtils.stripEnd(timeString, "h"); if ((StringUtils.isNotEmpty(hourString)) && (StringUtils.isNumeric(hourString))) { int hourAmount = Integer.parseInt(hourString); return DateUtils.addHours(aTS, hourAmount); } } else // we assume days { String dayString = StringUtils.stripEnd(timeString, "d"); if ((StringUtils.isNotEmpty(dayString)) && (StringUtils.isNumeric(dayString))) { int dayAmount = Integer.parseInt(dayString); return DateUtils.addDays(aTS, dayAmount); } } } // Push 1 hour ahead to avoid triggering a match with TS return DateUtils.addHours(new Date(), 1); }
From source file:io.lavagna.service.NotificationServiceTest.java
@Test public void sendEmailTestWithoutMyEvents() { Date creationDate = DateUtils.addMinutes(new Date(), -3); userRepository.updateProfile(user, user.getEmail(), user.getDisplayName(), true, true); labelService.addLabelValueToCard(assignedLabel.getId(), card1.getId(), new CardLabelValue.LabelValue(null, null, null, null, user.getId(), null), user, creationDate); labelService.addLabelValueToCard(watchedLabel.getId(), card2.getId(), new CardLabelValue.LabelValue(null, null, null, null, user.getId(), null), user, creationDate); cardDataService.createComment(card1.getId(), "first comment", creationDate, user.getId()); cardDataService.createComment(card2.getId(), "first comment on card 2", creationDate, otherUser.getId()); MailConfig mc = mock(MailConfig.class); when(mc.isMinimalConfigurationPresent()).thenReturn(true); when(mc.getFrom()).thenReturn("from@lavagna.io"); notificationService.notifyUser(user.getId(), new Date(), true, mc); verify(mc).send(eq("test@test.test"), eq("Lavagna: TEST-BRD-2"), any(String.class), any(String.class)); }
From source file:com.nridge.examples.oss.ds_rdbms.DSRDBMSTask.java
private SQLConnection createPopulateRDBMS() { int rowValue; String textValue;//from w w w.java 2 s . c o m SQLConnection sqlConnection; Logger appLogger = mAppMgr.getLogger(this, "createPopulateRDBMS"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); // Create our field definitions for the data table. DataTable dataTable = createDataTable(); // Create a SQL connection, table object and populate it in the RDBMS. try { sqlConnection = new SQLConnection(mAppMgr, SQL.PROPERTY_PREFIX_DEFAULT); SQLTable sqlTable = sqlConnection.newTable(Field.SQL_TABLE_TYPE_MEMORY); DataBag dataBag = new DataBag(dataTable.getColumnBag()); dataBag.setName(RDBMS_TABLE_NAME); sqlTable.create(dataBag); Date nowDate = new Date(); for (int row = 0; row < TOTAL_ROW_COUNT; row++) { dataBag.resetValues(); rowValue = row + 1; dataBag.setValueByName("integer_field", rowValue); dataBag.setValueByName("long_field", (long) rowValue); dataBag.setValueByName("float_field", (float) rowValue); dataBag.setValueByName("double_field", (double) rowValue); dataBag.setValueByName("boolean_field", NumUtl.isOdd(rowValue)); dataBag.setValueByName("datetime_field", DateUtils.addMinutes(nowDate, rowValue)); dataBag.setValueByName("datetime_field", DateUtils.addMinutes(nowDate, rowValue)); textValue = String.format("This is a test sentence %d of %d rows.", rowValue, TOTAL_ROW_COUNT); dataBag.setValueByName("text_field", textValue); sqlTable.insert(dataBag); if ((row > 0) && ((row % 50) == 0)) sqlTable.commit(); } sqlTable.commit(); } catch (NSException e) { e.printStackTrace(); sqlConnection = null; } return sqlConnection; }
From source file:alfio.manager.PaypalManager.java
public String createCheckoutRequest(Event event, String reservationId, OrderSummary orderSummary, CustomerName customerName, String email, String billingAddress, Locale locale, boolean postponeAssignment) throws Exception { APIContext apiContext = getApiContext(event); Optional<String> experienceProfileId = getOrCreateWebProfile(event, locale, apiContext); List<Transaction> transactions = buildPaymentDetails(event, orderSummary, reservationId, locale); String eventName = event.getShortName(); Payer payer = new Payer(); payer.setPaymentMethod("paypal"); Payment payment = new Payment(); payment.setIntent("sale"); payment.setPayer(payer);//from w w w . j ava 2s .c o m payment.setTransactions(transactions); RedirectUrls redirectUrls = new RedirectUrls(); String baseUrl = StringUtils.removeEnd( configurationManager.getRequiredValue( Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)), "/"); String bookUrl = baseUrl + "/event/" + eventName + "/reservation/" + reservationId + "/book"; UriComponentsBuilder bookUrlBuilder = UriComponentsBuilder.fromUriString(bookUrl) .queryParam("fullName", customerName.getFullName()) .queryParam("firstName", customerName.getFirstName()) .queryParam("lastName", customerName.getLastName()).queryParam("email", email) .queryParam("billingAddress", billingAddress).queryParam("postponeAssignment", postponeAssignment) .queryParam("hmac", computeHMAC(customerName, email, billingAddress, event)); String finalUrl = bookUrlBuilder.toUriString(); redirectUrls.setCancelUrl(finalUrl + "&paypal-cancel=true"); redirectUrls.setReturnUrl(finalUrl + "&paypal-success=true"); payment.setRedirectUrls(redirectUrls); experienceProfileId.ifPresent(payment::setExperienceProfileId); Payment createdPayment = payment.create(apiContext); TicketReservation reservation = ticketReservationRepository.findReservationById(reservationId); //add 15 minutes of validity in case the paypal flow is slow ticketReservationRepository.updateValidity(reservationId, DateUtils.addMinutes(reservation.getValidity(), 15)); if (!"created".equals(createdPayment.getState())) { throw new Exception(createdPayment.getFailureReason()); } //extract url for approval return createdPayment.getLinks().stream().filter(l -> "approval_url".equals(l.getRel())).findFirst() .map(Links::getHref).orElseThrow(IllegalStateException::new); }
From source file:com.aurel.track.item.history.HistorySaverBL.java
/** * Builds the trail text for history/*from www. jav a2 s .co m*/ * @param fieldChanges Map with FieldChange values * @param longFields the fields with longer texts (description, comment). This will be added at the end of the trail text * @param locale * @param isNew whether creating a new issue (isCreate || isCopy) or editing an existing one * @param newLineString * * @return */ private static boolean persistHistory(SortedMap<Integer, FieldChange> fieldChanges, AfterItemSaveEventParam afterItemSaveEventParam, Integer personID, List<Integer> longFields, Locale locale, boolean isCreate, boolean isCopy, Integer fieldChangeID) { SortedMap<Integer, FieldChange> historyLongTextMap = new TreeMap<Integer, FieldChange>(); //maintain order TWorkItemBean workItemBeanNew = afterItemSaveEventParam.getWorkItemNew(); TWorkItemBean workItemBeanOld = afterItemSaveEventParam.getWorkItemOld(); boolean needHistoryTransaction = false; if (isCreate || isCopy) { //need first status in history needHistoryTransaction = true; } Map<Integer, TFieldChangeBean> lastHistoryFieldChangesMap = null; if (!needHistoryTransaction && fieldChanges != null) { //gather the fields with explicit history List<Integer> explicitHistoryFields = new LinkedList<Integer>(); int minutes = GeneralSettings.getHistoryAndEmailDelay(); for (FieldChange fieldChange : fieldChanges.values()) { if (fieldChange.isChanged()) { needHistoryTransaction = true; if (minutes == 0 || minutes < 0) { //no need to handle recent history changes break; } Integer fieldID = fieldChange.getFieldID(); if (fieldChange.isExplicitHistory() && !SystemFields.INTEGER_STATE.equals(fieldID) && !SystemFields.INTEGER_COMMENT.equals(fieldID)) { //the status field although is hardcoded to have explicit history but me make it exception from rule. //(the status change will be added to the history even the last status change happened within x minutes) //the comment should be added in the history anyway explicitHistoryFields.add(fieldChange.getFieldID()); } } } if (!explicitHistoryFields.isEmpty()) { Date targetTime = new Date(); //now targetTime = DateUtils.addMinutes(targetTime, -minutes); Map<Integer, THistoryTransactionBean> lastHistoryTransactionsMap = GeneralUtils.createMapFromList( HistoryTransactionBL.loadByItemAndFieldsSince(workItemBeanNew.getObjectID(), explicitHistoryFields, targetTime)); List<TFieldChangeBean> lastFieldChanges = FieldChangeBL .loadByItemAndFieldsSince(workItemBeanNew.getObjectID(), explicitHistoryFields, targetTime); lastHistoryFieldChangesMap = new HashMap<Integer, TFieldChangeBean>(); for (TFieldChangeBean fieldChangeBean : lastFieldChanges) { Integer transactionID = fieldChangeBean.getHistoryTransaction(); Integer fieldID = fieldChangeBean.getFieldKey(); THistoryTransactionBean historyTransactionBean = lastHistoryTransactionsMap.get(transactionID); if (historyTransactionBean != null) { //only the first found Integer changedByPersonID = historyTransactionBean.getChangedByID(); if (personID.equals(changedByPersonID) && lastHistoryFieldChangesMap.get(fieldID) == null) { lastHistoryFieldChangesMap.put(fieldID, fieldChangeBean); } explicitHistoryFields.remove(fieldID); if (explicitHistoryFields.isEmpty()) { break; } } } } } boolean mightTriggerEmail = false; if (!needHistoryTransaction) { return false; } //Integer historyTransactionID = HistoryTransactionBL.saveHistoryTransaction(workItemBeanNew.getObjectID(), personID, new Date(), null); if (isCreate || isCopy) { //add the first status change history entry if not deep copy if (!workItemBeanNew.isDeepCopy()) { //with deep copy the status changes will be copied also no need for first status change in history //set null for workItemBeanOld parameter (by create is null anyway) because otherwise the //values are the same and will not be saved Integer statusTransactionID = HistoryTransactionBL .saveHistoryTransaction(workItemBeanNew.getObjectID(), personID, new Date(), null); saveExplicitField(SystemFields.INTEGER_STATE, statusTransactionID, workItemBeanNew, null, null); } mightTriggerEmail = true; } StringBuilder compoundTextNewBuffer = new StringBuilder(); StringBuilder compoundTextOldBuffer = new StringBuilder(); if (isCopy) { Object[] msgArguments = null; String messageKey = null; if (ApplicationBean.getInstance().getSiteBean().getProjectSpecificIDsOn()) { String projectSpecificID = SystemProjectSpecificIssueNoRT .getShowValue(workItemBeanOld.getIDNumber(), workItemBeanOld); msgArguments = new Object[] { projectSpecificID }; messageKey = "item.history.copyMessageProjectSpecificID"; } else { msgArguments = new Object[] { workItemBeanOld.getObjectID() }; messageKey = "item.history.copyMessage"; } compoundTextNewBuffer.append(LocalizeUtil.getParametrizedString(messageKey, msgArguments, locale)); } Set<Integer> attachmentHistoryFields = HistoryLoaderBL.getAttachmentHistoryFields(); Integer historyTransactionID = null; for (Map.Entry<Integer, FieldChange> entry : fieldChanges.entrySet()) { FieldChange fieldChange = (FieldChange) entry.getValue(); Integer fieldID = fieldChange.getFieldID(); String fieldLabel = fieldChange.getLocalizedFieldLabel(); String newValue = fieldChange.getNewShowValue(); String oldValue = fieldChange.getOldShowValue(); //For history text we are interested in: //1. all field changes for existing issues //2. "Comment" for new issues //For that the fieldChange.isChanged() should be set accordingly already if (!fieldChange.isChanged()) { continue; } if (attachmentHistoryFields.contains(fieldID)) { Integer attachmentChangeTransactionID = HistoryTransactionBL .saveHistoryTransaction(workItemBeanNew.getObjectID(), personID, new Date(), null); insertFieldChange(attachmentChangeTransactionID, fieldID, newValue, oldValue); mightTriggerEmail = true; continue; } if (fieldChange.isExplicitHistory() || SystemFields.INTEGER_COMMENT.equals(fieldID)) { TFieldChangeBean fieldChangeBean = null; boolean isCommentChange = false; if (fieldChangeID == null) { if (lastHistoryFieldChangesMap != null) { fieldChangeBean = lastHistoryFieldChangesMap.get(fieldID); } if (fieldChangeBean == null) { //no previous entry within x minutes mightTriggerEmail = true; } } else { isCommentChange = true; fieldChangeBean = FieldChangeBL.loadByPrimaryKey(fieldChangeID); mightTriggerEmail = true; } if (historyTransactionID == null && !isCommentChange) { historyTransactionID = HistoryTransactionBL .saveHistoryTransaction(workItemBeanNew.getObjectID(), personID, new Date(), null); } saveExplicitField(fieldID, historyTransactionID, workItemBeanNew, workItemBeanOld, fieldChangeBean); //the comment is saved anyway explicitly in the history as Comment field //even if explicit history is not configured. //Explicit history for comment means whether to historize the comment changes (edit and delete). //The field set into the workitemContext is COMMENT also for edit and delete comment //(instead of COMMENT_DELETE_HISTORY_FIELD or COMMENT_MODIFY_HISTORY_FIELD) comment because //we need the explicit history flag which is set only for COMMENT field (the other two are only pseudo fields) if (fieldChange.isExplicitHistory() && SystemFields.INTEGER_COMMENT.equals(fieldID)) { if (oldValue != null && !"".equals(oldValue)) { //history only if the comment is edited or deleted Integer commentChangeTransactionID = HistoryTransactionBL .saveHistoryTransaction(workItemBeanNew.getObjectID(), personID, new Date(), null); if (newValue == null || "".equals(newValue)) { insertFieldChange(commentChangeTransactionID, SystemFields.COMMENT_DELETE_HISTORY_FIELD, newValue, oldValue); } else { insertFieldChange(commentChangeTransactionID, SystemFields.COMMENT_MODIFY_HISTORY_FIELD, newValue, oldValue); } } } } else { //fields without explicit history if (longFields.contains(fieldID)) { //gather the changed long fields to add them at the end historyLongTextMap.put(fieldID, fieldChange); mightTriggerEmail = true; } else { if (newValue != null && !"".equals(newValue)) { if (compoundTextNewBuffer.length() > 0) { //some content already present compoundTextNewBuffer.append(commonFieldsSeparator + lineBreak); } compoundTextNewBuffer.append(fieldLabel + fieldLabelSeparator + newValue); mightTriggerEmail = true; } if (oldValue != null && !"".equals(oldValue)) { if (compoundTextOldBuffer.length() > 0) { //some content already present compoundTextOldBuffer.append(commonFieldsSeparator + lineBreak); } compoundTextOldBuffer.append(fieldLabel + fieldLabelSeparator + oldValue); mightTriggerEmail = true; } } } } //add the longText changes at the end //add the commonFieldsSeparator only after the last short field //after long fields (HTML text) it does not make sense (for ex. after a <p>) boolean firstLongField = true; for (Map.Entry<Integer, FieldChange> entry : historyLongTextMap.entrySet()) { FieldChange fieldChange = entry.getValue(); if (fieldChange != null) { if (compoundTextNewBuffer.length() > 0) { //some content already present if (firstLongField) { compoundTextNewBuffer.append(commonFieldsSeparator + lineBreak); } else { compoundTextNewBuffer.append(lineBreak); } } if (compoundTextOldBuffer.length() > 0) { //some content already present if (firstLongField) { compoundTextOldBuffer.append(commonFieldsSeparator + lineBreak); } else { compoundTextOldBuffer.append(lineBreak); } } firstLongField = false; String fieldLabel = fieldChange.getLocalizedFieldLabel(); String newShowValue = fieldChange.getNewShowValue(); if (newShowValue != null && !"".equals(newShowValue)) { compoundTextNewBuffer.append(fieldLabel + fieldLabelSeparator + newShowValue); } String oldShowValue = fieldChange.getOldShowValue(); if (oldShowValue != null && !"".equals(oldShowValue)) { compoundTextOldBuffer.append(fieldLabel + fieldLabelSeparator + oldShowValue); } } } saveCompoundField(historyTransactionID, workItemBeanNew.getObjectID(), personID, compoundTextNewBuffer.toString(), compoundTextOldBuffer.toString()); return mightTriggerEmail; }
From source file:alfio.manager.NotificationManager.java
private void processMessage(int messageId) { EmailMessage message = emailMessageRepository.findById(messageId); int eventId = message.getEventId(); int organizationId = eventRepository.findOrganizationIdByEventId(eventId); if (message.getAttempts() >= configurationManager.getIntConfigValue( Configuration.from(organizationId, eventId, ConfigurationKeys.MAIL_ATTEMPTS_COUNT), 10)) { tx.execute(status -> emailMessageRepository.updateStatusAndAttempts(messageId, ERROR.name(), message.getAttempts(), Arrays.asList(IN_PROCESS.name(), WAITING.name(), RETRY.name()))); log.warn("Message with id " + messageId + " will be discarded"); return;//from w w w. ja va 2 s. c om } try { int result = tx.execute(status -> emailMessageRepository.updateStatus(message.getEventId(), message.getChecksum(), IN_PROCESS.name(), Arrays.asList(WAITING.name(), RETRY.name()))); if (result > 0) { tx.execute(status -> { sendMessage(message); return null; }); } else { log.debug( "no messages have been updated on DB for the following criteria: eventId: {}, checksum: {}", message.getEventId(), message.getChecksum()); } } catch (Exception e) { tx.execute(status -> emailMessageRepository.updateStatusAndAttempts(message.getId(), RETRY.name(), DateUtils.addMinutes(new Date(), message.getAttempts() + 1), message.getAttempts() + 1, Arrays.asList(IN_PROCESS.name(), WAITING.name(), RETRY.name()))); log.warn("could not send message: ", e); } }
From source file:com.formkiq.core.service.UserServiceImpl.java
@Override public void updatePassword(final String email, final String resettoken, final String newPassword) { boolean updated = false; if (!StringUtils.isEmpty(resettoken)) { User user = this.userDao.findUser(email); if (user != null) { if (isMatch(resettoken, user.getResetToken())) { Date now = this.dateservice.now(); Date date = DateUtils.addMinutes(now, -getUserTokenExpiryInMinutes()); if (user.getResetInsertedDate().after(date)) { user.setResetInsertedDate(null); user.setResetToken(null); updated = true;/*from ww w . j av a 2s. c om*/ } } else { updated = isMatch(resettoken, user.getPassword()); } if (updated) { if (UserStatus.INVITE.equals(user.getStatus())) { user.setStatus(UserStatus.ACTIVE); } setUserPassword(user, newPassword); this.userDao.saveUser(user); } } } if (!updated) { throw new PreconditionFailedException("Invalid Old Password or Reset Token"); } }