Example usage for java.time LocalDateTime format

List of usage examples for java.time LocalDateTime format

Introduction

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

Prototype

@Override 
public String format(DateTimeFormatter formatter) 

Source Link

Document

Formats this date-time using the specified formatter.

Usage

From source file:com.publictransitanalytics.scoregenerator.output.NetworkAccessibility.java

public NetworkAccessibility(final int taskCount, final ScoreCard scoreCard, final Grid grid,
        final Set<Sector> centerSectors, final LocalDateTime startTime, final LocalDateTime endTime,
        final Duration tripDuration, final Duration samplingInterval, final boolean backward,
        final Duration inServiceTime) throws InterruptedException {
    type = AccessibilityType.NETWORK_ACCESSIBILITY;

    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    boundsCenter = new Point(grid.getBounds().getCenter());
    this.startTime = startTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.endTime = endTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.samplingInterval = DurationFormatUtils.formatDurationWords(samplingInterval.toMillis(), true, true);

    this.tripDuration = DurationFormatUtils.formatDurationWords(tripDuration.toMillis(), true, true);

    this.taskCount = taskCount;

    final Set<Sector> sectors = grid.getAllSectors();
    totalSectors = grid.getReachableSectors().size();

    final ImmutableMap.Builder<Bounds, Integer> countBuilder = ImmutableMap.builder();
    for (final Sector sector : sectors) {
        if (scoreCard.hasPath(sector)) {
            final Bounds bounds = new Bounds(sector);
            countBuilder.put(bounds, scoreCard.getReachedCount(sector));
        }//from w  w  w  .j a va  2s  .c om
    }
    sectorCounts = countBuilder.build();

    this.centerPoints = centerSectors.stream().map(sector -> new Point(sector.getBounds().getCenter()))
            .collect(Collectors.toSet());
    sampleCount = centerPoints.size();

    inServiceSeconds = inServiceTime.getSeconds();
}

From source file:fi.helsinki.opintoni.integration.coursepage.CoursePageRestClient.java

@Override
public List<CoursePageNotification> getCoursePageNotifications(Set<String> courseImplementationIds,
        LocalDateTime from, Locale locale) {
    if (courseImplementationIds.isEmpty()) {
        return newArrayList();
    }// ww  w  .  jav a2s  .  c  om

    ResponseEntity<List<CoursePageNotification>> responseEntity = restTemplate.exchange(
            "{baseUrl}/course_implementation_activity"
                    + "?course_implementation_id={courseImplementationIds}&timestamp={from}&langcode={locale}",
            HttpMethod.GET, null, new ParameterizedTypeReference<List<CoursePageNotification>>() {
            }, baseUrl, courseImplementationIds.stream().collect(Collectors.joining(",")),
            from.format(DateFormatter.COURSE_PAGE_DATE_TIME_FORMATTER), locale.getLanguage());

    return Optional.ofNullable(responseEntity.getBody()).orElse(newArrayList());
}

From source file:com.publictransitanalytics.scoregenerator.output.ComparativeTimeQualifiedPointAccessibility.java

public ComparativeTimeQualifiedPointAccessibility(final PathScoreCard scoreCard,
        final PathScoreCard trialScoreCard, final Grid grid, final Center centerPoint, final LocalDateTime time,
        LocalDateTime trialTime, final Duration tripDuration, final boolean backward, final String name,
        final String trialName, final Duration inServiceTime, final Duration trialInServiceTime)
        throws InterruptedException {

    type = AccessibilityType.COMPARATIVE_TIME_QUALIFIED_POINT_ACCESSIBILITY;
    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    center = new Point(centerPoint.getLogicalCenter().getPointRepresentation());
    this.time = time.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialTime = trialTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));

    this.tripDuration = DurationFormatUtils.formatDurationWords(tripDuration.toMillis(), true, true);
    final ImmutableMap.Builder<Bounds, ComparativeFullSectorReachInformation> builder = ImmutableMap.builder();

    final Set<Sector> sectors = grid.getAllSectors();

    final TaskIdentifier task = new TaskIdentifier(time, centerPoint);
    for (final Sector sector : sectors) {
        final MovementPath sectorPath = scoreCard.getBestPath(sector, task);
        final MovementPath trialSectorPath = trialScoreCard.getBestPath(sector, task);
        if (sectorPath != null || trialSectorPath != null) {
            final Bounds sectorBounds = new Bounds(sector);

            builder.put(sectorBounds, new ComparativeFullSectorReachInformation(sectorPath, trialSectorPath));
        }//from   w  w  w.  ja va  2 s.c o m
    }
    sectorPaths = builder.build();
    totalSectors = grid.getReachableSectors().size();
    this.name = name;
    this.trialName = trialName;
    inServiceSeconds = inServiceTime.getSeconds();
    trialInServiceSeconds = trialInServiceTime.getSeconds();
}

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

