Java Code Examples for java.time.format.DateTimeFormatter

The following examples show how to use java.time.format.DateTimeFormatter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
private void parse(DateTimeFormatter fmt,
                   String zid, String expected, String text,
                   Locale locale, TextStyle style, boolean ci) {
    if (ci) {
        text = text.toUpperCase();
    }
    String ret = fmt.parse(text, TemporalQueries.zone()).getId();
    // TBD: need an excluding list
    // assertEquals(...);
    if (ret.equals(expected) ||
        ret.equals(zid) ||
        ret.equals(ZoneName.toZid(zid)) ||
        ret.equals(expected.replace("UTC", "UCT"))) {
        return;
    }
    System.out.printf("[%-5s %s %s %16s] %24s -> %s(%s)%n",
                      locale.toString(),
                      ci ? "ci" : "  ",
                      style == TextStyle.FULL ? " full" :"short",
                      zid, text, ret, expected);
}
 
Example 2
@Override
public boolean isValid(Object object, ConstraintValidatorContext constraintContext) {
    if (object == null) {
        return true;
    } else if (object instanceof String) {

        for (String pattern : patterns) {
            try {
                DateTimeFormatter.ofPattern(pattern).parse(String.valueOf(object));
                return true;
            } catch (Throwable e) {
                // We do not care about this one, since there might be more than one format
            }
        }
        return false;
    } else {
        return object instanceof Long;
    }
}
 
Example 3
@Override
public String generateInfoText() {
    String dataInfo = "";
    int i;
    dataInfo += "File Name: " + this.getFileName();
    dataInfo += System.getProperty("line.separator") + "Trajectory number = " + String.valueOf(this.trajNum);
    dataInfo += System.getProperty("line.separator") + "Trajectory direction = " + trajDirection;
    dataInfo += System.getProperty("line.separator") + "Vertical motion =" + verticalMotion;
    dataInfo += System.getProperty("line.separator") + "Number of diagnostic output variables = "
            + String.valueOf(varNum);
    dataInfo += System.getProperty("line.separator") + "Variables:";
    for (i = 0; i < varNum; i++) {
        dataInfo += " " + varNames.get(i);
    }
    dataInfo += System.getProperty("line.separator") + System.getProperty("line.separator") + "Trajectories:";
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00");
    for (TrajectoryInfo aTrajInfo : trajInfos) {
        dataInfo += System.getProperty("line.separator") + "  " + format.format(aTrajInfo.startTime)
                + "  " + String.valueOf(aTrajInfo.startLat) + "  " + String.valueOf(aTrajInfo.startLon)
                + "  " + String.valueOf(aTrajInfo.startHeight);
    }

    dataInfo += System.getProperty("line.separator") + super.generateInfoText();

    return dataInfo;
}
 
Example 4
Source Project: armeria   Source File: HttpTimestampSupplier.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
String currentTimestamp() {
    final long currentTimeNanos = nanoTimeSupplier.getAsLong();

    if (nextUpdateNanos - currentTimeNanos > 0) {
        return timestamp;
    }

    final Instant now = instantSupplier.get();

    // The next time we need to update our formatted timestamp is the next time System.nanoTime()
    // equals the following second. We can determine this by adding one second to our current
    // nanoTime minus the nanos part of the current system time (i.e., the number of nanos since the
    // last second).
    nextUpdateNanos = currentTimeNanos - now.getNano() + NANOS_IN_SECOND;

    return timestamp = DateTimeFormatter.RFC_1123_DATE_TIME.format(
            ZonedDateTime.ofInstant(now, ZoneOffset.UTC));
}
 
