Example usage for java.time.format DateTimeFormatter ofPattern

List of usage examples for java.time.format DateTimeFormatter ofPattern

Introduction

In this page you can find the example usage for java.time.format DateTimeFormatter ofPattern.

Prototype

public static DateTimeFormatter ofPattern(String pattern) 

Source Link

Document

Creates a formatter using the specified pattern.

Usage

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleDoesNotThrowWhenNewRuleDoesNotClashWithExistingRules_ExistingNonRecurringInPastNewRecurringSameDayOfWeekOverlappingNoExclusion()
        throws Exception {
    // This checks that a new recurring rule does not clash with an existing
    // non-recurring one if that existing rule has a date before the new
    // recurring rule starts.

    // ARRANGE//  w  w w .  ja v  a2  s.  c  om
    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingThursdayRule = new BookingRule(existingThursdayNonRecurringRule);
    nonClashingThursdayRule.setIsRecurring(true);

    // Tweak date to be ahead of the existing non-recurring rule
    String existingDate = nonClashingThursdayRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusWeeks(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingThursdayRule.getBooking().setDate(newDate);

    // ACT
    doTestCreateRuleClashesOrNotWithExistingRule(nonClashingThursdayRule, false);
}

From source file:squash.booking.lambdas.core.RuleManager.java

private void purgeExpiredRulesAndRuleExclusions() throws Exception {
    ImmutablePair<Optional<Integer>, Set<BookingRule>> versionedBookingRules = getVersionedBookingRules();
    Set<BookingRule> existingBookingRules = versionedBookingRules.right;

    Optional<Integer> versionNumber = versionedBookingRules.left;
    String todayFormatted = getCurrentLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    Date today = (new SimpleDateFormat("yyyy-MM-dd").parse(todayFormatted));
    logger.log("Purging all rules and exclusions that expired before: " + todayFormatted);
    for (BookingRule bookingRule : existingBookingRules) {
        if (!bookingRule.getIsRecurring()
                && (new SimpleDateFormat("yyyy-MM-dd").parse(bookingRule.getBooking().getDate()))
                        .before(today)) {
            logger.log("Deleting non-recurring booking rule as it has expired: " + bookingRule.toString());
            try {
                deleteRule(bookingRule, false);
                logger.log("Deleted expired booking rule");
            } catch (Exception exception) {
                // Don't want to abort here if we fail to remove a rule - after all
                // we'll get another shot at it in 24 hours time.
                logger.log("Exception caught deleting expired booking rule - swallowing and carrying on...");
            }//from   www  .  j  av  a  2s.co  m
            continue;
        }

        // Purge any expired exclusions from this rule
        if (!bookingRule.getIsRecurring()) {
            // Non-recurring rules have no exclusions
            continue;
        }
        logger.log("Purging any expired exclusions from recurring rule: " + bookingRule);
        Set<String> datesToExclude = Sets.newHashSet(bookingRule.getDatesToExclude());
        Set<String> newDatesToExclude = new HashSet<>();
        for (String date : datesToExclude) {
            if ((new SimpleDateFormat("yyyy-MM-dd").parse(date)).after(new SimpleDateFormat("yyyy-MM-dd").parse(
                    getCurrentLocalDate().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))))) {
                // Keep the exclusion if it applies to a date after yesterday.
                newDatesToExclude.add(date);
            } else {
                logger.log("Expiring exclusion for: " + date);
            }
            if (datesToExclude.size() > newDatesToExclude.size()) {
                // Update the database as some exclusions have been purged
                logger.log("Proceeding to update the rule after purging expired exclusion(s)");
                String attributeName = getAttributeNameFromBookingRule(bookingRule);
                String attributeValue = StringUtils.join(newDatesToExclude, ",");
                logger.log("ItemName: " + ruleItemName);
                logger.log("AttributeName: " + attributeName);
                logger.log("AttributeValue: " + attributeValue);
                ReplaceableAttribute bookingRuleAttribute = new ReplaceableAttribute();
                bookingRuleAttribute.setName(attributeName);
                bookingRuleAttribute.setValue(attributeValue);
                bookingRuleAttribute.setReplace(true);
                try {
                    versionNumber = Optional
                            .of(optimisticPersister.put(ruleItemName, versionNumber, bookingRuleAttribute));
                    logger.log("Updated rule to purge expired exclusion(s)");
                } catch (Exception exception) {
                    // Don't want to abort here if we fail to remove an exclusion -
                    // after all we'll get another shot at it in 24 hours time.
                    logger.log(
                            "Exception caught deleting expired booking exclusion - swallowing and carrying on...");
                }
            }
        }
    }
    logger.log("Purged all expired rules and exclusions");
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleDoesNotThrowWhenNewRuleDoesNotClashWithExistingRules_ExistingNonRecurringNewRecurringDifferentDayOfWeekOverlapping()
        throws Exception {
    // Tests case where we would have a clash if the days-of-the-week agreed -
    // but they don't, so should not clash.

    // ARRANGE/*  w ww .j  a v  a 2s  .c o m*/
    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingWednesdayRule = new BookingRule(existingThursdayNonRecurringRule);
    nonClashingWednesdayRule.setIsRecurring(true);

    // Move date to a different day of the week
    String existingDate = nonClashingWednesdayRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(6)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingWednesdayRule.getBooking().setDate(newDate); // Wednesday

    // ACT
    doTestCreateRuleClashesOrNotWithExistingRule(nonClashingWednesdayRule, false);
}