/**
 * Gets a List of ElectionHeaders from the Bulletin Board and returns it. Fetched list depends on the given ElectionFilterTyp
 * @param filter// w  w  w .  j  a  va2  s  .c  o m
 * The filter can be set to All, Open or Closed
 * @return returns a list of election headers
 */
public List<ElectionHeader> getElectionHeaders(ElectionFilterTyp filter) {
    List<ElectionHeader> electionHeaderlist = new ArrayList<ElectionHeader>();

    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime actualDateTime = LocalDateTime.now();
    String dateTimeString = actualDateTime.format(format);

    URL url = null;
    //depending on the filter a different request is sent to the bulletin board
    switch (filter) {
    // if the filter is set to ALL, all the electionheaders on the bulletin board are requested
    case ALL: {
        try {
            url = new URL(bulletinBoardUrl + "/elections");
        } catch (MalformedURLException ex) {
            Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
        break;

    // if the filter is set to OPEN only ElectionHeaders where the VotingPeriod is still going are requested from the bulletin board
    case OPEN: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/open?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    // if the filter is set to CLOSED only ElectionHeaders where the VotingPeriod is already over are requested from the bulletin board
    case CLOSED: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/closed?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    }

    try {

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        //Recieved Json String is transformed into a list of ElectionHeader objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            String title = result.getString("electionTitle");
            LocalDateTime beginDate = LocalDateTime.parse(result.getString("beginDate"), format);
            LocalDateTime endDate = LocalDateTime.parse(result.getString("endDate"), format);

            ElectionHeader electionHeader = new ElectionHeader(id, title, beginDate, endDate);
            electionHeaderlist.add(electionHeader);
        }
    } catch (IOException x) {
        System.err.println(x);
    }

    return electionHeaderlist;
}

From source file:com.publictransitanalytics.scoregenerator.output.ComparativePointAccessibility.java

public ComparativePointAccessibility(final int taskCount, final int trialTaskCount,
        final PathScoreCard scoreCard, final PathScoreCard trialScoreCard, final Grid grid,
        final PointLocation centerPoint, final LocalDateTime startTime, final LocalDateTime endTime,
        final LocalDateTime trialStartTime, final LocalDateTime trialEndTime, final Duration samplingInterval,
        final Duration tripDuration, final boolean backward, final String trialName,
        final Duration inServiceTime, final Duration trialInServiceTime) throws InterruptedException {
    type = AccessibilityType.COMPARATIVE_POINT_ACCESSIBILITY;
    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    center = new Point(centerPoint);
    this.startTime = startTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.endTime = endTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialStartTime = trialStartTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialEndTime = trialEndTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.samplingInterval = DurationFormatUtils.formatDurationWords(samplingInterval.toMillis(), true, true);

    this.tripDuration = DurationFormatUtils.formatDurationWords(tripDuration.toMillis(), true, true);

    this.taskCount = taskCount;
    this.trialTaskCount = trialTaskCount;

    final Set<Sector> sectors = grid.getAllSectors();
    totalSectors = grid.getReachableSectors().size();

    final ImmutableMap.Builder<Bounds, ComparativeSectorReachInformation> informationBuilder = ImmutableMap
            .builder();/*w w  w .ja  va2s . c  om*/

    for (final Sector sector : sectors) {
        final Map<LogicalTask, MovementPath> bestPaths = scoreCard.getBestPaths(sector);
        final Map<LogicalTask, MovementPath> trialBestPaths = trialScoreCard.getBestPaths(sector);
        if (!bestPaths.isEmpty() || !trialBestPaths.isEmpty()) {
            final Set<MovementPath> bestPathSet = getBestPathSet(bestPaths);
            final Set<LocalDateTime> reachTimes = scoreCard.getReachedTimes(sector);
            final Set<MovementPath> trialBestPathSet = getBestPathSet(trialBestPaths);
            final Set<LocalDateTime> trialReachTimes = trialScoreCard.getReachedTimes(sector);
            int numBestPaths = bestPathSet.size();
            int numTrialBestPaths = trialBestPathSet.size();

            final Bounds bounds = new Bounds(sector);
            final ComparativeSectorReachInformation information = new ComparativeSectorReachInformation(
                    bestPathSet, numBestPaths, reachTimes, trialBestPathSet, numTrialBestPaths,
                    trialReachTimes);
            informationBuilder.put(bounds, information);
        }
    }
    sectorPaths = informationBuilder.build();
    this.trialName = trialName;

    inServiceSeconds = inServiceTime.getSeconds();
    trialInServiceSeconds = trialInServiceTime.getSeconds();
}

From source file:com.publictransitanalytics.scoregenerator.output.ComparativeNetworkAccessibility.java

public ComparativeNetworkAccessibility(final int taskCount, final int trialTaskCount, final ScoreCard scoreCard,
        final ScoreCard trialScoreCard, final Grid grid, final Set<Sector> centerSectors,
        final LocalDateTime startTime, final LocalDateTime endTime, final LocalDateTime trialStartTime,
        final LocalDateTime trialEndTime, final Duration tripDuration, final Duration samplingInterval,
        final boolean backward, final String trialName, final Duration inServiceTime,
        final Duration trialInServiceTime) throws InterruptedException {
    type = AccessibilityType.COMPARATIVE_NETWORK_ACCESSIBILITY;

    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    boundsCenter = new Point(grid.getBounds().getCenter());
    this.startTime = startTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.endTime = endTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialStartTime = trialStartTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialEndTime = trialEndTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.samplingInterval = DurationFormatUtils.formatDurationWords(samplingInterval.toMillis(), true, true);

    this.tripDuration = DurationFormatUtils.formatDurationWords(tripDuration.toMillis(), true, true);

    this.taskCount = taskCount;
    this.trialTaskCount = trialTaskCount;

    final Set<Sector> sectors = grid.getAllSectors();
    totalSectors = grid.getReachableSectors().size();

    final ImmutableMap.Builder<Bounds, CountComparison> countBuilder = ImmutableMap.builder();
    for (final Sector sector : sectors) {
        final int count = scoreCard.hasPath(sector) ? scoreCard.getReachedCount(sector) : 0;
        final int trialCount = trialScoreCard.hasPath(sector) ? trialScoreCard.getReachedCount(sector) : 0;

        if (count != 0 && trialCount != 0) {
            final Bounds bounds = new Bounds(sector);
            final CountComparison comparison = new CountComparison(count, trialCount);
            countBuilder.put(bounds, comparison);
        }//from w ww.j  av  a 2s  .  c o m
    }

    sectorCounts = countBuilder.build();

    this.centerPoints = centerSectors.stream().map(sector -> new Point(sector.getBounds().getCenter()))
            .collect(Collectors.toSet());
    sampleCount = centerPoints.size();

    this.trialName = trialName;

    inServiceSeconds = inServiceTime.getSeconds();
    trialInServiceSeconds = trialInServiceTime.getSeconds();
}

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  ww. j av  a 2 s .  c  o 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.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

@Test
public void testGenerateJWT() throws Exception {
    ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1);
    JWTSecurityHandler.JWTMaterialParameter jwtParam = createJWTParameter(appId);

    RMAppSecurityActions actor = RMAppSecurityActionsFactory.getInstance().getActor(conf);
    String jwt = actor.generateJWT(jwtParam);
    Assert.assertNotNull(jwt);/*from   w w  w  .j a v a2 s  . com*/
    String[] tokenizedSubject = JWT_SUBJECT.split("__");
    JWT decoded = JWTParser.parse(jwt);
    String subject = decoded.getJWTClaimsSet().getSubject();
    Assert.assertEquals(tokenizedSubject[1], subject);

    // Test generate and fall-back to application submitter
    appId = ApplicationId.newInstance(System.currentTimeMillis(), 2);
    jwtParam = new JWTSecurityHandler.JWTMaterialParameter(appId, "dorothy");
    jwtParam.setRenewable(false);
    LocalDateTime now = DateUtils.getNow();
    LocalDateTime expiresAt = now.plus(10L, ChronoUnit.MINUTES);
    jwtParam.setExpirationDate(expiresAt);
    jwtParam.setValidNotBefore(now);
    jwtParam.setAudiences(new String[] { "job" });
    jwt = actor.generateJWT(jwtParam);
    decoded = JWTParser.parse(jwt);
    subject = decoded.getJWTClaimsSet().getSubject();
    Assert.assertEquals("dorothy", subject);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    LocalDateTime nbfFromToken = DateUtils.date2LocalDateTime(decoded.getJWTClaimsSet().getNotBeforeTime());
    Assert.assertEquals(now.format(formatter), nbfFromToken.format(formatter));
    LocalDateTime expirationFromToken = DateUtils
            .date2LocalDateTime(decoded.getJWTClaimsSet().getExpirationTime());
    Assert.assertEquals(expiresAt.format(formatter), expirationFromToken.format(formatter));
}

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);//  w  ww  . ja va  2s  . 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:net.resheim.eclipse.timekeeper.ui.Activator.java