Example 5
@Test(dataProvider="sample_isoOffsetTime")
public void test_print_isoOffsetTime(
        Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId,
        String expected, Class<?> expectedEx) {
    TemporalAccessor test = buildAccessor(null, null, null, hour, min, sec, nano, offsetId, zoneId);
    if (expectedEx == null) {
        assertEquals(DateTimeFormatter.ISO_OFFSET_TIME.format(test), expected);
    } else {
        try {
            DateTimeFormatter.ISO_OFFSET_TIME.format(test);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example 6
Source Project: jdk8u-jdk   Source File: TCKWeekFields.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="weekFields")
public void test_parse_resolve_localizedWoyDow(DayOfWeek firstDayOfWeek, int minDays) {
    LocalDate date = LocalDate.of(2012, 12, 15);
    WeekFields week = WeekFields.of(firstDayOfWeek, minDays);
    TemporalField dowField = week.dayOfWeek();
    TemporalField woyField = week.weekOfYear();

    for (int i = 1; i <= 60; i++) {
        DateTimeFormatter f = new DateTimeFormatterBuilder()
                .appendValue(YEAR).appendLiteral(':')
                .appendValue(MONTH_OF_YEAR).appendLiteral(':')
                .appendValue(woyField).appendLiteral(':')
                .appendValue(dowField).toFormatter();
        String str = date.getYear() + ":" + date.getMonthValue() + ":" +
                date.get(woyField) + ":" + date.get(dowField);
        LocalDate parsed = LocalDate.parse(str, f);
        assertEquals(parsed, date, " :: " + str + " " + i);

        date = date.plusDays(1);
    }
}
 
Example 7
@Test(dataProvider="sample_isoLocalDateTime")
public void test_print_isoLocalDateTime(
        Integer year, Integer month, Integer day,
        Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId,
        String expected, Class<?> expectedEx) {
    TemporalAccessor test = buildAccessor(year, month, day, hour, min, sec, nano, offsetId, zoneId);
    if (expectedEx == null) {
        assertEquals(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(test), expected);
    } else {
        try {
            DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(test);
            fail();
        } catch (Exception ex) {
            assertTrue(expectedEx.isInstance(ex));
        }
    }
}
 
Example 8
Source Project: android-docs-samples   Source File: AuthUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * function to convert the time from UTC to local TimeZone
 * @param expiryTime    :   expiry time in UTC timezone
 * @return  Date        :   converted datetime to local timezonne
 */
private static Date getConvertedDateTime(String expiryTime) {
    try {
        final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
        DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT);
        LocalDateTime ldt = LocalDateTime.parse(expiryTime, format);
        ZoneId fromZoneId = ZoneId.of(TimeZone.getTimeZone("UTC").getID());
        ZonedDateTime fromZoneDateTime = ldt.atZone(fromZoneId);
        ZoneId currentZoneId = TimeZone.getDefault().toZoneId();
        ZonedDateTime zonedDateTime = fromZoneDateTime.withZoneSameInstant(currentZoneId);
        return new SimpleDateFormat(DATE_FORMAT, Locale.US).parse(format.format(zonedDateTime));
    } catch(Exception ex) {
        ex.printStackTrace();
    }

    return null;
}
 
Example 9
@Test(dataProvider="LocalWeekBasedYearPatterns")
public void test_parse_WeekBasedYear(String pattern, String text, int pos, int expectedPos, LocalDate expectedValue) {
    ParsePosition ppos = new ParsePosition(pos);
    DateTimeFormatterBuilder b = new DateTimeFormatterBuilder().appendPattern(pattern);
    DateTimeFormatter dtf = b.toFormatter(locale);
    TemporalAccessor parsed = dtf.parseUnresolved(text, ppos);
    if (ppos.getErrorIndex() != -1) {
        assertEquals(ppos.getErrorIndex(), expectedPos);
    } else {
        WeekFields weekDef = WeekFields.of(locale);
        assertEquals(ppos.getIndex(), expectedPos, "Incorrect ending parse position");
        assertEquals(parsed.isSupported(weekDef.dayOfWeek()), pattern.indexOf('e') >= 0);
        assertEquals(parsed.isSupported(weekDef.weekOfWeekBasedYear()), pattern.indexOf('w') >= 0);
        assertEquals(parsed.isSupported(weekDef.weekBasedYear()), pattern.indexOf('Y') >= 0);
        // ensure combination resolves into a date
        LocalDate result = LocalDate.parse(text, dtf);
        assertEquals(result, expectedValue, "LocalDate incorrect for " + pattern + ", weekDef: " + weekDef);
    }
}
 
Example 10
Source Project: jdk8u-jdk   Source File: TestReducedParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="ReducedWithChrono")
public void test_reducedWithChronoYear(ChronoLocalDate date) {
    Chronology chrono = date.getChronology();
    DateTimeFormatter df
            = new DateTimeFormatterBuilder().appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1))
            .toFormatter()
            .withChronology(chrono);
    int expected = date.get(YEAR);
    String input = df.format(date);

    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor parsed = df.parseUnresolved(input, pos);
    int actual = parsed.get(YEAR);
    assertEquals(actual, expected,
            String.format("Wrong date parsed, chrono: %s, input: %s",
            chrono, input));

}
 
