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:ffx.potential.ForceFieldEnergy.java

/**
 * <p>//from ww w . j  av a2  s  .  co m
 * energy</p>
 *
 * @param gradient a boolean.
 * @param print a boolean.
 * @return a double.
 */
public double energy(boolean gradient, boolean print) {
    try {
        bondTime = 0;
        angleTime = 0;
        stretchBendTime = 0;
        ureyBradleyTime = 0;
        outOfPlaneBendTime = 0;
        torsionTime = 0;
        piOrbitalTorsionTime = 0;
        torsionTorsionTime = 0;
        improperTorsionTime = 0;
        vanDerWaalsTime = 0;
        electrostaticTime = 0;
        restraintBondTime = 0;
        ncsTime = 0;
        coordRestraintTime = 0;
        totalTime = System.nanoTime();

        // Zero out the potential energy of each bonded term.
        bondEnergy = 0.0;
        angleEnergy = 0.0;
        stretchBendEnergy = 0.0;
        ureyBradleyEnergy = 0.0;
        outOfPlaneBendEnergy = 0.0;
        torsionEnergy = 0.0;
        piOrbitalTorsionEnergy = 0.0;
        torsionTorsionEnergy = 0.0;
        improperTorsionEnergy = 0.0;
        totalBondedEnergy = 0.0;

        // Zero out potential energy of restraint terms
        restraintBondEnergy = 0.0;
        ncsEnergy = 0.0;
        restrainEnergy = 0.0;

        // Zero out bond and angle RMSDs.
        bondRMSD = 0.0;
        angleRMSD = 0.0;

        // Zero out the potential energy of each non-bonded term.
        vanDerWaalsEnergy = 0.0;
        permanentMultipoleEnergy = 0.0;
        polarizationEnergy = 0.0;
        totalElectrostaticEnergy = 0.0;
        totalNonBondedEnergy = 0.0;

        // Zero out the solvation energy.
        solvationEnergy = 0.0;

        // Zero out the relative solvation energy (sequence optimization)
        relativeSolvationEnergy = 0.0;
        nRelativeSolvations = 0;

        esvBias = 0.0;

        // Zero out the total potential energy.
        totalEnergy = 0.0;

        // Zero out the Cartesian coordinate gradient for each atom.
        if (gradient) {
            for (int i = 0; i < nAtoms; i++) {
                atoms[i].setXYZGradient(0.0, 0.0, 0.0);
                atoms[i].setLambdaXYZGradient(0.0, 0.0, 0.0);
            }
        }

        /**
         * Computed the bonded energy terms in parallel.
         */
        try {
            bondedRegion.setGradient(gradient);
            parallelTeam.execute(bondedRegion);
        } catch (Exception e) {
            e.printStackTrace();
            logger.severe(e.toString());
        }

        if (!lambdaBondedTerms) {
            /**
             * Compute restraint terms.
             */
            if (ncsTerm) {
                ncsTime = -System.nanoTime();
                ncsEnergy = ncsRestraint.residual(gradient, print);
                ncsTime += System.nanoTime();
            }
            if (restrainTerm && !coordRestraints.isEmpty()) {
                coordRestraintTime = -System.nanoTime();
                for (CoordRestraint restraint : coordRestraints) {
                    restrainEnergy += restraint.residual(gradient, print);
                }
                coordRestraintTime += System.nanoTime();
            }
            if (comTerm) {
                comRestraintTime = -System.nanoTime();
                comRestraintEnergy = comRestraint.residual(gradient, print);
                comRestraintTime += System.nanoTime();
            }
            /**
             * Compute non-bonded terms.
             */
            if (vanderWaalsTerm) {
                vanDerWaalsTime = -System.nanoTime();
                vanDerWaalsEnergy = vanderWaals.energy(gradient, print);
                nVanDerWaalInteractions = this.vanderWaals.getInteractions();
                vanDerWaalsTime += System.nanoTime();
            }
            if (multipoleTerm) {
                electrostaticTime = -System.nanoTime();
                totalElectrostaticEnergy = particleMeshEwald.energy(gradient, print);
                permanentMultipoleEnergy = particleMeshEwald.getPermanentEnergy();
                polarizationEnergy = particleMeshEwald.getPolarizationEnergy();
                nPermanentInteractions = particleMeshEwald.getInteractions();
                solvationEnergy = particleMeshEwald.getGKEnergy();
                nGKInteractions = particleMeshEwald.getGKInteractions();
                electrostaticTime += System.nanoTime();
            }
        }

        if (relativeSolvationTerm) {
            List<Residue> residuesList = molecularAssembly.getResidueList();
            for (Residue residue : residuesList) {
                if (residue instanceof MultiResidue) {
                    Atom refAtom = residue.getSideChainAtoms().get(0);
                    if (refAtom != null && refAtom.getUse()) {
                        /**
                         * Reasonably confident that it should be -=, as we
                         * are trying to penalize residues with strong
                         * solvation energy.
                         */
                        double thisSolvation = relativeSolvation.getSolvationEnergy(residue, false);
                        relativeSolvationEnergy -= thisSolvation;
                        if (thisSolvation != 0) {
                            nRelativeSolvations++;
                        }
                    }
                }
            }
        }

        totalTime = System.nanoTime() - totalTime;

        totalBondedEnergy = bondEnergy + restraintBondEnergy + angleEnergy + stretchBendEnergy
                + ureyBradleyEnergy + outOfPlaneBendEnergy + torsionEnergy + piOrbitalTorsionEnergy
                + improperTorsionEnergy + torsionTorsionEnergy + ncsEnergy + restrainEnergy;
        totalNonBondedEnergy = vanDerWaalsEnergy + totalElectrostaticEnergy + relativeSolvationEnergy;
        totalEnergy = totalBondedEnergy + totalNonBondedEnergy + solvationEnergy;
        if (esvTerm) {
            esvBias = esvSystem.getBiasEnergy(null);
            totalEnergy += esvBias;
        }
    } catch (EnergyException ex) {
        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()) {
            logger.log(Level.SEVERE, " Error in calculating energies or gradients", ex);
            return 0.0;
        } else {
            throw ex; // Rethrow exception
        }
    }

    if (print || printOverride) {
        if (printCompact) {
            logger.info(this.toString());
        } else {
            StringBuilder sb = new StringBuilder();
            if (gradient) {
                sb.append("\n Computed Potential Energy and Atomic Coordinate Gradients\n");
            } else {
                sb.append("\n Computed Potential Energy\n");
            }
            sb.append(this);
            logger.info(sb.toString());
        }
    }
    return totalEnergy;
}

