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:com.romeikat.datamessie.core.base.ui.page.AbstractDocumentsFilterPage.java

private LocalDate parseLocalDate(final StringValue stringValue) {
    final LocalDate today = LocalDate.now();
    // No date corresponds to today
    if (stringValue == null) {
        return today;
    }//from  w  w  w. j  a  va2  s .  co m
    // 0 corresponds to no date
    if (stringValue.toString().equals("0")) {
        return null;
    }
    // Negative numbers correspond to number of days from today in the past
    try {
        final int numberOfDays = Integer.parseInt(stringValue.toString());
        if (numberOfDays < 0) {
            final LocalDate localDate = today.plusDays(numberOfDays);
            return localDate;
        }
    } catch (final NumberFormatException e) {
    }
    // Date pattern
    final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    try {
        final LocalDate localDate = LocalDate.parse(stringValue.toString(), dateFormatter);
        return localDate;
    } catch (final IllegalArgumentException ex) {
    }
    // Ohterwise, use today
    return today;
}

From source file:dk.dma.ais.packet.AisPacketCSVOutputSink.java

private void addTimestampPretty(List fields, AisPacket packet) {
    final long timestamp = packet.getBestTimestamp();
    if (timestamp >= 0)
        fields.add(DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss")
                .format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("UTC"))));
    else//from w  w w  .  java  2  s .c  om
        fields.add("null");
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Create a random dataset name with an optionnal prefix
 * //from   w  ww  .  ja  v  a  2s  . co m
 * @param prefix
 * @return a random dataset name
 */
public static String createRandomDataSetName(@Nullable String prefix) {

    String random = Long.toString(Math.round(Math.random() * 1000));
    String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH'h'mm'm'ss's'S"));

    String dataSet = Strings.nullToEmpty(prefix) + date + '_' + random;

    return dataSet;
}

From source file:org.ops4j.pax.web.resources.jsf.OsgiResource.java

/**
 * <p>//from w  w w.j  av a 2s . c  o m
 * RFC 2616 allows three different date-formats:
 * <ul>
 * <li>RFC 1123</li>
 * <li>RFC 1036</li>
 * <li>ASCI-Time</li>
 * </ul>
 * </p>
 *
 * @param headerValue value transmitted from client
 * @return the parsed DateTime
 * @see <a href=
 * "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3">RFC
 * 2616</a>
 */
private LocalDateTime convertIfModifiedSinceToDate(String headerValue) {

    LocalDateTime time = null;
    try {
        time = LocalDateTime.parse(headerValue, DateTimeFormatter.RFC_1123_DATE_TIME);
    } catch (DateTimeParseException e) {
        logger.trace("could not parse date with RFC-1123. Will try RFC-1036 format...");
    }

    if (time == null) {
        try {
            time = LocalDateTime.parse(headerValue, DateTimeFormatter.ofPattern(PATTERN_RFC_1036));
        } catch (DateTimeParseException e) {
            logger.trace("could not parse date with RFC-1036. Will try ASCITIME format...");
        }
    }

    if (time == null) {
        try {
            time = LocalDateTime.parse(headerValue, DateTimeFormatter.ofPattern(PATTERN_ASCITIME));
        } catch (DateTimeParseException e) {
            logger.trace("could not parse date with ASCITIME.");
        }
    }

    if (time == null) {
        logger.error("Could not parse given if-modified-since header with value '{}'", headerValue);
    }
    return time;
}

From source file:org.wallride.service.PostService.java

/**
 *
 * @param blogLanguage/* ww w  . jav  a  2s  . co m*/
 * @param type
 * @param maxRank
 * @see PostService#getPopularPosts(String, PopularPost.Type)
 */