Example 11
@Test(dataProvider="resolveOneToField")
public void test_resolveOneToField(TemporalField field1, long value1,
                                   TemporalField expectedField1, Long expectedValue1,
                                   TemporalField expectedField2, Long expectedValue2) {
    String str = Long.toString(value1);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field1).toFormatter();

    TemporalAccessor accessor = f.parse(str);
    assertEquals(accessor.query(TemporalQueries.localDate()), null);
    assertEquals(accessor.query(TemporalQueries.localTime()), null);
    if (expectedField1 != null) {
        assertEquals(accessor.isSupported(expectedField1), true);
        assertEquals(accessor.getLong(expectedField1), expectedValue1.longValue());
    }
    if (expectedField2 != null) {
        assertEquals(accessor.isSupported(expectedField2), true);
        assertEquals(accessor.getLong(expectedField2), expectedValue2.longValue());
    }
}
 
Example 12
Source Project: ph-commons   Source File: PDTFormatterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLeadingZero ()
{
  DateTimeFormatter aFormatter = PDTFormatter.getFormatterDate (PDTFormatter.DEFAULT_STYLE,
                                                                Locale.GERMANY,
                                                                EDTFormatterMode.PARSE);
  assertEquals (LocalDate.of (2015, Month.FEBRUARY, 1),
                aFormatter.withResolverStyle (ResolverStyle.LENIENT).parse ("1.2.2015", LocalDate::from));
  assertEquals (LocalDate.of (2015, Month.FEBRUARY, 1), aFormatter.parse ("1.2.2015", LocalDate::from));

  aFormatter = PDTFormatter.getFormatterDateTime (PDTFormatter.DEFAULT_STYLE, Locale.GERMANY, EDTFormatterMode.PARSE);
  if (EJavaVersion.JDK_9.isSupportedVersion ())
  {
    // Assume CLDR - the "," was added!
    assertEquals (LocalDateTime.of (2015, Month.FEBRUARY, 1, 3, 45, 1),
                  aFormatter.parse ("01.02.2015, 03:45:01", LocalDateTime::from));
    assertEquals (LocalDateTime.of (2015, Month.FEBRUARY, 1, 3, 45, 1),
                  aFormatter.parse ("1.2.2015, 3:45:1", LocalDateTime::from));
  }
  else
  {
    assertEquals (LocalDateTime.of (2015, Month.FEBRUARY, 1, 3, 45, 1),
                  aFormatter.parse ("01.02.2015 03:45:01", LocalDateTime::from));
    assertEquals (LocalDateTime.of (2015, Month.FEBRUARY, 1, 3, 45, 1),
                  aFormatter.parse ("1.2.2015 3:45:1", LocalDateTime::from));
  }
}
 