From source file:org.cgiar.ccafs.marlo.action.summaries.ExpectedDeliverablesSummaryAction.java

private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    TypedTableModel model = new TypedTableModel(
            new String[] { "center", "date", "year", "regionalAvalaible", "showDescription", "cycle" },
            new Class[] { String.class, String.class, String.class, Boolean.class, Boolean.class,
                    String.class });
    String center = this.getLoggedCrp().getAcronym();

    ZonedDateTime timezone = ZonedDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    String zone = timezone.getOffset() + "";
    if (zone.equals("Z")) {
        zone = "+0";
    }//from   w  w w  .  ja  v a2s  .  co m
    String date = timezone.format(format) + "(GMT" + zone + ")";
    String year = this.getSelectedYear() + "";
    model.addRow(new Object[] { center, date, year, this.hasProgramnsRegions(),
            this.hasSpecificities(APConstants.CRP_REPORTS_DESCRIPTION), this.getSelectedCycle() });
    return model;
}

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

@Test
public void testAddRuleExclusionHappyPathCallsTheOptimisticPersisterCorrectly() throws Exception {
    // Happy path where addRuleExclusion goes right through and creates the
    // exclusion.

    // ARRANGE//w w w.j  ava 2 s .  c om
    initialiseRuleManager();
    int versionToUse = 22; // Arbitrary
    expectOptimisticPersisterToReturnVersionedAttributes(versionToUse);

    // Create an arbitrary, 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"));
    expectToAddOrDeleteRuleExclusionViaOptimisticPersister(versionToUse, saturdayExclusionDate, true,
            existingSaturdayRecurringRuleWithExclusion);

    // ACT
    // N.B. The third parameter is arbitrary here.
    Optional<BookingRule> updatedRule = ruleManager.addRuleExclusion(saturdayExclusionDate,
            existingSaturdayRecurringRuleWithExclusion, true);

    // ASSERT
    String[] newExcludeDates = new String[] { existingSaturdayRecurringRuleWithExclusion.getDatesToExclude()[0],
            saturdayExclusionDate };
    existingSaturdayRecurringRuleWithExclusion.setDatesToExclude(newExcludeDates);
    assertTrue("The updated rule should be returned", updatedRule.isPresent());
    assertTrue("The updated rule should be correct",
            updatedRule.get().equals(existingSaturdayRecurringRuleWithExclusion));
}

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