@CacheEvict(value = WallRideCacheConfiguration.POPULAR_POST_CACHE, key = "'list.type.' + #blogLanguage.language + '.' + #type")
public void updatePopularPosts(BlogLanguage blogLanguage, PopularPost.Type type, int maxRank) {
    logger.info("Start update of the popular posts");

    GoogleAnalytics googleAnalytics = blogLanguage.getBlog().getGoogleAnalytics();
    if (googleAnalytics == null) {
        logger.info("Configuration of Google Analytics can not be found");
        return;
    }

    Analytics analytics = GoogleAnalyticsUtils.buildClient(googleAnalytics);

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        logger.info("GuestServlet is not ready yet");
        return;
    }

    final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);

    Map<Post, Long> posts = new LinkedHashMap<>();

    int startIndex = 1;
    int currentRetry = 0;
    int totalResults = 0;

    do {
        try {
            LocalDate now = LocalDate.now();
            LocalDate startDate;
            switch (type) {
            case DAILY:
                startDate = now.minusDays(1);
                break;
            case WEEKLY:
                startDate = now.minusWeeks(1);
                break;
            case MONTHLY:
                startDate = now.minusMonths(1);
                break;
            default:
                throw new ServiceException();
            }

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Analytics.Data.Ga.Get get = analytics.data().ga()
                    .get(googleAnalytics.getProfileId(), startDate.format(dateTimeFormatter),
                            now.format(dateTimeFormatter), "ga:sessions")
                    .setDimensions(String.format("ga:pagePath", googleAnalytics.getCustomDimensionIndex()))
                    .setSort(String.format("-ga:sessions", googleAnalytics.getCustomDimensionIndex()))
                    .setStartIndex(startIndex).setMaxResults(GoogleAnalyticsUtils.MAX_RESULTS);
            if (blogLanguage.getBlog().isMultiLanguage()) {
                get.setFilters("ga:pagePath=~/" + blogLanguage.getLanguage() + "/");
            }

            logger.info(get.toString());
            final GaData gaData = get.execute();
            if (CollectionUtils.isEmpty(gaData.getRows())) {
                break;
            }

            for (List row : gaData.getRows()) {
                UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) row.get(0)).build();

                MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
                request.setRequestURI(uriComponents.getPath());
                request.setQueryString(uriComponents.getQuery());
                MockHttpServletResponse response = new MockHttpServletResponse();

                BlogLanguageRewriteRule rewriteRule = new BlogLanguageRewriteRule(blogService);
                BlogLanguageRewriteMatch rewriteMatch = (BlogLanguageRewriteMatch) rewriteRule.matches(request,
                        response);
                try {
                    rewriteMatch.execute(request, response);
                } catch (ServletException e) {
                    throw new ServiceException(e);
                } catch (IOException e) {
                    throw new ServiceException(e);
                }

                request.setRequestURI(rewriteMatch.getMatchingUrl());

                HandlerExecutionChain handler;
                try {
                    handler = mapping.getHandler(request);
                } catch (Exception e) {
                    throw new ServiceException(e);
                }

                if (!(handler.getHandler() instanceof HandlerMethod)) {
                    continue;
                }

                HandlerMethod method = (HandlerMethod) handler.getHandler();
                if (!method.getBeanType().equals(ArticleDescribeController.class)
                        && !method.getBeanType().equals(PageDescribeController.class)) {
                    continue;
                }

                // Last path mean code of post
                String code = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size() - 1);
                Post post = postRepository.findOneByCodeAndLanguage(code,
                        rewriteMatch.getBlogLanguage().getLanguage());
                if (post == null) {
                    logger.debug("Post not found [{}]", code);
                    continue;
                }

                if (!posts.containsKey(post)) {
                    posts.put(post, Long.parseLong((String) row.get(1)));
                }
                if (posts.size() >= maxRank) {
                    break;
                }
            }

            if (posts.size() >= maxRank) {
                break;
            }

            startIndex += GoogleAnalyticsUtils.MAX_RESULTS;
            totalResults = gaData.getTotalResults();
        } catch (IOException e) {
            logger.warn("Failed to synchronize with Google Analytics", e);
            if (currentRetry >= GoogleAnalyticsUtils.MAX_RETRY) {
                throw new GoogleAnalyticsException(e);
            }

            currentRetry++;
            logger.info("{} ms to sleep...", GoogleAnalyticsUtils.RETRY_INTERVAL);
            try {
                Thread.sleep(GoogleAnalyticsUtils.RETRY_INTERVAL);
            } catch (InterruptedException ie) {
                throw new GoogleAnalyticsException(e);
            }
            logger.info("Retry for the {} time", currentRetry);
        }
    } while (startIndex <= totalResults);

    popularPostRepository.deleteByType(blogLanguage.getLanguage(), type);

    int rank = 1;
    for (Map.Entry<Post, Long> entry : posts.entrySet()) {
        PopularPost popularPost = new PopularPost();
        popularPost.setLanguage(blogLanguage.getLanguage());
        popularPost.setType(type);
        popularPost.setRank(rank);
        popularPost.setViews(entry.getValue());
        popularPost.setPost(entry.getKey());
        popularPostRepository.saveAndFlush(popularPost);
        rank++;
    }

    logger.info("Complete the update of popular posts");
}