Example 13
@SuppressWarnings("deprecation")
@Test(dataProvider="date")
public void test_date_parse(LocalDate date, FormatStyle dateStyle, int dateStyleOld, Locale locale) {
    DateFormat old = DateFormat.getDateInstance(dateStyleOld, locale);
    Date oldDate = new Date(date.getYear() - 1900, date.getMonthValue() - 1, date.getDayOfMonth());
    String text = old.format(oldDate);

    DateTimeFormatter f = builder.appendLocalized(dateStyle, null).toFormatter(locale);
    TemporalAccessor parsed = f.parse(text, pos);
    assertEquals(pos.getIndex(), text.length());
    assertEquals(pos.getErrorIndex(), -1);
    assertEquals(LocalDate.from(parsed), date);
}
 
Example 14
private DateTimeFormatter getFormatter(Locale locale, TextStyle style, boolean ci) {
    DateTimeFormatterBuilder db = new DateTimeFormatterBuilder();
    if (ci) {
        db = db.parseCaseInsensitive();
    }
    return db.appendZoneText(style)
             .toFormatter(locale)
             .withDecimalStyle(DecimalStyle.of(locale));
}
 
Example 15
@Test(dataProvider="resolveThreeToDate")
public void test_resolveThreeToDate(TemporalField field1, long value1,
                                  TemporalField field2, long value2,
                                  TemporalField field3, long value3,
                                  LocalDate expectedDate) {
    String str = value1 + " " + value2 + " " + value3;
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(field1).appendLiteral(' ')
            .appendValue(field2).appendLiteral(' ')
            .appendValue(field3).toFormatter();

    TemporalAccessor accessor = f.parse(str);
    assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate);
    assertEquals(accessor.query(TemporalQueries.localTime()), null);
}
 
Example 16
@Test
public void test_parse_fromField_SecondOfDay_NanoOfSecond() {
    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .appendValue(SECOND_OF_DAY).appendLiteral('.').appendValue(NANO_OF_SECOND).toFormatter();
    TemporalAccessor acc = fmt.parse("864.123456789");
    assertEquals(acc.isSupported(SECOND_OF_DAY), true);
    assertEquals(acc.isSupported(NANO_OF_SECOND), true);
    assertEquals(acc.isSupported(MICRO_OF_SECOND), true);
    assertEquals(acc.isSupported(MILLI_OF_SECOND), true);
    assertEquals(acc.getLong(SECOND_OF_DAY), 864L);
    assertEquals(acc.getLong(NANO_OF_SECOND), 123456789L);
    assertEquals(acc.getLong(MICRO_OF_SECOND), 123456L);
    assertEquals(acc.getLong(MILLI_OF_SECOND), 123L);
}
 
Example 17
@Test(dataProvider = "instantZones")
public void test_parse_instantZones_supported(DateTimeFormatter formatter, String text, ZonedDateTime expected) {
    TemporalAccessor actual = formatter.parse(text);
    assertEquals(actual.isSupported(INSTANT_SECONDS), true);
    assertEquals(actual.isSupported(EPOCH_DAY), true);
    assertEquals(actual.isSupported(SECOND_OF_DAY), true);
    assertEquals(actual.isSupported(NANO_OF_SECOND), true);
    assertEquals(actual.isSupported(MICRO_OF_SECOND), true);
    assertEquals(actual.isSupported(MILLI_OF_SECOND), true);
}
 
Example 18
@Test
public void test_resolverFields_ignoreCrossCheck() throws Exception {
    DateTimeFormatter base = new DateTimeFormatterBuilder()
            .appendValue(YEAR).appendLiteral('-').appendValue(DAY_OF_YEAR).appendLiteral('-')
            .appendValue(DAY_OF_WEEK).toFormatter();
    DateTimeFormatter f = base.withResolverFields(YEAR, DAY_OF_YEAR);
    try {
        base.parse("2012-321-1", LocalDate::from);  // wrong day-of-week
        fail();
    } catch (DateTimeException ex) {
        // expected, should fail in cross-check of day-of-week
    }
    LocalDate parsed = f.parse("2012-321-1", LocalDate::from);  // ignored wrong day-of-week
    assertEquals(parsed, LocalDate.of(2012, 11, 16));
}
 
