Example usage for java.time ZonedDateTime now

List of usage examples for java.time ZonedDateTime now

Introduction

In this page you can find the example usage for java.time ZonedDateTime now.

Prototype

public static ZonedDateTime now() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:sg.ncl.MainController.java

@RequestMapping(value = "/signup2", method = RequestMethod.POST)
public String validateDetails(@Valid @ModelAttribute(SIGNUP_MERGED_FORM) SignUpMergedForm signUpMergedForm,
        BindingResult bindingResult, final RedirectAttributes redirectAttributes)
        throws WebServiceRuntimeException {

    if (bindingResult.hasErrors() || !signUpMergedForm.getIsValid()) {
        log.warn("Register form has errors {}", signUpMergedForm.toString());
        return SIGNUP_PAGE;
    }//from w  ww . j a  va2  s. co m

    if (!signUpMergedForm.getHasAcceptTeamOwnerPolicy()) {
        signUpMergedForm.setErrorTeamOwnerPolicy("Please accept the team owner policy");
        log.warn("Policy not accepted");
        return SIGNUP_PAGE;
    }

    // get form fields
    // craft the registration json
    JSONObject mainObject = new JSONObject();
    JSONObject credentialsFields = new JSONObject();
    credentialsFields.put("username", signUpMergedForm.getEmail().trim());
    credentialsFields.put(PSWD, signUpMergedForm.getPassword());

    // create the user JSON
    JSONObject userFields = new JSONObject();
    JSONObject userDetails = new JSONObject();
    JSONObject addressDetails = new JSONObject();

    userDetails.put(FNAME, signUpMergedForm.getFirstName().trim());
    userDetails.put(LNAME, signUpMergedForm.getLastName().trim());
    userDetails.put(JOB_TITLE, signUpMergedForm.getJobTitle().trim());
    userDetails.put(EMAIL, signUpMergedForm.getEmail().trim());
    userDetails.put(PHONE, signUpMergedForm.getPhone().trim());
    userDetails.put(INSTITUTION, signUpMergedForm.getInstitution().trim());
    userDetails.put(INSTITUTION_ABBREVIATION, signUpMergedForm.getInstitutionAbbreviation().trim());
    userDetails.put(INSTITUTION_WEB, signUpMergedForm.getWebsite().trim());
    userDetails.put(ADDRESS, addressDetails);

    addressDetails.put(ADDRESS1, signUpMergedForm.getAddress1().trim());
    addressDetails.put(ADDRESS2, signUpMergedForm.getAddress2().trim());
    addressDetails.put(COUNTRY, signUpMergedForm.getCountry().trim());
    addressDetails.put(REGION, signUpMergedForm.getProvince().trim());
    addressDetails.put(CITY, signUpMergedForm.getCity().trim());
    addressDetails.put(ZIP_CODE, signUpMergedForm.getPostalCode().trim());

    userFields.put(USER_DETAILS, userDetails);
    userFields.put(APPLICATION_DATE, ZonedDateTime.now());

    JSONObject teamFields = new JSONObject();

    // add all to main json
    mainObject.put("credentials", credentialsFields);
    mainObject.put("user", userFields);
    mainObject.put("team", teamFields);

    // check if user chose create new team or join existing team by checking team name
    String createNewTeamName = signUpMergedForm.getTeamName().trim();
    String joinNewTeamName = signUpMergedForm.getJoinTeamName().trim();

    if (!createNewTeamName.isEmpty()) {
        return checkNewTeamForm(signUpMergedForm, redirectAttributes, mainObject, teamFields,
                createNewTeamName);
    } else if (!joinNewTeamName.isEmpty()) {
        return checkJoinTeamForm(signUpMergedForm, redirectAttributes, mainObject, teamFields, joinNewTeamName);
    } else {
        log.warn("Signup unreachable statement");
        // logic error not suppose to reach here
        // possible if user fill up create new team but without the team name
        redirectAttributes.addFlashAttribute("signupError",
                "There is a problem when submitting your form. Please re-enter and submit the details again.");
        redirectAttributes.addFlashAttribute(SIGNUP_MERGED_FORM, signUpMergedForm);
        return REDIRECT_SIGNUP;
    }
}

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  .j a  v  a  2  s.c  o  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:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

@Override
public AssignmentConstants.Status getAssignmentCannonicalStatus(String assignmentId)
        throws IdUnusedException, PermissionException {
    Assignment assignment = getAssignment(assignmentId);
    ZonedDateTime currentTime = ZonedDateTime.now();

    // TODO these status's should be an enum and translation should occur in tool
    if (assignment.getDraft()) {
        return AssignmentConstants.Status.DRAFT;
    } else if (assignment.getOpenDate().isAfter(currentTime.toInstant())) {
        return AssignmentConstants.Status.NOT_OPEN;
    } else if (assignment.getDueDate().isAfter(currentTime.toInstant())) {
        return AssignmentConstants.Status.OPEN;
    } else if ((assignment.getCloseDate() != null)
            && (assignment.getCloseDate().isBefore(currentTime.toInstant()))) {
        return AssignmentConstants.Status.CLOSED;
    } else {/* w  ww.  j  a  v a2s  .  com*/
        return AssignmentConstants.Status.DUE;
    }
}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

@Override
public String getDeepLinkWithPermissions(String context, String assignmentId, boolean allowReadAssignment,
        boolean allowAddAssignment, boolean allowSubmitAssignment) throws Exception {
    Assignment a = getAssignment(assignmentId);

    String assignmentContext = a.getContext(); // assignment context
    if (allowReadAssignment && a.getOpenDate().isBefore(ZonedDateTime.now().toInstant())) {
        // this checks if we want to display an assignment link
        try {//from   w  w  w  . j  ava 2  s. com
            Site site = siteService.getSite(assignmentContext);
            // site id
            ToolConfiguration fromTool = site.getToolForCommonId("sakai.assignment.grades");
            // Three different urls to be rendered depending on the
            // user's permission
            if (allowAddAssignment) {
                return serverConfigurationService.getPortalUrl()
                        + "/directtool/" + fromTool.getId() + "?assignmentId=" + assignmentId
                        + "&assignmentReference=" + AssignmentReferenceReckoner.reckoner().context(context)
                                .id(assignmentId).reckon().getReference()
                        + "&panel=Main&sakai_action=doView_assignment";
            } else if (allowSubmitAssignment) {
                return serverConfigurationService.getPortalUrl()
                        + "/directtool/" + fromTool.getId() + "?assignmentId=" + assignmentId
                        + "&assignmentReference=" + AssignmentReferenceReckoner.reckoner().context(context)
                                .id(assignmentId).reckon().getReference()
                        + "&panel=Main&sakai_action=doView_submission";
            } else {
                // user can read the assignment, but not submit, so
                // render the appropriate url
                return serverConfigurationService.getPortalUrl()
                        + "/directtool/" + fromTool.getId() + "?assignmentId=" + assignmentId
                        + "&assignmentReference=" + AssignmentReferenceReckoner.reckoner().context(context)
                                .id(assignmentId).reckon().getReference()
                        + "&panel=Main&sakai_action=doView_assignment_as_student";
            }
        } catch (IdUnusedException e) {
            // No site found
            throw new IdUnusedException("No site found while creating assignment url");
        }
    }
    return "";
}

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;
    }//from w w w . j a va  2s .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.j  a  v a2  s .  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) {//  w  w  w .  j  a va  2  s.  c om
    // 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;
}