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:org.cgiar.ccafs.marlo.action.summaries.SearchTermsSummaryAction.java

@Override
public String execute() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {/*from w ww.j  a  va  2  s  .  co m*/
        Resource reportResource = resourceManager.createDirectly(
                this.getClass().getResource("/pentaho/crp/SearchTerms.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 currentDate = timezone.format(format) + "(GMT" + zone + ")";
        String parameters = this.getRequest().getParameter("keys");
        if (parameters != null) {
            if (parameters.isEmpty()) {
                // Empty keys
            } else {
                // String parametersNotEspecialChar = parameters.replaceAll("[^a-zA-Z0-9]+", "");
                keys = Arrays.asList(parameters.split(","));
            }
        }
        // Set Main_Query
        CompoundDataFactory cdf = CompoundDataFactory.normalize(masterReport.getDataFactory());
        String masterQueryName = "main";
        TableDataFactory sdf = (TableDataFactory) cdf.getDataFactoryForQuery(masterQueryName);
        TypedTableModel model = this.getMasterTableModel(center, currentDate);
        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("projects_details"), "project");
        this.fillSubreport((SubReport) hm.get("projects_activities"), "activities");
        this.fillSubreport((SubReport) hm.get("projects_deliverables"), "deliverables");
        ExcelReportUtil.createXLSX(masterReport, os);
        bytesXLSX = os.toByteArray();
        os.close();
    } catch (Exception e) {
        LOG.error("Error generating PDF " + 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()
            + ". Cycle: " + this.getSelectedCycle() + ". Time to generate: " + stopTime + "ms.");
    return SUCCESS;
}

From source file:eu.fthevenet.binjr.sources.jrds.adapters.JrdsDataAdapter.java

@Override
public CsvDecoder<Double> getDecoder() {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            .withZone(getTimeZoneId());//from w  w w  .j a  v  a2s.  co m
    return new CsvDecoder<>(getEncoding(), DELIMITER, DoubleTimeSeriesProcessor::new, s -> {
        Double val = Double.parseDouble(s);
        return val.isNaN() ? 0 : val;
    }, s -> ZonedDateTime.parse(s, formatter));
}

From source file:net.tradelib.core.Series.java

public void print(String pattern) {
    print(DateTimeFormatter.ofPattern(pattern));
}

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);//  w ww  .  j  a  v a  2s  .  c om
    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:org.openlmis.fulfillment.service.OrderCsvHelperTest.java

@Test
public void shouldFormatDates() throws IOException {
    List<OrderFileColumn> orderFileColumns = new ArrayList<>();
    orderFileColumns.add(new OrderFileColumn(true, "header.period", PERIOD, true, 1, "MM/yy", ORDER,
            "processingPeriodId", "ProcessingPeriod", "startDate", null));
    orderFileColumns.add(new OrderFileColumn(true, "header.order.date", ORDER_DATE, true, 2, "dd/MM/yy", ORDER,
            "createdDate", null, null, null));

    OrderFileTemplate orderFileTemplate = new OrderFileTemplate("O", false, orderFileColumns);

    String csv = writeCsvFile(order, orderFileTemplate);
    String date = order.getCreatedDate().format(DateTimeFormatter.ofPattern("dd/MM/yy"));

    assertThat(csv, startsWith("01/16," + date));
}

From source file:jp.co.opentone.bsol.linkbinder.service.correspon.impl.CorresponFullTextSearchServiceImpl.java

protected boolean isAcceptableDateString(String keyword) {
    final DateTimeFormatter acceptableFormats[] = { DateTimeFormatter.ofPattern("yyyy-MM-dd"),
            DateTimeFormatter.ofPattern("yyyyMMdd") };

    return Stream.of(StringUtils.split(keyword, ' ')).allMatch(s -> {
        String str = StringUtils.trim(s);
        boolean parsed = false;
        for (DateTimeFormatter f : acceptableFormats) {
            try {
                LocalDate.parse(str, f);
                parsed = true;/*from   www .j a  va2s .c  o m*/
                break;
            } catch (DateTimeParseException ignore) {
            }
        }
        return parsed;
    });
}

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