Example 19
@Test
public void test_appendValueReduced_subsequent_parse() throws Exception {
    builder.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL).appendValueReduced(YEAR, 2, 2, 2000);
    DateTimeFormatter f = builder.toFormatter();
    assertEquals(f.toString(), "Value(MonthOfYear,1,2,NORMAL)ReducedValue(Year,2,2,2000)");
    ParsePosition ppos = new ParsePosition(0);
    TemporalAccessor parsed = f.parseUnresolved("123", ppos);
    assertNotNull(parsed, "Parse failed: " + ppos.toString());
    assertEquals(parsed.getLong(MONTH_OF_YEAR), 1L);
    assertEquals(parsed.getLong(YEAR), 2023L);
}
 
Example 20
Source Project: james-project   Source File: DecoderUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void decodeDatetimeShouldAllowAppleMailPrependsZeroNotSpace() throws Exception {
    LocalDateTime localDateTime = DecoderUtils.decodeDateTime("09-Apr-2008 15:17:51 +0200");
    assertThat(ZonedDateTime.of(localDateTime, ZoneId.systemDefault())
            .withZoneSameInstant(ZoneId.of("GMT"))
            .format(DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss VV", Locale.US)))
        .isEqualTo("09 Apr 2008 13:17:51 GMT");
}
 
Example 21
Source Project: smarthome   Source File: DateTimeTypeTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void createZonedDate() {
    String inputTimeString;

    // set default time zone
    TimeZone.setDefault(parameterSet.defaultTimeZone);

    // get formatted time string
    if (parameterSet.inputTimeString == null) {
        int durationInNano = (int) TimeUnit.NANOSECONDS.convert(parameterSet.inputTimeMap.get("milliseconds"),
                TimeUnit.MILLISECONDS);

        LocalDateTime dateTime = LocalDateTime.of(parameterSet.inputTimeMap.get("year"),
                parameterSet.inputTimeMap.get("month") + 1, parameterSet.inputTimeMap.get("date"),
                parameterSet.inputTimeMap.get("hourOfDay"), parameterSet.inputTimeMap.get("minute"),
                parameterSet.inputTimeMap.get("second"), durationInNano);
        ZonedDateTime zonedDate = ZonedDateTime.of(dateTime, parameterSet.inputTimeZone.toZoneId()).toInstant()
                .atZone(parameterSet.defaultTimeZone.toZoneId());
        inputTimeString = zonedDate.format((DateTimeFormatter.ofPattern(DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS)));
    } else {
        inputTimeString = parameterSet.inputTimeString;
    }
    DateTimeType dt = new DateTimeType(inputTimeString);
    if (parameterSet.inputTimeZone == null) {
        dt = new DateTimeType(dt.getZonedDateTime().withZoneSameInstant(TimeZone.getDefault().toZoneId()));
    }
    // Test
    assertEquals(parameterSet.expectedResult, dt.toString());
}
 
Example 22
@Test
public void test_toFormat_parseObject_StringParsePosition_invalidPosition_tooSmall() throws Exception {
    // SimpleDateFormat throws StringIndexOutOfBoundException
    DateTimeFormatter dtf = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    ParsePosition pos = new ParsePosition(-1);
    Format test = dtf.toFormat();
    assertNull(test.parseObject("ONE30", pos));
    assertTrue(pos.getErrorIndex() >= 0);
}
 
Example 23
@SuppressWarnings("deprecation")
@Test(dataProvider="time")
public void test_time_parse(LocalTime time, FormatStyle timeStyle, int timeStyleOld, Locale locale) {
    DateFormat old = DateFormat.getTimeInstance(timeStyleOld, locale);
    Date oldDate = new Date(1970, 0, 0, time.getHour(), time.getMinute(), time.getSecond());
    String text = old.format(oldDate);

    DateTimeFormatter f = builder.appendLocalized(null, timeStyle).toFormatter(locale);
    TemporalAccessor parsed = f.parse(text, pos);
    assertEquals(pos.getIndex(), text.length());
    assertEquals(pos.getErrorIndex(), -1);
    assertEquals(LocalTime.from(parsed), time);
}
 
Example 24
Source Project: datacollector   Source File: OffsetQueryUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, String> getOffsetsFromColumns(TableRuntimeContext tableContext, Map<String, Field> fields) throws StageException {
  final Map<String, String> offsets = new HashMap<>();
  for (String offsetColumn : tableContext.getSourceTableContext().getOffsetColumns()) {
    Field field = fields.get(offsetColumn);
    String value;

    if(field.getValue() == null) {
      throw new StageException(JdbcErrors.JDBC_408, offsetColumn);
    }

    if (field.getType().isOneOf(Field.Type.DATE, Field.Type.TIME)) {
      //For DATE/TIME fields store the long in string format and convert back to date when using offset
      //in query
      value = String.valueOf(field.getValueAsDatetime().getTime());
    } else if (field.getType() == Field.Type.DATETIME) {
      //DATETIME is similar to above, but there may also be a nanosecond portion (stored in field attr)
      String nanosAttr = field.getAttribute(JdbcUtil.FIELD_ATTRIBUTE_NANOSECONDS);
      int nanos;
      if (StringUtils.isNotBlank(nanosAttr) && StringUtils.isNumeric(nanosAttr)) {
        nanos = Integer.parseInt(nanosAttr);
      } else {
        nanos = 0;
      }
      value = TableContextUtil.getOffsetValueForTimestampParts(field.getValueAsDatetime().getTime(), nanos);
    } else if(field.getType() == Field.Type.ZONED_DATETIME) {
      value = field.getValueAsZonedDateTime().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    } else {
      value = field.getValueAsString();
    }
    offsets.put(offsetColumn, value);
  }
  return offsets;
}
 
Example 25
Source Project: uyuni   Source File: ResponseMappers.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Map db info into a list with filters views beans with projects
 *
 * @param filtersWithProjects list of filters db with projects
 * @return list with a filter resume response bean
 */
public static List<FilterResponse> mapFilterListingFromDB(
        Map<ContentFilter, List<ContentProject>> filtersWithProjects) {
    return filtersWithProjects.entrySet().stream()
            .map(e -> {
                ContentFilter filter = e.getKey();
                List<ContentProject> projects = e.getValue();

                FilterResponse contentFilterResponse = new FilterResponse();
                contentFilterResponse.setId(filter.getId());
                contentFilterResponse.setName(filter.getName());
                contentFilterResponse.setEntityType(filter.getEntityType().getLabel());
                contentFilterResponse.setMatcher(filter.getCriteria().getMatcher().getLabel());
                contentFilterResponse.setCriteriaKey(filter.getCriteria().getField());
                // If we have a date as a criteria value we need to format it with the current user timezone
                if (filter.getCriteria().getField().equals("issue_date")) {
                    DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
                    OffsetDateTime offsetDateTime = OffsetDateTime.parse(
                            filter.getCriteria().getValue(), timeFormatter
                    );
                    Date criteriaValueDate = Date.from(Instant.from(offsetDateTime));

                    contentFilterResponse.setCriteriaValue(ViewHelper.getInstance().renderDate(criteriaValueDate));
                }
                else {
                    contentFilterResponse.setCriteriaValue(filter.getCriteria().getValue());
                }
                contentFilterResponse.setRule(filter.getRule().getLabel());
                contentFilterResponse.setProjects(
                        projects.stream()
                                .map(p -> new ImmutablePair<String, String>(p.getLabel(), p.getName()))
                                .collect(Collectors.toList())
                );
                return contentFilterResponse;
            })
            .collect(Collectors.toList());
}
 
Example 26
Source Project: jkube   Source File: LogOutputSpec.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private String formatTimestamp(Timestamp timestamp,boolean withColor) {
    if (timeFormatter == null) {
        return "";
    }

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DEFAULT_TIMESTAMP_PATTERN);
    LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestamp.toString()));

    return (withColor ?
            ansi().fgBright(BLACK).a(localDateTime).reset().toString() :
            localDateTime) + " ";
}
 