@Test
public void testAddRuleExclusionThrowsWhenTheOptimisticPersisterThrows() throws Exception {
    // N.B. This applies except when the optimistic persister throws a
    // conditional check failed exclusion, which is covered by other tests.

    // ARRANGE/*from   w w  w  .  j a v a  2s  .c  o  m*/
    thrown.expect(Exception.class);
    String message = "Test OptimisticPersister exception";
    thrown.expectMessage(message);

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

    mockery.checking(new Expectations() {
        {
            oneOf(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()), with(anything()));
            will(throwException(new Exception(message)));
        }
    });

    String existingDate = existingFridayRecurringRuleWithoutExclusions.getBooking().getDate();
    String exclusionDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusWeeks(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    // ACT
    // This should throw
    // N.B. The third parameter is arbitrary here.
    ruleManager.addRuleExclusion(exclusionDate, existingFridayRecurringRuleWithoutExclusions, true);
}

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

@Test
public void testDeleteYesterdaysBookingsNotifiesTheSnsTopicWhenItThrows() throws Exception {
    // It is useful for the admin user to be notified whenever the deleting
    // of bookings does not succeed - so that they can clean the database
    // manually instead. This tests that whenever the booking manager catches an
    // exception while deleting bookings, it notifies the admin SNS topic.

    // ARRANGE//from   w ww  .  j ava  2s. c om
    thrown.expect(Exception.class);
    String message = "Test Exception";
    thrown.expectMessage(message);

    initialiseBookingManager();

    // Make method throw
    String yesterday = fakeCurrentDate.minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    AmazonServiceException ase = new AmazonServiceException(message);
    mockery.checking(new Expectations() {
        {
            oneOf(mockOptimisticPersister).deleteAllAttributes(with(equal(yesterday)));
            will(throwException(ase));
        }
    });
    bookingManager.setOptimisticPersister(mockOptimisticPersister);

    // Set up mock SNS client to expect a notification
    mockSNSClient = mockery.mock(AmazonSNS.class);
    String partialMessage = "Apologies - but there was an error deleting yesterday's bookings from the database";
    mockery.checking(new Expectations() {
        {
            oneOf(mockSNSClient).publish(with(equal(adminSnsTopicArn)), with(startsWith(partialMessage)),
                    with(equal("Sqawsh bookings for yesterday failed to delete")));
        }
    });
    bookingManager.setSNSClient(mockSNSClient);

    // ACT - this should throw - and notify the SNS topic
    // N.B. Parameter is arbitrary here.
    bookingManager.deleteYesterdaysBookings(false);
}

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

@Test
public void testAddRuleExclusionThrowsIfTheOptimisticPersisterThrowsAConditionalCheckFailedExceptionThreeTimesRunning()
        throws Exception {
    // The optimistic persister can throw a conditional check failed exclusion
    // if two database writes happen to get interleaved. Almost always, a retry
    // should fix this, and we allow up to three tries. This tests that if all
    // three tries fail then the rule manager will give up and throw.

    // ARRANGE/*from ww w  . j a va 2  s . c  o m*/
    thrown.expect(Exception.class);
    String message = "Database put failed - conditional check failed";
    thrown.expectMessage(message);

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

    mockery.checking(new Expectations() {
        {
            // All three tries throw
            exactly(3).of(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()),
                    with(anything()));
            will(throwException(new Exception(message)));
        }
    });

    String existingDate = existingFridayRecurringRuleWithoutExclusions.getBooking().getDate();
    String exclusionDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusWeeks(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    // ACT
    // This should throw - albeit after three tries internally
    // N.B. The third parameter is arbitrary here.
    ruleManager.addRuleExclusion(exclusionDate, existingFridayRecurringRuleWithoutExclusions, true);
}

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

