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:edu.wustl.lookingglass.community.CommunityRepository.java

private void resolveMerge() throws NoWorkTreeException, GitAPIException, IOException {
    assert this.username != null;
    assert this.email != null;

    Status status = this.git.status().call();
    Map<String, StageState> conflicting = status.getConflictingStageState();

    for (String path : conflicting.keySet()) {
        StageState stageState = conflicting.get(path);
        switch (stageState) {
        case BOTH_MODIFIED: // UU
        case BOTH_ADDED: // AA
        case ADDED_BY_US: // AU
        case ADDED_BY_THEM: // UA
            // Both the local and server version have been modified
            File conflictingFile = new File(this.repoDir, path);
            String fullPath = conflictingFile.getAbsolutePath();

            // Since the local copy was modified it probably makes sense to leave it
            // since that's the copy the user has been working on. Here's my assumption...
            // a sync didn't happen, so the user opens their project and sees it's not their
            // latest changes, they accept the failure and start to fix it... finally a sync
            // happens... at this point they are probably editing this world, so when they save
            // they wouldn't even load the new file, so we should just keep the old file.

            // TODO: we should really prompt the user to resolve this conflict.
            // but that's kinda hard with the singletons... because you probably just want
            // to open both files in two different windows (editors) but we can't do that. :(

            // Recover server version
            this.git.checkout().setStage(Stage.THEIRS).addPath(path).call();

            // Append a timestamp
            LocalDateTime date = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-mm-dd+HH'h'MM'm'");
            String timestamp = date.format(formatter);
            File theirFile = new File(FilenameUtils.getFullPath(fullPath), FilenameUtils.getBaseName(path)
                    + " (" + timestamp + ")." + FilenameUtils.getExtension(path));

            if (conflictingFile.exists() && !theirFile.exists()) {
                Files.move(conflictingFile.toPath(), theirFile.toPath());

                String relativePath = this.repoDir.toURI().relativize(theirFile.toURI()).getPath();
                this.git.add().addFilepattern(relativePath).call();
            }/* w w  w  .j  a  v a 2 s.  co m*/

            // Recover local version
            this.git.checkout().setStage(Stage.OURS).addPath(path).call();
            this.git.add().addFilepattern(path).call();
            break;

        case DELETED_BY_US: // DU
            // The modified local version is already in the checkout, so it just needs to be added.
            // We need to specifically mention the file, so we can't reuse the Add () method
            this.git.add().addFilepattern(path).call();
            break;
        case DELETED_BY_THEM: // UD
            // Recover server version
            this.git.checkout().setStage(Stage.THEIRS).addPath(path).call();
            this.git.add().addFilepattern(path).call();
            break;
        case BOTH_DELETED: // DD
            break;
        default:
            throw new IllegalArgumentException("Unknown StageState: " + stageState);
        }
    }

    RepositoryState resolvedState = this.git.getRepository().getRepositoryState();
    assert resolvedState == RepositoryState.MERGING_RESOLVED;

    // we are done resolving the merge!
    this.git.commit().setAuthor(this.username, this.email).call();

    RepositoryState safeState = this.git.getRepository().getRepositoryState();
    assert safeState == RepositoryState.SAFE;
}

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

/**
 * Get the main information of the report
 * //from ww  w  .j  a v a  2 s  .  co  m
 * @return
 */
private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    final TypedTableModel model = new TypedTableModel(
            new String[] { "currentDate", "center", "researchProgram" },
            new Class[] { String.class, String.class, String.class });
    String currentDate = "";

    // Get datetime
    final ZonedDateTime timezone = ZonedDateTime.now();
    final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    currentDate = timezone.format(format) + this.getTimeZone();
    final String center = this.getCenterSession();

    model.addRow(new Object[] { currentDate, center, researchProgram.getName() });
    return model;
}

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

private List<String> getTimeSlotLabels() {

    // First time slot of the day is 10am...
    // ...so initialise to one time slot (i.e. 45 minutes) earlier
    logger.log("About to get time slot labels");
    LocalTime time = LocalTime.of(9, 15);
    List<String> timeSlots = new ArrayList<>();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a");
    for (int slots = 1; slots <= 16; slots++) {
        time = time.plusMinutes(45);/*from  w  w w  .j av a 2 s  .  c o  m*/
        timeSlots.add(time.format(formatter));
    }
    logger.log("Got slot labels: " + timeSlots);

    return timeSlots;
}

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

@Test
public void testCreateRuleDoesNotThrowIfTheOptimisticPersisterThrowsAConditionalCheckFailedExceptionOnlyTwice()
        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./*from   w w w. ja va2  s .co  m*/

    // ARRANGE
    int versionToUse = 1; // Arbitrary
    expectOptimisticPersisterToReturnVersionedAttributes(versionToUse, 3);
    initialiseRuleManager();

    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingRule = new BookingRule(existingThursdayNonRecurringRule);
    // Change day-of-week so it no longer clashes
    String existingDate = nonClashingRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusDays(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingRule.getBooking().setDate(newDate); // Wednesday

    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);
        }
    });

    // ACT
    // This should _not_ throw - we are allowed three tries
    // N.B. The second parameter is arbitrary here.
    ruleManager.createRule(nonClashingRule, true);
}

From source file:org.talend.dataprep.api.filter.SimpleFilterService.java

/**
 * Test a string value against a pattern returned during value analysis.
 *
 * @param value A string value. May be null.
 * @param pattern A pattern as returned in value analysis.
 * @return <code>true</code> if value matches, <code>false</code> otherwise.
 *///from  w w w  .  ja  v a2  s .c o  m