Example 27
@Test
public void test_adjacent_strict_firstFixedWidth() throws Exception {
    // succeeds because both number elements are fixed width
    DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY, 2).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('9').toFormatter(Locale.UK);
    ParsePosition pp = new ParsePosition(0);
    TemporalAccessor parsed = f.parseUnresolved("12309", pp);
    assertEquals(pp.getErrorIndex(), -1);
    assertEquals(pp.getIndex(), 5);
    assertEquals(parsed.getLong(HOUR_OF_DAY), 12L);
    assertEquals(parsed.getLong(MINUTE_OF_HOUR), 30L);
}
 
Example 28
Source Project: constellation   Source File: DateTimeRangeInputPane.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Build a list of human readable ZoneId strings to display in the ComboBox.
 *
 * @return An ObservableList<String> of human readable ZoneId strings.
 */
private static ObservableList<String> getZoneIds() {
    final DateTimeFormatter zf = DateTimeFormatter.ofPattern("Z");
    final Instant instant = Instant.now();
    final Set<String> zoneSet = ZoneId.getAvailableZoneIds();
    final List<ZoneId> zoned = new ArrayList<>();
    zoneSet.stream().map(ZoneId::of).forEach(zoned::add);

    Collections.sort(zoned, (final ZoneId zi1, final ZoneId zi2) -> {
        final ZonedDateTime z1 = ZonedDateTime.ofInstant(instant, zi1);
        final ZonedDateTime z2 = ZonedDateTime.ofInstant(instant, zi2);
        final int off1 = z1.getOffset().getTotalSeconds();
        final int off2 = z2.getOffset().getTotalSeconds();
        if (off1 != off2) {
            return off1 - off2;
        }

        return zi1.getId().compareTo(zi2.getId());
    });

    final ObservableList<String> zones = FXCollections.observableArrayList();
    zoned.stream().forEach(zi -> {
        final ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, zi);
        zones.add(String.format("%s %s [%s]", zdt.format(zf), zi.getId(), zi.getDisplayName(TextStyle.FULL, Locale.getDefault())));
    });

    return zones;
}
 
