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 testApplyRulesCallsBookingManagerCorrectly_PurgeExpiredRuleExclusions() throws Exception {
    // applyRules should delete rule exclusions for dates before the current
    // day.//from   w  w  w.j a  v a2s .c  o m

    // ARRANGE
    initialiseRuleManager();

    // Set the current date to a date after an exclusion, but also for a
    // day-of-the-week when no other rules apply (just to avoid extra
    // createBooking noise):
    String exclusionDate = existingSaturdayRecurringRuleWithExclusion.getDatesToExclude()[0];
    String daysAfterExclusionDate = LocalDate.parse(exclusionDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            .plusDays(2).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    ruleManager.setCurrentLocalDate(
            LocalDate.parse(daysAfterExclusionDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));

    expectOptimisticPersisterToReturnVersionedAttributes(42);
    expectPurgeExpiredRulesAndRuleExclusions(42, existingBookingRules,
            Optional.of(existingThursdayNonRecurringRule),
            Optional.of(new ImmutablePair<>(existingSaturdayRecurringRuleWithExclusion, exclusionDate)));

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

From source file:org.apache.hadoop.hive.metastore.ObjectStore.java

private String createDbGuidAndPersist() throws MetaException {
    boolean success = false;
    Query query = null;/*from www. ja va 2  s  . co  m*/
    try {
        openTransaction();
        MMetastoreDBProperties prop = new MMetastoreDBProperties();
        prop.setPropertykey("guid");
        final String guid = UUID.randomUUID().toString();
        LOG.debug("Attempting to add a guid " + guid + " for the metastore db");
        prop.setPropertyValue(guid);
        prop.setDescription("Metastore DB GUID generated on "
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
        pm.makePersistent(prop);
        success = commitTransaction();
        if (success) {
            LOG.info("Metastore db guid " + guid + " created successfully");
            return guid;
        }
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    } finally {
        rollbackAndCleanup(success, query);
    }
    // it possible that some other HMS instance could have created the guid
    // at the same time due which this instance could not create a guid above
    // in such case return the guid already generated
    final String guid = getGuidFromDB();
    if (guid == null) {
        throw new MetaException("Unable to create or fetch the metastore database uuid");
    }
    return guid;
}

From source file:sg.ncl.MainController.java

@RequestMapping("/admin/usage")
public String adminTeamUsage(Model model, @RequestParam(value = "start", required = false) String start,
        @RequestParam(value = "end", required = false) String end,
        @RequestParam(value = "organizationType", required = false) String organizationType,
        @RequestParam(value = "team", required = false) String team,
        final RedirectAttributes redirectAttributes, HttpSession session)
        throws IOException, WebServiceRuntimeException {
    if (!validateIfAdmin(session)) {
        return NO_PERMISSION_PAGE;
    }//  www . jav  a2 s.c o  m

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    ZonedDateTime nowDate = ZonedDateTime.now();
    String now = nowDate.format(formatter);
    if (start == null) {
        start = nowDate.with(firstDayOfMonth()).format(formatter);
    }
    if (end == null) {
        end = now;
    }
    if (now.compareTo(start) < 0 || now.compareTo(end) < 0) {
        redirectAttributes.addFlashAttribute(MESSAGE, "Period selected is beyond current date (today).");
        return REDIRECT_TEAM_USAGE;
    }

    // get list of teamids
    HttpEntity<String> request = createHttpEntityHeaderOnly();
    ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request,
            String.class);
    JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());

    List<Team2> searchTeams = new ArrayList<>();
    TeamManager2 teamManager2 = new TeamManager2();
    getSearchTeams(organizationType, team, jsonArray, searchTeams, teamManager2);

    if (!searchTeams.isEmpty()) {
        List<String> dates = getDates(start, end, formatter);

        Map<String, List<Long>> teamUsages = new HashMap<>();
        Long totalUsage = 0L;
        for (Team2 team2 : searchTeams) {
            try {
                List<Long> usages = new ArrayList<>();
                totalUsage += getTeamUsageStatistics(team2, start, end, request, usages);
                teamUsages.put(team2.getName(), usages);
            } catch (RestClientException rce) {
                log.warn("Error connecting to sio analytics service for team usage: {}", rce);
                redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
                return REDIRECT_TEAM_USAGE;
            } catch (StartDateAfterEndDateException sde) {
                redirectAttributes.addFlashAttribute(MESSAGE, ERR_START_DATE_AFTER_END_DATE);
                return REDIRECT_TEAM_USAGE;
            }
        }
        model.addAttribute("dates", dates);
        model.addAttribute("teamUsages", teamUsages);
        model.addAttribute("totalUsage", totalUsage);
    }

    List<Team2> allTeams = new ArrayList<>(teamManager2.getTeamMap().values());
    allTeams.sort(Comparator.comparing(Team2::getName, String.CASE_INSENSITIVE_ORDER));
    model.addAttribute(ALL_TEAMS, allTeams);
    model.addAttribute("start", start);
    model.addAttribute("end", end);
    model.addAttribute("organizationType", organizationType);
    model.addAttribute("team", team);
    return "usage_statistics";
}

From source file:sg.ncl.MainController.java

@RequestMapping(value = "/admin/energy", method = RequestMethod.GET)
public String adminEnergy(Model model, @RequestParam(value = "start", required = false) String start,
        @RequestParam(value = "end", required = false) String end, final RedirectAttributes redirectAttributes,
        HttpSession session) throws IOException {

    if (!validateIfAdmin(session)) {
        return NO_PERMISSION_PAGE;
    }//from  w  ww  .  jav a 2s  .  c o  m

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    ZonedDateTime now = ZonedDateTime.now();
    if (start == null) {
        ZonedDateTime startDate = now.with(firstDayOfMonth());
        start = startDate.format(formatter);
    }
    if (end == null) {
        ZonedDateTime endDate = now.with(lastDayOfMonth());
        end = endDate.format(formatter);
    }

    HttpEntity<String> request = createHttpEntityHeaderOnly();

    ResponseEntity responseEntity;
    try {
        responseEntity = restTemplate.exchange(
                properties.getEnergyStatistics("startDate=" + start, "endDate=" + end), HttpMethod.GET, request,
                String.class);
    } catch (RestClientException e) {
        log.warn("Error connecting to sio analytics service for energy usage: {}", e);
        redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
        return REDIRECT_ENERGY_USAGE;
    }

    String responseBody = responseEntity.getBody().toString();
    JSONArray jsonArray = new JSONArray(responseBody);

    // handling exceptions from SIO
    if (RestUtil.isError(responseEntity.getStatusCode())) {
        MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
        ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
        switch (exceptionState) {
        case START_DATE_AFTER_END_DATE_EXCEPTION:
            log.warn("Get energy usage : Start date after end date error");
            redirectAttributes.addFlashAttribute(MESSAGE, ERR_START_DATE_AFTER_END_DATE);
            return REDIRECT_ENERGY_USAGE;

        default:
            log.warn("Get energy usage : sio or deterlab adapter connection error");
            redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
            return REDIRECT_ENERGY_USAGE;
        }
    } else {
        log.info("Get energy usage info : {}", responseBody);
    }

    DecimalFormat df2 = new DecimalFormat(".##");

    double sumEnergy = 0.00;
    List<String> listOfDate = new ArrayList<>();
    List<Double> listOfEnergy = new ArrayList<>();
    ZonedDateTime currentZonedDateTime = convertToZonedDateTime(start);
    String currentDate = null;
    for (int i = 0; i < jsonArray.length(); i++) {
        sumEnergy += jsonArray.getDouble(i);

        // add into listOfDate to display graph
        currentDate = currentZonedDateTime.format(formatter);
        listOfDate.add(currentDate);

        // add into listOfEnergy to display graph
        double energy = Double.valueOf(df2.format(jsonArray.getDouble(i)));
        listOfEnergy.add(energy);

        currentZonedDateTime = convertToZonedDateTime(currentDate).plusDays(1);
    }

    sumEnergy = Double.valueOf(df2.format(sumEnergy));
    model.addAttribute("listOfDate", listOfDate);
    model.addAttribute("listOfEnergy", listOfEnergy);
    model.addAttribute("start", start);
    model.addAttribute("end", end);
    model.addAttribute("energy", sumEnergy);
    return "energy_usage";
}

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

private TypedTableModel getMasterTableModel(List<CrpProgram> flagships, List<CrpProgram> regions,
        ProjectPartner projectLeader) {/*from  w  w w. jav a 2 s. co  m*/
    // Initialization of Model
    TypedTableModel model = new TypedTableModel(
            new String[] { "title", "center", "current_date", "project_submission", "cycle", "isNew",
                    "isAdministrative", "type", "isGlobal", "isPhaseOne", "budget_gender", "hasTargetUnit",
                    "hasW1W2Co", "hasActivities", "phaseID" },
            new Class[] { String.class, String.class, String.class, String.class, String.class, Boolean.class,
                    Boolean.class, String.class, Boolean.class, Boolean.class, Boolean.class, Boolean.class,
                    Boolean.class, Boolean.class, Long.class });
    // Filling title
    String title = "";
    if (projectLeader != null) {
        if (projectLeader.getInstitution() != null && projectLeader.getInstitution().getAcronym() != ""
                && projectLeader.getInstitution().getAcronym() != null) {
            title += projectLeader.getInstitution().getAcronym() + "-";
        }
    }
    if (projectInfo.getAdministrative() == false) {
        if (flagships != null) {
            if (!flagships.isEmpty()) {
                for (CrpProgram crpProgram : flagships) {
                    title += crpProgram.getAcronym() + "-";
                }
            }
        }
        if (projectInfo.getNoRegional() != null && projectInfo.getNoRegional()) {
            title += "Global" + "-";
        } else {
            if (regions != null && !regions.isEmpty()) {
                for (CrpProgram crpProgram : regions) {
                    title += crpProgram.getAcronym() + "-";
                }
            }
        }
    }
    title += "P" + Long.toString(projectID);
    // Get datetime
    ZonedDateTime timezone = ZonedDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    String zone = timezone.getOffset() + "";
    if (zone.equals("Z")) {
        zone = "+0";
    }
    String currentDate = timezone.format(format) + "(GMT" + zone + ")";
    // Filling submission
    List<Submission> submissions = new ArrayList<>();
    for (Submission submission : project
            .getSubmissions().stream().filter(c -> c.getCycle().equals(this.getSelectedCycle())
                    && c.getYear() == this.getSelectedYear() && c.getUnSubmitUser() == null)
            .collect(Collectors.toList())) {
        submissions.add(submission);
    }
    String submission = "";
    if (!submissions.isEmpty()) {
        if (submissions.size() > 1) {
            LOG.error("More than one submission was found, the report will retrieve the first one");
        }
        Submission fisrtSubmission = submissions.get(0);
        String submissionDate = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm")
                .format(fisrtSubmission.getDateTime());
        submission = "Submitted on " + submissionDate + " (" + fisrtSubmission.getCycle() + " cycle "
                + fisrtSubmission.getYear() + ")";
    } else {
        if (!this.getSelectedCycle().isEmpty() && this.getSelectedYear() != 0) {
            if (this.getSelectedCycle().equals("Reporting")) {
                submission = "Submission for " + this.getSelectedCycle() + " cycle " + this.getSelectedYear()
                        + ": &lt;not submited&gt;";
            } else {
                submission = "Submission for " + this.getSelectedCycle() + " cycle " + this.getSelectedYear()
                        + ": &lt;pending&gt;";
            }
        } else {
            submission = "Submission for " + "&lt;Not Defined&gt;" + " cycle " + "&lt;Not Defined&gt;" + " year"
                    + ": &lt;Not Defined&gt;";
        }
    }

    // TODO: Get image from repository
    String centerURL = "";
    // set CRP imgage URL from repo
    // centerURL = this.getBaseUrl() + "/global/images/crps/" + project.getCrp().getAcronym() + ".png";
    // Add center url to LOG
    // LOG.info("Center URL is: " + centerURL);
    // Get The Crp/Center/Platform where the project was created
    GlobalUnitProject globalUnitProject = project.getGlobalUnitProjects().stream()
            .filter(gu -> gu.isActive() && gu.isOrigin()).collect(Collectors.toList()).get(0);
    centerURL = globalUnitProject.getGlobalUnit().getAcronym();
    Boolean isAdministrative = false;
    String type = "Research Project";
    if (projectInfo.getAdministrative() != null) {
        if (projectInfo.getAdministrative() == true) {
            type = "Management Project";
        }
        isAdministrative = projectInfo.getAdministrative();
    } else {
        isAdministrative = false;
    }
    Boolean isNew = this.isProjectNew(projectID);
    Boolean hasGender = false;
    try {
        hasGender = this.hasSpecificities(APConstants.CRP_BUDGET_GENDER);
    } catch (Exception e) {
        LOG.warn("Failed to get " + APConstants.CRP_BUDGET_GENDER
                + " parameter. Parameter will be set as false. Exception: " + e.getMessage());
        hasGender = false;
    }
    Boolean hasTargetUnit = false;
    if (targetUnitList.size() > 0) {
        hasTargetUnit = true;
    }

    Boolean hasActivities = false;
    try {
        hasActivities = this.hasSpecificities(APConstants.CRP_ACTIVITES_MODULE);
    } catch (Exception e) {
        LOG.warn("Failed to get " + APConstants.CRP_ACTIVITES_MODULE
                + " parameter. Parameter will be set as false. Exception: " + e.getMessage());
        hasActivities = false;
    }

    Long phaseID = this.getSelectedPhase().getId();

    model.addRow(new Object[] { title, centerURL, currentDate, submission, this.getSelectedCycle(), isNew,
            isAdministrative, type, projectInfo.getLocationGlobal(), this.isPhaseOne(), hasGender,
            hasTargetUnit, hasW1W2Co, hasActivities, phaseID });
    return model;
}

From source file:org.cgiar.ccafs.marlo.action.BaseAction.java

/**
 * Common logic for setting the Modification Justification
 * //from   w ww. j a  v  a2 s. co  m
 * @param entity
 */
protected void setModificationJustification(MarloAuditableEntity entity) {
    /**
     * Hibernate will not save unchanged entities, so having the localDateTime ensures a unique entry is created each
     * save.
     */
    if (StringUtils.isEmpty(this.justification)) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd,yyyy HH:mm");
        entity.setModificationJustification(
                "No justification provided at : " + LocalDateTime.now().format(formatter));
    } else if (this.justification.equals(entity.getModificationJustification())) {
        /**
         * We have the same justification text as before - which can lead to the entity not being saved if no other fields
         * have been saved. Add a * character to ensure that they are different.
         */
        entity.setModificationJustification(this.justification + "*");
    } else {
        entity.setModificationJustification(this.justification);
    }
}

From source file:sg.ncl.MainController.java

/**
 * @param zonedDateTimeJSON JSON string//from w ww  .jav  a2  s. c  o  m
 * @return a date in the format MMM-d-yyyy
 */
protected String formatZonedDateTime(String zonedDateTimeJSON) throws Exception {
    ZonedDateTime zonedDateTime = getZonedDateTime(zonedDateTimeJSON);
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM-d-yyyy");
    return zonedDateTime.format(format);
}