From source file:com.thinkbiganalytics.integration.IntegrationTestBase.java

private ServiceLevelAgreementGroup createFeedProcessingDeadlineSla(String feedName, String feedId,
        LocalDateTime deadline, String noLaterThanHours) {
    int hourOfDay = deadline.get(ChronoField.HOUR_OF_DAY);
    int minuteOfHour = deadline.get(ChronoField.MINUTE_OF_HOUR);
    String cronExpression = String.format("0 %s %s 1/1 * ? *", minuteOfHour, hourOfDay);

    ServiceLevelAgreementGroup sla = new ServiceLevelAgreementGroup();
    String time = deadline.format(DateTimeFormatter.ofPattern("HH:mm"));
    sla.setName("Before " + time + " (cron: " + cronExpression + ")");
    sla.setDescription("The feed should complete before given date and time");
    List<ServiceLevelAgreementRule> rules = new ArrayList<>();
    ServiceLevelAgreementRule rule = new ServiceLevelAgreementRule();
    rule.setName("Feed Processing deadline");
    rule.setDisplayName("Feed Processing deadline");
    rule.setDescription("Ensure a Feed processes data by a specified time");
    rule.setObjectClassType("com.thinkbiganalytics.metadata.sla.api.core.FeedOnTimeArrivalMetric");
    rule.setObjectShortClassType("FeedOnTimeArrivalMetric");
    rule.setCondition(ObligationGroup.Condition.REQUIRED);

    rule.setProperties(newFieldRuleProperties(newFieldRuleProperty("FeedName", "feedName", feedName),
            newFieldRuleProperty("ExpectedDeliveryTime", "cronString", cronExpression),
            newFieldRuleProperty("NoLaterThanTime", "lateTime", noLaterThanHours),
            newFieldRuleProperty("NoLaterThanUnits", "lateUnits", "hrs")));

    rules.add(rule);//ww  w .  j a  va 2  s .c  o m
    sla.setRules(rules);

    Response response = given(ServiceLevelAgreementRestController.V1_FEEDMGR_SLA).body(sla).when()
            .post(String.format("feed/%s", feedId));

    response.then().statusCode(HTTP_OK);

    return response.as(ServiceLevelAgreementGroup.class);
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleThrowsWhenNewRuleClashesWithExistingRules_ExistingRecurringNewRecurringSameDayOfWeekOverlapping()
        throws Exception {
    // Always clash if both new and existing rules are recurring and
    // overlapping.

    // ARRANGE//from   w  ww  .ja  va2 s. c o  m
    thrown.expect(Exception.class);
    thrown.expectMessage("Booking rule creation failed");

    // Set up a rule to create that clashes in required way with existing rules
    BookingRule clashingFridayRule = new BookingRule(existingFridayRecurringRuleWithoutExclusions);
    // Move date to same day-of-week but to some date later than the existing
    // non-recurring rule - should make no difference.
    String existingDate = clashingFridayRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusWeeks(100)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    clashingFridayRule.getBooking().setDate(newDate);

    // ACT
    doTestCreateRuleClashesOrNotWithExistingRule(clashingFridayRule, true);
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleDoesNotThrowWhenNewRuleDoesNotClashWithExistingRules_ExistingRecurringNewNonRecurringSameDayOfWeekOverlappingExclusions()
        throws Exception {
    // If existing rule is recurring and new rule is non-recurring for
    // overlapping court/time and same day-of-the-week for a date in the future
    // and there is a relevant exclusion, then we do not have a clash. This
    // checks that when the relevant exclusion is not the first exclusion in the
    // exclusions array, it is still respected.

    // ARRANGE/*from   w ww.java 2 s . c o  m*/
    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingSaturdayRule = new BookingRule(existingSaturdayRecurringRuleWithExclusion);
    nonClashingSaturdayRule.setIsRecurring(false);
    nonClashingSaturdayRule.setDatesToExclude(new String[0]);

    // Move date to equal the second exclusion on the existing recurring rule
    // Add second exclusion:
    String existingExclusion = existingSaturdayRecurringRuleWithExclusion.getDatesToExclude()[0];
    String newExclusion = LocalDate.parse(existingExclusion, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            .plusWeeks(12).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    String[] newExcludeDates = new String[] { existingSaturdayRecurringRuleWithExclusion.getDatesToExclude()[0],
            newExclusion };
    existingSaturdayRecurringRuleWithExclusion.setDatesToExclude(newExcludeDates);

    nonClashingSaturdayRule.getBooking().setDate(newExcludeDates[1]);

    // ACT
    doTestCreateRuleClashesOrNotWithExistingRule(nonClashingSaturdayRule, false);
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleThrowsWhenNewRuleClashesWithExistingRules_ExistingRecurringNewNonRecurringSameDayOfWeekOverlappingNoExclusion()
        throws Exception {
    // If existing rule is recurring and new rule is non-recurring for
    // overlapping court/time and same day-of-the-week for a date in the future
    // and there is no relevant exclusion - we have a clash.

    // ARRANGE/*ww w .  j av  a 2s.  c om*/
    thrown.expect(Exception.class);
    thrown.expectMessage("Booking rule creation failed");

    // Set up a rule to create that clashes in required way with existing rules
    BookingRule clashingFridayRule = new BookingRule(existingFridayRecurringRuleWithoutExclusions);
    clashingFridayRule.setIsRecurring(false);
    // Move date to same day-of-week but to some future date
    String existingDate = clashingFridayRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusWeeks(12)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    clashingFridayRule.getBooking().setDate(newDate);

    // ACT
    doTestCreateRuleClashesOrNotWithExistingRule(clashingFridayRule, true);
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleDoesNotThrowWhenNewRuleDoesNotClashWithExistingRules_ExistingRecurringNewNonRecurringBeforeStartSameDayOfWeekOverlappingNoExclusion()
        throws Exception {
    // If existing rule is recurring and new rule is non-recurring for
    // overlapping court/time and same day-of-the-week, but for a date both not
    // in the past and before the recurring rule starts, we do not have a clash.

    // ARRANGE/*from  ww  w.j a v a  2s  .c  om*/

    // Set up a rule to create that avoids clash in required way with existing
    // rules
    BookingRule nonClashingFridayRule = new BookingRule(existingFridayRecurringRuleWithoutExclusions);
    nonClashingFridayRule.setIsRecurring(false);
    // Move date to one week earlier i.e. to before recurring rule starts
    String existingDate = nonClashingFridayRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusWeeks(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingFridayRule.getBooking().setDate(newDate);

    // ACT
    doTestCreateRuleClashesOrNotWithExistingRule(nonClashingFridayRule, false);
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleThrowsWhenNewNonRecurringRuleIsInThePast() throws Exception {

    // ARRANGE//from  w  ww . ja va2 s . c  o m
    thrown.expect(Exception.class);
    thrown.expectMessage("Booking rule creation failed");

    // Set up a rule to create that clashes in required way with existing rules
    BookingRule pastRule = new BookingRule(existingThursdayNonRecurringRule);
    // Tweak so does not clash
    pastRule.getBooking().setCourt(pastRule.getBooking().getCourt() + pastRule.getBooking().getCourtSpan());
    pastRule.getBooking().setSlot(pastRule.getBooking().getSlot() + pastRule.getBooking().getSlotSpan());

    // Set current date to be ahead of this new rule
    ruleManager.setCurrentLocalDate(LocalDate
            .parse(pastRule.getBooking().getDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(1));

    // ACT
    doTestCreateRuleClashesOrNotWithExistingRule(pastRule, true);
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
* Mthode ralisant l'export des FEC (Fichiers des critures Comptables)
* @throws AxelorException/*from  ww w. j  a  v a 2s .  c o  m*/
* @throws IOException
*/
@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public void exportMoveLineTypeSelect1000(MoveLineReport moveLineReport) throws AxelorException, IOException {

    log.info("In Export type 1000 service : ");
    List<String[]> allMoveLineData = new ArrayList<String[]>();
    Company company = moveLineReport.getCompany();

    String moveLineQueryStr = "";
    moveLineQueryStr += String.format(" AND self.move.company = %s", company.getId());
    moveLineQueryStr += String.format(" AND self.move.period.year = %s", moveLineReport.getYear().getId());

    if (moveLineReport.getPeriod() != null) {
        moveLineQueryStr += String.format(" AND self.move.period = %s", moveLineReport.getPeriod().getId());
    } else {
        if (moveLineReport.getDateFrom() != null) {
            moveLineQueryStr += String.format(" AND self.date >= '%s'",
                    moveLineReport.getDateFrom().toString());
        }
        if (moveLineReport.getDateTo() != null) {
            moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
        }
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }

    moveLineQueryStr += String
            .format("AND self.move.accountingOk = false AND self.move.ignoreInAccountingOk = false");

    List<MoveLine> moveLineList = moveLineRepo.all()
            .filter("self.move.statusSelect = ?1" + moveLineQueryStr, MoveRepository.STATUS_VALIDATED)
            .order("date").order("name").fetch();
    if (moveLineList.size() > 0) {

        for (MoveLine moveLine : moveLineList) {
            String items[] = new String[18];
            Move move = moveLine.getMove();
            Journal journal = move.getJournal();
            items[0] = journal.getCode();
            items[1] = journal.getName();
            items[2] = moveLine.getName();
            items[3] = moveLine.getDate().format(DateTimeFormatter.BASIC_ISO_DATE);
            items[4] = moveLine.getAccount().getCode();
            items[5] = moveLine.getAccount().getName();
            items[6] = null; //Le numro de compte auxiliaire ( blanc pour le moment) 
            items[7] = null; //Le libell de compte auxiliaire ( blanc pour le moment) 
            items[8] = moveLine.getOrigin();
            items[9] = moveLine.getDate().format(DateTimeFormatter.BASIC_ISO_DATE); // Pour le moment on va utiliser la date des lignes d'criture. 
            items[10] = moveLine.getDescription();
            items[11] = moveLine.getDebit().toString();
            items[12] = moveLine.getCredit().toString();
            if (moveLine.getDebit().compareTo(BigDecimal.ZERO) > 0) {
                List<String> ReconcileSeqList = new ArrayList<String>();
                List<String> ReconcileDateList = new ArrayList<String>();

                for (Reconcile reconcile : moveLine.getDebitReconcileList()) {
                    ReconcileSeqList.add(reconcile.getReconcileSeq());
                    ReconcileDateList.add(
                            reconcile.getReconciliationDate().format(DateTimeFormatter.ofPattern("YYYYMMdd")));
                }
                items[13] = StringUtils.join(ReconcileSeqList, "; ");
                items[14] = StringUtils.join(ReconcileDateList, "; ");
            } else {
                List<String> ReconcileSeqList = new ArrayList<String>();
                List<String> ReconcileDateList = new ArrayList<String>();
                for (Reconcile reconcile : moveLine.getCreditReconcileList()) {
                    ReconcileSeqList.add(reconcile.getReconcileSeq());
                    ReconcileDateList
                            .add(reconcile.getReconciliationDate().format(DateTimeFormatter.BASIC_ISO_DATE));
                }
                items[13] = StringUtils.join(ReconcileSeqList, "; ");
                items[14] = StringUtils.join(ReconcileDateList, "; ");
            }
            items[15] = move.getValidationDate().format(DateTimeFormatter.BASIC_ISO_DATE);
            items[16] = moveLine.getCurrencyAmount().toString();
            if (move.getCurrency() != null) {
                items[17] = move.getCurrency().getCode();
            }
            allMoveLineData.add(items);
        }
    }

    String fileName = this.setFileName(moveLineReport);
    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    //TODO create a template Helper

    new File(filePath).mkdirs();
    log.debug("Full path to export : {}{}", filePath, fileName);
    //      CsvTool.csvWriter(filePath, fileName, '|', null, allMoveLineData);
    CsvTool.csvWriter(filePath, fileName, '|', this.createHeaderForHeaderFile(moveLineReport.getTypeSelect()),
            allMoveLineData);
    moveLineReportRepo.save(moveLineReport);

    Path path = Paths.get(filePath + fileName);

    try (InputStream is = new FileInputStream(path.toFile())) {
        Beans.get(MetaFiles.class).attach(is, fileName, moveLineReport);
    }

}