From source file:com.amazonaws.services.kinesis.io.StringDataExtractor.java

/**
 * Builder method to add a date format (based on
 * {@link java.text.SimpleDateFormat} when the dateValueIndex item is a
 * string./*from   w  w w .j a v  a 2 s. c  o  m*/
 * 
 * @param dateFormat
 * @return
 */
@SuppressWarnings("unchecked")
public T withDateFormat(String dateFormat) {
    if (dateFormat != null && !dateFormat.equals("")) {
        this.dateFormat = dateFormat;
        this.dateFormatter = DateTimeFormatter.ofPattern(dateFormat);
    }
    return (T) this;
}

From source file:svc.managers.SMSManagerTest.java

@Test
public void licenseReadMessageGetsGeneratedAgain() throws TwiMLException, ParseException {
    setStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN);
    session.setAttribute("dob", "06/01/1963");
    session.setAttribute("license_number", "F917801962");
    Citation citation = new Citation();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    citation.citation_date = LocalDate.parse("02/03/1990", formatter);
    List<Citation> citations = new ArrayList<Citation>();
    citations.add(citation);//from www . j  a va 2s.  c o  m

    when(citationManagerMock.findCitations((CitationSearchCriteria) notNull())).thenReturn(citations);

    TwimlMessageRequest twimlMessageRequest = new TwimlMessageRequest();
    twimlMessageRequest.setBody("1");
    String message = "1 ticket was found\n1) ticket from: 02/03/1990\nReply with the ticket number you want to view.";
    MessagingResponse twimlResponse = manager.getTwimlResponse(twimlMessageRequest, requestMock, session);
    assertEquals(createTwimlResponse(message).toXml(), twimlResponse.toXml());
}

From source file:de.steilerdev.myVerein.server.controller.admin.UserManagementController.java