private boolean matches(String value, String pattern) {
    if (value == null && pattern == null) {
        return true;
    }
    if (value == null) {
        return false;
    }
    // Character based patterns
    if (StringUtils.containsAny(pattern, new char[] { 'A', 'a', '9' })) {
        if (value.length() != pattern.length()) {
            return false;
        }
        final char[] valueArray = value.toCharArray();
        final char[] patternArray = pattern.toCharArray();
        for (int i = 0; i < valueArray.length; i++) {
            if (patternArray[i] == 'A') {
                if (!Character.isUpperCase(valueArray[i])) {
                    return false;
                }
            } else if (patternArray[i] == 'a') {
                if (!Character.isLowerCase(valueArray[i])) {
                    return false;
                }
            } else if (patternArray[i] == '9') {
                if (!Character.isDigit(valueArray[i])) {
                    return false;
                }
            } else {
                if (valueArray[i] != patternArray[i]) {
                    return false;
                }
            }
        }
    } else {
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        try {
            formatter.toFormat().parseObject(value);
        } catch (ParseException e) {
            return false;
        }
    }
    return true;
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets a list of all the posted ballots of the given election form the bulletin board and returns it
 * @param election/*from ww  w  .j a  v a2s.  c o m*/
 * Election for which the list of ballots should be retrieved 
 * @return 
 * the list of all posted ballots to the given election
 */
public List<Ballot> getBallotsByElection(Election election) {
    List<Ballot> ballots = new ArrayList<Ballot>();
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + election.getId() + "/ballots");

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //transforms the recieved json string into a list of ballot objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            LocalDateTime timeStamp = LocalDateTime.parse(result.getString("timestamp"), format);

            JsonObject jsonData = result.getJsonObject("jsonData");
            List<String> selectedOptions = new ArrayList<String>();
            JsonArray optionsArray = jsonData.getJsonArray("e");
            for (int i = 0; i < optionsArray.size(); i++) {
                selectedOptions.add(optionsArray.getString(i));
            }
            String u_HatString = jsonData.getString("u_Hat");
            String cString = jsonData.getString("c");
            String dString = jsonData.getString("d");
            String pi1String = jsonData.getString("pi1");
            String pi2String = jsonData.getString("pi2");
            String pi3String = jsonData.getString("pi3");
            //create ballot object and add it to the list
            Ballot ballot = new Ballot(id, election, selectedOptions, u_HatString, cString, dString, pi1String,
                    pi2String, pi3String, timeStamp);
            System.out.println(ballot.isValid());
            ballots.add(ballot);
        }

    } catch (IOException x) {
        System.err.println(x);
    }
    return ballots;

}

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

private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    TypedTableModel model = new TypedTableModel(new String[] { "date", "center", "showDescription" },
            new Class[] { String.class, String.class, Boolean.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";
    }// www .ja  va  2  s  .  co m
    String date = timezone.format(format) + "(GMT" + zone + ")";
    model.addRow(new Object[] { date, center, this.hasSpecificities(APConstants.CRP_REPORTS_DESCRIPTION) });
    return model;
}

From source file:org.openlmis.fulfillment.web.OrderControllerIntegrationTest.java

@Test
public void shouldExportOrderIfTypeIsNotSpecified() {
    String csvContent = restAssured.given().header(HttpHeaders.AUTHORIZATION, getTokenHeader())
            .pathParam("id", secondOrder.getId()).when().get(EXPORT_URL).then().statusCode(200).extract().body()
            .asString();/* w w w  .j  av  a  2s .co  m*/

    assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
    assertTrue(csvContent.startsWith(
            "Order number,Facility code,Product code,Product name," + "Ordered quantity,Period,Order date"));

    String orderDate = secondOrder.getCreatedDate().format(DateTimeFormatter.ofPattern("dd/MM/yy"));

    for (OrderLineItem lineItem : secondOrder.getOrderLineItems()) {
        String string = StringUtils.joinWith(",", secondOrder.getOrderCode(), facility2.getCode(),
                "Product Code", "Product Name", lineItem.getOrderedQuantity(),
                period1.getStartDate().format(DateTimeFormatter.ofPattern("MM/yy")), orderDate);
        assertThat(csvContent, containsString(string));
    }
}

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

@Test
public void testCreateNonrecurringRuleHappyPathCallsTheOptimisticPersisterCorrectly() throws Exception {
    // Happy path where createRule goes right through and creates the
    // non-recurring rule.

    // ARRANGE//from w w w. ja  v a 2 s  . c o m

    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingRule = new BookingRule(existingThursdayNonRecurringRule);
    // Change day-of-week so it no longer clashes
    String existingDate = nonClashingRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusDays(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingRule.getBooking().setDate(newDate); // Wednesday

    doTestCreateRuleClashesOrNotWithExistingRule(nonClashingRule, false);
}

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

@Test
public void testCreateRecurringRuleHappyPathCallsTheOptimisticPersisterCorrectly() throws Exception {
    // Happy path where createRule goes right through and creates the recurring
    // rule./*from   w w w .  java  2 s .  c o m*/

    // ARRANGE

    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingRule = new BookingRule(existingFridayRecurringRuleWithoutExclusions);
    // Change day-of-week so it no longer clashes
    String existingDate = nonClashingRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(2)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingRule.getBooking().setDate(newDate); // Sunday

    doTestCreateRuleClashesOrNotWithExistingRule(nonClashingRule, false);
}