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 testAddRuleExclusionThrowsIfExclusionOccursInThePast() throws Exception {
    // Exclusions must be for future dates (not just after their rule begins).
    // To test this we need to try adding an exclusion in the past, but after
    // the rule begins.

    // ARRANGE//  ww  w .  j  a  va  2s .  com
    thrown.expect(Exception.class);
    thrown.expectMessage("Booking rule exclusion addition failed");

    initialiseRuleManager();
    expectOptimisticPersisterToReturnVersionedAttributes(2); // 2 arbitrary

    // Set current date to a fortnight after the rule begins
    String startSaturday = existingSaturdayRecurringRuleWithExclusion.getBooking().getDate();
    String fortnightAfterStart = LocalDate.parse(startSaturday, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            .plusWeeks(2).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    ruleManager.setCurrentLocalDate(
            LocalDate.parse(fortnightAfterStart, DateTimeFormatter.ofPattern("yyyy-MM-dd")));

    // Choose exclusion date before the fake current date, but after the start
    // date.
    String weekAfterStart = LocalDate.parse(startSaturday, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            .plusWeeks(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    // ACT
    // N.B. The third parameter is arbitrary here.
    ruleManager.addRuleExclusion(weekAfterStart, existingSaturdayRecurringRuleWithExclusion, true);
}

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

@Test
public void testAddRuleExclusionThrowsIfMaximumNumberOfExclusionsExists() throws Exception {
    // There is a certain maximum number of exclusions that can be present on
    // each rule. Trying to add another should throw.

    // ARRANGE//from w  ww.j ava2  s. c om
    thrown.expect(Exception.class);
    thrown.expectMessage("Booking rule exclusion addition failed");

    initialiseRuleManager();
    expectOptimisticPersisterToReturnVersionedAttributes(2); // 2 arbitrary

    // Set maximum exclusion number equal to that already present
    ruleManager.setMaxNumberOfDatesToExclude(1);
    // Create an arbitrary-but-otherwise-valid exclusion date to add
    String saturdayExclusionDate = LocalDate
            .parse(existingSaturdayRecurringRuleWithExclusion.getBooking().getDate(),
                    DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            .plusWeeks(12).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    // ACT
    // This should throw as adding it would exceed the maximum number
    // N.B. The third parameter is arbitrary here.
    ruleManager.addRuleExclusion(saturdayExclusionDate, existingSaturdayRecurringRuleWithExclusion, true);
}

From source file:ffx.potential.ForceFieldEnergy.java

/**
 * {@inheritDoc}/*ww  w . j a  va  2  s . com*/
 */
@Override
public double energyAndGradient(double x[], double g[], boolean verbose) {
    /**
     * Un-scale the coordinates.
     */
    if (optimizationScaling != null) {
        int len = x.length;
        for (int i = 0; i < len; i++) {
            x[i] /= optimizationScaling[i];
        }
    }
    setCoordinates(x);
    double e = energy(true, verbose);

    // Try block already exists inside energy(boolean, boolean), so only
    // need to try-catch getGradients.
    try {
        getGradients(g);
        /**
         * Scale the coordinates and gradients.
         */
        if (optimizationScaling != null) {
            int len = x.length;
            for (int i = 0; i < len; i++) {
                x[i] *= optimizationScaling[i];
                g[i] /= optimizationScaling[i];
            }
        }
        return e;
    } catch (EnergyException ex) {
        ex.printStackTrace();
        if (printOnFailure) {
            String timeString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd-HH_mm_ss"));

            String filename = String.format("%s-ERROR-%s.pdb",
                    FilenameUtils.removeExtension(molecularAssembly.getFile().getName()), timeString);

            PotentialsFunctions ef = new PotentialsUtils();
            filename = ef.versionFile(filename);
            logger.info(String.format(" Writing on-error snapshot to file %s", filename));
            ef.saveAsPDB(molecularAssembly, new File(filename));
        }
        if (ex.doCauseSevere()) {
            ex.printStackTrace();
            logger.log(Level.SEVERE, " Error in calculating energies or gradients", ex);
        } else {
            ex.printStackTrace();
            throw ex; // Rethrow exception
        }

        return 0; // Should ordinarily be unreachable.
    }
}

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

@Test
public void testApplyRulesCallsBookingManagerCorrectly_NonRecurringRuleDoesNotRecur() throws Exception {
    // A nonrecurring rule should apply for its date only and should not recur
    // in later weeks.

    // ARRANGE//from  w ww  . java  2  s. co  m
    initialiseRuleManager();
    expectOptimisticPersisterToReturnVersionedAttributes(42);
    expectPurgeExpiredRulesAndRuleExclusions(42, existingBookingRules);
    // Set apply date to one week after the non-recurring rule - it should be
    // ignored.
    String existingDate = existingThursdayNonRecurringRule.getBooking().getDate();
    String applyDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusWeeks(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    // ACT
    // This should not create a booking
    ruleManager.applyRules(applyDate, false);
}

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

@Test
public void testApplyRulesCallsBookingManagerCorrectly_ApplicableRecurringRuleNoExclusionRecurrentBooking()
        throws Exception {
    // A recurring rule with no exclusion for the apply date should cause a
    // booking to be made. This tests for an apply date corresponding to a later
    // recurrence of the recurrent rule rather than the rule's initial booking.

    // ARRANGE/*  w  ww . j av a  2 s.co  m*/
    initialiseRuleManager();
    expectOptimisticPersisterToReturnVersionedAttributes(42);

    // Set up booking for a recurrence of the rule's initial booking
    String initialDate = existingFridayRecurringRuleWithoutExclusions.getBooking().getDate();
    String newBookingDate = LocalDate.parse(initialDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            .plusWeeks(10).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    Booking bookingToCreate = new Booking(existingFridayRecurringRuleWithoutExclusions.getBooking());
    bookingToCreate.setDate(newBookingDate);
    expectBookingManagerCall(bookingToCreate);
    expectPurgeExpiredRulesAndRuleExclusions(42, existingBookingRules);

    // ACT
    // This should create a booking
    ruleManager.applyRules(newBookingDate, false);
}

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

@Test
public void testApplyRulesCallsBookingManagerCorrectly_FutureRecurringRuleNoExclusion() throws Exception {
    // A recurring rule with no exclusion for the apply date, but that does not
    // begin until after the apply date should not cause a booking to be made.

    // ARRANGE//from w w  w .j  a  v a2 s . com
    initialiseRuleManager();
    expectOptimisticPersisterToReturnVersionedAttributes(42);
    expectPurgeExpiredRulesAndRuleExclusions(42, existingBookingRules);
    mockery.checking(new Expectations() {
        {
            never(mockBookingManager).createBooking(with(anything()), with.booleanIs(anything()));
        }
    });

    // Get date before start date of rule
    String initialDate = existingFridayRecurringRuleWithoutExclusions.getBooking().getDate();
    String earlierDate = LocalDate.parse(initialDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusWeeks(2)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    // ACT
    // This should not create a booking
    ruleManager.applyRules(earlierDate, false);
}

From source file:org.kitodo.production.services.data.ProcessService.java

/**
 * Calculate and return duration/age of given process as a String.
 *
 * @param process ProcessDTO object for which duration/age is calculated
 * @return process age of given process/*from  w ww  .  j  a v  a 2 s .c  o m*/
 */
public static String getProcessDuration(ProcessDTO process) {
    String creationDateTimeString = process.getCreationDate();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime createLocalDate = LocalDateTime.parse(creationDateTimeString, formatter);
    Duration duration = Duration.between(createLocalDate, LocalDateTime.now());
    return String.format("%sd; %sh", duration.toDays(),
            duration.toHours() - TimeUnit.DAYS.toHours(duration.toDays()));
}

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

@Test
public void testApplyRulesCallsBookingManagerCorrectly_NoRelevantRules() throws Exception {
    // An apply date with no relevant rules should not cause a booking to be
    // made, but should still purge expired rules and exclusions.

    // ARRANGE//from  w  w w . j  a  v  a2  s  .com
    initialiseRuleManager();
    expectOptimisticPersisterToReturnVersionedAttributes(42);
    expectPurgeExpiredRulesAndRuleExclusions(42, existingBookingRules);
    mockery.checking(new Expectations() {
        {
            never(mockBookingManager).createBooking(with(anything()), with.booleanIs(anything()));
        }
    });

    // Get date for day of week different to any rule's
    String friday = existingFridayRecurringRuleWithoutExclusions.getBooking().getDate();
    String monday = LocalDate.parse(friday, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(3)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    // ACT
    // This should not create a booking - none of our rules are for mondays
    ruleManager.applyRules(monday, false);
}

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

@Test
public void testApplyRulesToleratesApplyDateInThePast() throws Exception {
    // An apply date in the past should not cause a booking to be made, but
    // should still purge expired rules and exclusions.

    // ARRANGE/*from w w w .  j  av a2  s .  com*/
    initialiseRuleManager();
    expectPurgeExpiredRulesAndRuleExclusions(42, existingBookingRules);
    mockery.checking(new Expectations() {
        {
            never(mockBookingManager).createBooking(with(anything()), with.booleanIs(anything()));
        }
    });

    // Get date before our current date
    String pastDate = LocalDate.parse(fakeCurrentSaturdayDateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            .minusWeeks(33).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    // ACT
    // This should be tolerated even though the date is in the past
    ruleManager.applyRules(pastDate, false);
}

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

@Test
public void testApplyRulesCallsBookingManagerCorrectly_PurgeExpiredNonRecurringRule() throws Exception {
    // applyRules should delete non-recurring rules for dates before the current
    // date.//from   ww  w . j  a  v a 2  s  .co m

    // ARRANGE
    initialiseRuleManager();

    // Set the current date to a date after an existing non-recurring rule, but
    // also for a day-of-the-week when no other rules apply (just to avoid extra
    // createBooking noise):
    String thursday = existingThursdayNonRecurringRule.getBooking().getDate();
    String dayAfterThursday = LocalDate.parse(thursday, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(4)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    ruleManager
            .setCurrentLocalDate(LocalDate.parse(dayAfterThursday, DateTimeFormatter.ofPattern("yyyy-MM-dd")));

    expectOptimisticPersisterToReturnVersionedAttributes(42);
    expectPurgeExpiredRulesAndRuleExclusions(42, existingBookingRules,
            Optional.of(existingThursdayNonRecurringRule), Optional.empty());

    // ACT
    // This should delete the (expired) Thursday rule
    ruleManager.applyRules(dayAfterThursday, false);
}