/**
 * If a modification on a division needs to be stored durable, this function is invoked by POSTing the parameters to the URI /api/admin/user.
 * @param firstName The first name of the user.
 * @param lastName The last name of the user.
 * @param email The email (unique identifier) of the user.
 * @param birthday The birthday of the user (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param password The initial password of a new user (Only allowed for a new user).
 * @param gender The gender of the user.
 * @param street The street of the user's address.
 * @param streetNumber The street number of the user's address.
 * @param zip The zip code of the user's address.
 * @param city The city of the user's address.
 * @param country The country of the user.
 * @param activeMemberSince The date, when the user became an active member of the club (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param passiveMemberSince The date, when the user became a passive member of the club (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param resignationDate The date, when the user resigned (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param iban The IBAN of the user's bank account.
 * @param bic The BIC of the user's bank account.
 * @param divisions A comma seperated list of divisions, the user is part of.
 * @param userFlag If it is a new user, the user flag is "true", otherwise it is holding the identifier (email) of the user, in case it changed.
 * @param parameters The complete map of all parameters, containing the custom user fields.
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available.
 *//*from w  w  w .  ja v a  2  s.co m*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> saveUser(@RequestParam String firstName, @RequestParam String lastName,
        @RequestParam String email, @RequestParam String birthday, @RequestParam String password,
        @RequestParam(required = false) String gender, @RequestParam String street,
        @RequestParam String streetNumber, @RequestParam String zip, @RequestParam String city,
        @RequestParam String country, @RequestParam String activeMemberSince,
        @RequestParam String passiveMemberSince, @RequestParam String resignationDate,
        @RequestParam String iban, @RequestParam String bic, @RequestParam String divisions,
        @RequestParam String userFlag, @RequestParam Map<String, String> parameters,
        @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Starting to save a user.");
    User userObject;

    logger.debug("[" + currentUser + "] Loading user");

    if (email.isEmpty() || userFlag.isEmpty()) {
        logger.warn("[" + currentUser + "] The email/user flag can not be empty");
        return new ResponseEntity<>("The email can not be empty", HttpStatus.BAD_REQUEST);
    } else if (userFlag.equals("true")) {
        logger.info("[" + currentUser + "] A new user is created using the email " + email);
        if (userRepository.findByEmail(email) == null) {
            userObject = new User();
            if (password.isEmpty()) {
                logger.warn(
                        "[" + currentUser + "] The password of the new user " + email + " can not be empty");
                return new ResponseEntity<>("The password can not be empty", HttpStatus.BAD_REQUEST);
            } else {
                userObject.setPassword(password);
            }
        } else {
            logger.warn("[" + currentUser + "] A user with the given email " + email + " already exists");
            return new ResponseEntity<>("A user with the given email already exists.", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.info("[" + currentUser + "] An existing user " + userFlag + " is modified");
        if ((userObject = userRepository.findByEmail(userFlag)) == null) {
            logger.warn("[{}] Unable to find existing user object", currentUser);
            return new ResponseEntity<>("Unable to retrieve the user", HttpStatus.BAD_REQUEST);
        } else if (!userObject.getEmail().equals(email) && userRepository.findByEmail(email) != null) {
            logger.warn("[{}] The new email {} is already taken", currentUser, email);
            return new ResponseEntity<>("The new email is already taken", HttpStatus.BAD_REQUEST);
        }
    }

    logger.debug("[" + currentUser + "] Checking permissions");

    if (!currentUser.isAllowedToAdministrate(userObject, divisionRepository)) {
        logger.warn("[" + currentUser + "] The user is not allowed to save the user");
        return new ResponseEntity<>("You are not allowed to perform these changes.", HttpStatus.FORBIDDEN);
    }

    logger.debug("[" + currentUser + "] Parsing parameters and updating user");

    if (firstName.isEmpty() || lastName.isEmpty()) {
        logger.warn("[" + currentUser + "] Required parameter missing");
        return new ResponseEntity<>("Required parameter missing", HttpStatus.BAD_REQUEST);
    }
    userObject.setFirstName(firstName);
    userObject.setLastName(lastName);
    userObject.setEmail(email);

    if (!birthday.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing birthday for " + userObject.getEmail());
        try {
            userObject.setBirthday(LocalDate.parse(birthday, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + birthday + ")");
            return new ResponseEntity<>("Wrong date format within birthday field", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing birthday field for " + userObject.getEmail());
        userObject.setBirthday(null);
    }

    if (gender != null && !gender.isEmpty() && !gender.equals("default")) {
        logger.debug("[" + currentUser + "] Parsing gender for " + userObject.getEmail());
        try {
            userObject.setGender(User.Gender.valueOf(gender));
        } catch (IllegalArgumentException e) {
            logger.warn("[" + currentUser + "] Unable to parse gender: " + e.getMessage());
            return new ResponseEntity<>("Unable to parse gender", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing gender field for " + userObject.getEmail());
        userObject.setGender(null);
    }

    userObject.setStreet(street);
    userObject.setStreetNumber(streetNumber);
    userObject.setZipCode(zip);
    userObject.setCity(city);
    userObject.setCountry(country);

    if (!activeMemberSince.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing active member field for " + userObject.getEmail());
        try {
            userObject
                    .setActiveSince(LocalDate.parse(activeMemberSince, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + activeMemberSince + ")");
            return new ResponseEntity<>("Wrong date format within active member field", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing active member field for " + userObject.getEmail());
        userObject.setActiveSince(null);
    }

    if (!passiveMemberSince.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing passive member field for " + userObject.getEmail());
        try {
            userObject.setPassiveSince(
                    LocalDate.parse(passiveMemberSince, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + passiveMemberSince + ")");
            return new ResponseEntity<>("Wrong date format within passive member field",
                    HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing passive member field for " + userObject.getEmail());
        userObject.setPassiveSince(null);
    }

    if (!resignationDate.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing resignation date field for " + userObject.getEmail());
        try {
            userObject.setResignationDate(
                    LocalDate.parse(resignationDate, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + resignationDate + ")");
            return new ResponseEntity<>("Wrong date format within resignation date field",
                    HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing resignation date field for " + userObject.getEmail());
        userObject.setResignationDate(null);
    }

    userObject.setIban(iban);
    userObject.setBic(bic);

    if (!divisions.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing divisions for " + userObject.getEmail());
        String[] divArray = divisions.split(",");
        List<Division> divisionList = new ArrayList<>();
        for (String division : divArray) {
            Division div = divisionRepository.findByName(division);
            if (div == null) {
                logger.warn("[" + currentUser + "] Unrecognized division (" + division + ")");
                return new ResponseEntity<>("Division " + division + " does not exist", HttpStatus.BAD_REQUEST);
            } else {
                divisionList.add(div);
            }
        }
        userObject.replaceDivisions(divisionRepository, eventRepository, divisionList);
    } else {
        logger.debug("[" + currentUser + "] Clearing divisions for " + userObject.getEmail());
        userObject.replaceDivisions(divisionRepository, eventRepository, (List<Division>) null);
    }

    logger.debug("[" + currentUser + "] Parsing and setting custom user fields");
    userObject.setCustomUserField(parameters.keySet().parallelStream()
            .filter(key -> key.startsWith("cuf_") && !parameters.get(key).trim().isEmpty()) //Filtering all custom user fields, which are not empty
            .collect(Collectors.toMap(key -> key.substring(4), key -> parameters.get(key).trim()))); //Creating map of all fields

    logger.debug("[" + currentUser + "] Saving user " + userObject.getEmail());

    try {
        logger.debug("[{}] Saving user {}", currentUser, userObject);
        userRepository.save(userObject);
        logger.info("[" + currentUser + "] Successfully saved user " + userObject.getEmail());
        return new ResponseEntity<>("Successfully saved user", HttpStatus.OK);
    } catch (ConstraintViolationException e) {
        logger.warn("[" + currentUser + "] A database constraint was violated while saving the user: "
                + e.getMessage());
        return new ResponseEntity<>("A database constraint was violated while saving the user.",
                HttpStatus.BAD_REQUEST);
    }
}

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

@Override
public String execute() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {//from   w  ww  .  ja v  a  2s.c  o m
        Resource reportResource;
        if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
            reportResource = resourceManager.createDirectly(
                    this.getClass().getResource("/pentaho/crp/ProjectHighlightsExcel.prpt"),
                    MasterReport.class);
        } else {
            reportResource = resourceManager.createDirectly(
                    this.getClass().getResource("/pentaho/crp/ProjectHighlightsPDF.prpt"), MasterReport.class);
        }

        MasterReport masterReport = (MasterReport) reportResource.getResource();
        String center = this.getLoggedCrp().getAcronym();
        // 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 date = timezone.format(format) + "(GMT" + zone + ")";
        // Set Main_Query
        CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory());
        String masterQueryName = "main";
        TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName);
        TypedTableModel model = this.getMasterTableModel(center, date, String.valueOf(this.getSelectedYear()));
        sdf.addTable(masterQueryName, model);
        masterReport.setDataFactory(cdf);
        // Set i8n for pentaho
        masterReport = this.addi8nParameters(masterReport);
        // Get details band
        ItemBand masteritemBand = masterReport.getItemBand();
        // Create new empty subreport hash map
        HashMap<String, Element> hm = new HashMap<String, Element>();
        // method to get all the subreports in the prpt and store in the HashMap
        this.getAllSubreports(hm, masteritemBand);
        // Uncomment to see which Subreports are detecting the method getAllSubreports
        // System.out.println("Pentaho SubReports: " + hm);
        this.fillSubreport((SubReport) hm.get("project_highlight"), "project_highlight");
        if (this.getSelectedFormat().equals(APConstants.SUMMARY_FORMAT_EXCEL)) {
            ExcelReportUtil.createXLSX(masterReport, os);
            bytesXLSX = os.toByteArray();
        } else {
            PdfReportUtil.createPDF(masterReport, os);
            bytesPDF = os.toByteArray();
        }
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating ProjectHighlights" + this.getSelectedFormat() + ": " + e.getMessage());
        throw e;
    }
    // Calculate time of generation
    long stopTime = System.currentTimeMillis();
    stopTime = stopTime - startTime;
    LOG.info("Downloaded successfully: " + this.getFileName() + ". User: "
            + this.getCurrentUser().getComposedCompleteName() + ". CRP: " + this.getLoggedCrp().getAcronym()
            + ". Time to generate: " + stopTime + "ms.");
    return SUCCESS;
}

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

@Override
public String execute() throws Exception {
    if (projectHighlightID == null
            || projectHighLightManager.getProjectHighligthById(projectHighlightID) == null
            || projectHighLightManager.getProjectHighligthById(projectHighlightID)
                    .getProjectHighlightInfo(this.getSelectedPhase()) == null) {
        LOG.error("Project Highlight " + projectHighlightID + " Not found");
        return NOT_FOUND;
    } else {/*from  www.ja v a  2  s  .com*/
        projectHighlightInfo = projectHighLightManager.getProjectHighligthById(projectHighlightID)
                .getProjectHighlightInfo(this.getSelectedPhase());
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        Resource reportResource = resourceManager.createDirectly(
                this.getClass().getResource("/pentaho/crp/ProjectHighlightPDF.prpt"), MasterReport.class);
        MasterReport masterReport = (MasterReport) reportResource.getResource();
        String center = this.getLoggedCrp().getAcronym();
        // 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 date = timezone.format(format) + "(GMT" + zone + ")";
        // Set Main_Query
        CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory());
        String masterQueryName = "main";
        TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName);
        TypedTableModel model = this.getMasterTableModel(center, date, String.valueOf(this.getSelectedYear()));
        sdf.addTable(masterQueryName, model);
        masterReport.setDataFactory(cdf);
        // Set i8n for pentaho
        masterReport = this.addi8nParameters(masterReport);
        // Get details band
        ItemBand masteritemBand = masterReport.getItemBand();
        // Create new empty subreport hash map
        HashMap<String, Element> hm = new HashMap<String, Element>();
        // method to get all the subreports in the prpt and store in the HashMap
        this.getAllSubreports(hm, masteritemBand);
        // Uncomment to see which Subreports are detecting the method getAllSubreports
        // System.out.println("Pentaho SubReports: " + hm);
        this.fillSubreport((SubReport) hm.get("project_highlight"), "project_highlight");
        PdfReportUtil.createPDF(masterReport, os);
        bytesPDF = os.toByteArray();
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating ProjectHighlights Summary: " + e.getMessage());
        throw e;
    }
    // Calculate time of generation
    long stopTime = System.currentTimeMillis();
    stopTime = stopTime - startTime;
    LOG.info("Downloaded successfully: " + this.getFileName() + ". User: " + this.getDownloadByUser()
            + ". CRP: " + this.getLoggedCrp().getAcronym() + ". Time to generate: " + stopTime + "ms.");
    return SUCCESS;
}