private List<Booking> expectOptimisticPersisterGetAllItemsToReturnAllBookings(boolean addNonBookingItems) {
    // (the version number must be set here but its value is irrelevant)
    List<ImmutablePair<String, List<Attribute>>> expectedDateAttributeListPairs = new ArrayList<>();
    List<Attribute> attributes = new ArrayList<>();
    // Add bookings that are not all on a single day.
    List<Booking> bookingsForMoreThanOneDay = new ArrayList<>();
    bookingsForMoreThanOneDay.add(existingSingleBooking);
    Booking bookingForAnotherDay = new Booking(existingSingleBooking);
    bookingForAnotherDay/*  w  ww.  j a v a  2s . c  om*/
            .setDate(LocalDate.parse(existingSingleBooking.getDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                    .minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    bookingsForMoreThanOneDay.add(bookingForAnotherDay);

    bookingsForMoreThanOneDay.stream().forEach(booking -> {
        attributes.add(new Attribute(
                booking.getCourt().toString() + "-" + booking.getCourtSpan().toString() + "-"
                        + booking.getSlot().toString() + "-" + booking.getSlotSpan().toString(),
                booking.getName()));
        expectedDateAttributeListPairs.add(new ImmutablePair<>(booking.getDate(), attributes));
    });

    if (addNonBookingItems) {
        // OptimisticPersister also has items for booking rules and lifecycle
        // state. The booking manager should ignore these items when returning the
        // bookings.
        List<Attribute> nonBookingAttributes = new ArrayList<>();
        nonBookingAttributes.add(new Attribute("Some attribute name", "Some arbitrary value"));
        expectedDateAttributeListPairs.add(new ImmutablePair<>("LifecycleState", nonBookingAttributes));
        expectedDateAttributeListPairs
                .add(new ImmutablePair<>("BookingRulesAndExclusions", nonBookingAttributes));
    }

    // Set up mock optimistic persister to return these bookings - or to throw
    mockery.checking(new Expectations() {
        {
            oneOf(mockOptimisticPersister).getAllItems();
            will(returnValue(expectedDateAttributeListPairs));
        }
    });
    bookingManager.setOptimisticPersister(mockOptimisticPersister);

    return bookingsForMoreThanOneDay;
}

From source file:net.tourbook.photo.Photo.java

public static void setupTimeZone() {

    _dtParser = DateTimeFormatter//
            .ofPattern("yyyy:MM:dd HH:mm:ss") //$NON-NLS-1$
            .withZone(TimeTools.getDefaultTimeZone());
}

From source file:com.ottogroup.bi.streaming.operator.json.JsonProcessingUtils.java

/**
 * Extracts from a {@link JSONObject} the value of the field referenced by the provided path. The received content is treated as
 * {@link String} value which must be parsed into a {@link ZonedDateTime} representation. If the value is a plain {@link ZonedDateTime} value 
 * it is returned right away. {@link ZonedDateTime} values contained inside {@link String} instances are parsed out by {@link SimpleDateFormat#parse(String)}. 
 * If parsing fails or the type is not of the referenced ones the method throws a {@link ParseException}
 * @param jsonObject/*  ww  w .j a  va 2  s  .  co  m*/
 *          The {@link JSONObject} to read the value from (null is not permitted as input)
 * @param fieldPath
 *          Path inside the {@link JSONObject} pointing towards the value of interest (null is not permitted as input)
 * @param formatString
 *          The expected format (eg. YYYY-mm-DD)
 * @return
 *          Value found at the end of the provided path. An empty path simply returns the input
 * @throws JSONException
 *          Thrown in case extracting values from the {@link JSONObject} fails for any reason
 * @throws IllegalArgumentException
 *          Thrown in case a provided parameter does not comply with the restrictions
 * @throws NoSuchElementException
 *          Thrown in case an element referenced inside the path does not exist at the expected location inside the {@link JSONObject}
 * @throws ParseException
 *          Thrown in case parsing out an {@link ZonedDateTime} from the retrieved field value fails for any format related reason 
 */
public ZonedDateTime getZonedDateTimeFieldValue(final JSONObject jsonObject, final String[] fieldPath,
        final String formatString)
        throws JSONException, IllegalArgumentException, NoSuchElementException, ParseException {

    Object value = getFieldValue(jsonObject, fieldPath);
    if (value instanceof ZonedDateTime)
        return (ZonedDateTime) value;
    else if (value instanceof String)
        return (StringUtils.isNotBlank(formatString)
                ? ZonedDateTime.parse((String) value, DateTimeFormatter.ofPattern(formatString))
                : ZonedDateTime.parse((String) value));

    throw new ParseException("Types of " + (value != null ? value.getClass().getName() : "null")
            + " cannot be parsed into a valid zoned date & time representation", 0);
}

From source file:org.hawkular.alerts.actions.elasticsearch.ElasticsearchPlugin.java

private void transformTimestamp(String pattern, Object input) {
    if (input == null) {
        return;//from  w  ww.j a  va  2  s  .c om
    }
    if (input instanceof Map.Entry) {
        Map.Entry<String, Object> entry = (Map.Entry<String, Object>) input;
        if (entry.getValue() instanceof Map || entry.getValue() instanceof List) {
            transformTimestamp(pattern, entry.getValue());
        } else {
            if (TIMESTAMP_FIELDS.contains(entry.getKey())) {
                try {
                    Long timestamp = (Long) entry.getValue();
                    entry.setValue(DateTimeFormatter.ofPattern(pattern)
                            .format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), UTC)));
                } catch (Exception e) {
                    log.warnf("Cannot parse %s timestamp", entry.getKey());
                }
            }
        }
    } else if (input instanceof Map) {
        Map<String, Object> map = (Map<String, Object>) input;
        map.entrySet().stream().forEach(e -> transformTimestamp(pattern, e));
    } else if (input instanceof List) {
        List list = (List) input;
        list.stream().forEach(e -> transformTimestamp(pattern, e));
    }
}