Example 29
@Test
public void test_resolverFields_ignoreCrossCheck() throws Exception {
    DateTimeFormatter base = new DateTimeFormatterBuilder()
            .appendValue(YEAR).appendLiteral('-').appendValue(DAY_OF_YEAR).appendLiteral('-')
            .appendValue(DAY_OF_WEEK).toFormatter();
    DateTimeFormatter f = base.withResolverFields(YEAR, DAY_OF_YEAR);
    try {
        base.parse("2012-321-1", LocalDate::from);  // wrong day-of-week
        fail();
    } catch (DateTimeException ex) {
        // expected, should fail in cross-check of day-of-week
    }
    LocalDate parsed = f.parse("2012-321-1", LocalDate::from);  // ignored wrong day-of-week
    assertEquals(parsed, LocalDate.of(2012, 11, 16));
}
 
Example 30
@Test
public void test_parse_fromField_SecondOfDay() {
    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .appendValue(SECOND_OF_DAY).toFormatter();
    TemporalAccessor acc = fmt.parse("864");
    assertEquals(acc.isSupported(SECOND_OF_DAY), true);
    assertEquals(acc.isSupported(NANO_OF_SECOND), true);
    assertEquals(acc.isSupported(MICRO_OF_SECOND), true);
    assertEquals(acc.isSupported(MILLI_OF_SECOND), true);
    assertEquals(acc.getLong(SECOND_OF_DAY), 864L);
    assertEquals(acc.getLong(NANO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MICRO_OF_SECOND), 0L);
    assertEquals(acc.getLong(MILLI_OF_SECOND), 0L);
}