@Test
public void testDeleteYesterdaysBookingsCorrectlyCallsTheOptimisticPersister() throws Exception {
    // Set up mock optimistic persister to expect yesterday's bookings to be
    // deleted./* w ww . j a  v  a 2s  .c o m*/
    initialiseBookingManager();

    String yesterday = fakeCurrentDate.minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    mockery.checking(new Expectations() {
        {
            oneOf(mockOptimisticPersister).deleteAllAttributes(with(equal(yesterday)));
        }
    });
    bookingManager.setOptimisticPersister(mockOptimisticPersister);

    // Act
    // N.B. Parameter is arbitrary here.
    bookingManager.deleteYesterdaysBookings(false);
}

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

@Test
public void testAddRuleExclusionDoesNotThrowIfTheOptimisticPersisterThrowsAConditionalCheckFailedExceptionOnlyTwice()
        throws Exception {
    // The optimistic persister can throw a conditional check failed exclusion
    // if two database writes happen to get interleaved. Almost always, a retry
    // should fix this, and we allow up to three tries. This tests that if we
    // throw twice but the third try succeeds, then the rule manager does not
    // throw./*  w  w  w  .j a v a2  s . c  o m*/

    // ARRANGE

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

    final Sequence retrySequence = mockery.sequence("retry");
    mockery.checking(new Expectations() {
        {
            // Two failures...
            exactly(2).of(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()),
                    with(anything()));
            will(throwException(new Exception("Database put failed - conditional check failed")));
            inSequence(retrySequence);
            // ... but third attempt succeeds
            oneOf(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()), with(anything()));
            will(returnValue(2));
            inSequence(retrySequence);
        }
    });

    String existingDate = existingFridayRecurringRuleWithoutExclusions.getBooking().getDate();
    String exclusionDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusWeeks(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

    // ACT
    // This should _not_ throw - we are allowed three tries internally
    // N.B. The third parameter is arbitrary here.
    ruleManager.addRuleExclusion(exclusionDate, existingFridayRecurringRuleWithoutExclusions, true);
}

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

private void doTestDeleteYesterdaysBookingsCorrectlyCallsTheLifecycleManager(boolean isSquashServiceUserCall)
        throws Exception {

    // ARRANGE/* ww w. ja v a 2s  .c  o m*/
    initialiseBookingManager();

    // Set up mock lifecycle manager
    mockLifecycleManager = mockery.mock(ILifecycleManager.class, "replacementLifecycleManagerMock");
    mockery.checking(new Expectations() {
        {
            oneOf(mockLifecycleManager).throwIfOperationInvalidForCurrentLifecycleState(false,
                    isSquashServiceUserCall);
        }
    });
    bookingManager.setLifecycleManager(mockLifecycleManager);

    // Set up optimistic persister to expect bookings to be deleted -
    // this is incidental to the test, but needs to be setup for the test to run
    // at all.
    String yesterday = fakeCurrentDate.minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    mockery.checking(new Expectations() {
        {
            oneOf(mockOptimisticPersister).deleteAllAttributes(with(equal(yesterday)));
        }
    });
    bookingManager.setOptimisticPersister(mockOptimisticPersister);

    // ACT
    bookingManager.deleteYesterdaysBookings(isSquashServiceUserCall);
}

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

@Test
public void testAddRuleExclusionThrowsIfExclusionOccursBeforeRuleStarts() throws Exception {
    // Exclusions must be for dates after their rule begins.

    // ARRANGE/*from  www.j  a  va  2  s .c  o  m*/
    thrown.expect(Exception.class);
    thrown.expectMessage("Booking rule exclusion addition failed");

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

    String ruleStartDate = existingSaturdayRecurringRuleWithExclusion.getBooking().getDate();
    String saturdayExclusionDateBeforeRuleStarts = LocalDate
            .parse(ruleStartDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusWeeks(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

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