/**
 * Must be called by the UI-thread// w w w.  jav a 2 s  .  co m
 *
 * @param idleTimeMillis
 */
private void handleReactivation(long idleTimeMillis) {
    // We want only one dialog open.
    if (dialogIsOpen) {
        return;
    }
    synchronized (this) {
        if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
            // If we have an active task
            ITask task = TasksUi.getTaskActivityManager().getActiveTask();
            if (task != null && Activator.getValue(task, Activator.START) != null) {
                dialogIsOpen = true;
                String tickString = Activator.getValue(task, Activator.TICK);
                LocalDateTime started = getActiveSince();
                LocalDateTime ticked = LocalDateTime.parse(tickString);
                LocalDateTime lastTick = ticked;
                // Subtract the IDLE_INTERVAL time the computer _was_
                // idle while counting up to the threshold. During this
                // period fields were updated. Thus must be adjusted for.
                ticked = ticked.minusNanos(IDLE_INTERVAL);
                String time = DurationFormatUtils.formatDuration(lastIdleTime, "H:mm:ss", true);

                StringBuilder sb = new StringBuilder();
                if (task.getTaskKey() != null) {
                    sb.append(task.getTaskKey());
                    sb.append(": ");
                }
                sb.append(task.getSummary());
                MessageDialog md = new MessageDialog(Display.getCurrent().getActiveShell(),
                        "Disregard idle time?", null,
                        MessageFormat.format(
                                "The computer has been idle since {0}, more than {1}. The active task \"{2}\" was started on {3}. Deactivate the task and disregard the idle time?",
                                ticked.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US)), time,
                                sb.toString(),
                                started.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US))),
                        MessageDialog.QUESTION, new String[] { "No", "Yes" }, 1);
                int open = md.open();
                dialogIsOpen = false;
                if (open == 1) {
                    // Stop task, subtract initial idle time
                    TasksUi.getTaskActivityManager().deactivateTask(task);
                    reduceTime(task, ticked.toLocalDate().toString(), IDLE_INTERVAL / 1000);
                } else {
                    // Continue task, add idle time
                    LocalDateTime now = LocalDateTime.now();
                    long seconds = lastTick.until(now, ChronoUnit.MILLIS);
                    accumulateTime(task, ticked.toLocalDate().toString(), seconds);
                    Activator.setValue(task, Activator.TICK, now.toString());
                }
            }
        }
    }
}