类java.time.format.DateTimeParseException源码实例Demo

下面列出了怎么用java.time.format.DateTimeParseException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: bearchoke   文件: ZonedDateTimeReadConverter.java
@Override
public ZonedDateTime convert(String value) {
    ZonedDateTime result = null;

    try {
        if (log.isTraceEnabled()) {
            log.trace("Converting String {} to ZonedDateTime", value);
        }

        result = ZonedDateTime.parse(value);
    } catch (DateTimeParseException e) {
        log.error("{} could not be converted to java.time.ZonedDateTime", value);
    }

    return result;
}
 
源代码2 项目: pt2matsim   文件: HafasConverter.java
public static void run(String hafasFolder, TransitSchedule schedule, CoordinateTransformation transformation, Vehicles vehicles, String chosenDateString) throws IOException {
	if(!hafasFolder.endsWith("/")) hafasFolder += "/";

	// 3a. Get start_fahrplan date
	LocalDate fahrplanStartDate = ECKDATENReader.getFahrPlanStart(hafasFolder);
	LocalDate fahrplanEndDate = ECKDATENReader.getFahrPlanEnd(hafasFolder);
	try {
		LocalDate chosenDate = ECKDATENReader.getDate(chosenDateString);

		if (chosenDate.isBefore(fahrplanStartDate) || chosenDate.isAfter(fahrplanEndDate)) {
			throw new IllegalArgumentException(
					String.format("Chosen date %s is outside fahrplan period: (%s, %s)", chosenDate, fahrplanStartDate, fahrplanEndDate)
			);
		}

		int dayNr = (int) ChronoUnit.DAYS.between(fahrplanStartDate, chosenDate);
		run(hafasFolder, schedule, transformation, vehicles, dayNr);

	} catch (DateTimeParseException ex) {
		throw new IllegalArgumentException(
				"Format of chosen date (should be dd.MM.yyyy) is invalid: " + chosenDateString
		);
	}
}
 
@Test(dataProvider="resolveClockHourOfAmPm")
public void test_resolveClockHourOfAmPm(ResolverStyle style, long value, Integer expectedValue) {
    String str = Long.toString(value);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_AMPM).toFormatter();

    if (expectedValue != null) {
        TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
        assertEquals(accessor.query(TemporalQueries.localDate()), null);
        assertEquals(accessor.query(TemporalQueries.localTime()), null);
        assertEquals(accessor.isSupported(CLOCK_HOUR_OF_AMPM), false);
        assertEquals(accessor.isSupported(HOUR_OF_AMPM), true);
        assertEquals(accessor.getLong(HOUR_OF_AMPM), expectedValue.longValue());
    } else {
        try {
            f.withResolverStyle(style).parse(str);
            fail();
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
源代码4 项目: hmftools   文件: LimsFactory.java
@NotNull
@VisibleForTesting
static Map<String, LocalDate> readPreLimsArrivalDateTsv(@NotNull String preLimsArrivalDatesTsv) throws IOException {
    Map<String, LocalDate> arrivalDatesPerSampleId = Maps.newHashMap();
    List<String> lines = Files.lines(Paths.get(preLimsArrivalDatesTsv)).collect(Collectors.toList());
    for (String line : lines) {
        String[] parts = line.split(FIELD_SEPARATOR);

        if (parts.length == 2) {
            String sampleId = parts[0].trim();
            String arrivalDateString = parts[1].trim();
            LocalDate arrivalDate;
            try {
                arrivalDate = LocalDate.parse(arrivalDateString, LimsConstants.DATE_FORMATTER);
            } catch (DateTimeParseException exc) {
                LOGGER.warn("Could not parse date in pre-HMF arrival date csv: {}", arrivalDateString);
                arrivalDate = null;
            }
            arrivalDatesPerSampleId.put(sampleId, arrivalDate);
        } else {
            LOGGER.warn("Invalid line in pre-HMF arrival date csv: {}", line);
        }
    }
    return arrivalDatesPerSampleId;
}
 
源代码5 项目: jdk8u-jdk   文件: TCKDateTimeParseResolver.java
@Test(dataProvider="resolveClockHourOfDay")
public void test_resolveClockHourOfDay(ResolverStyle style, long value, Integer expectedHour, int expectedDays) {
    String str = Long.toString(value);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_DAY).toFormatter();

    if (expectedHour != null) {
        TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
        assertEquals(accessor.query(TemporalQueries.localDate()), null);
        assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.of(expectedHour, 0));
        assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays));
    } else {
        try {
            f.withResolverStyle(style).parse(str);
            fail();
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
源代码6 项目: TencentKona-8   文件: TCKIsoFields.java
@Test(dataProvider = "parseLenientWeek")
public void test_parse_parseLenientWeek_SMART(String str, LocalDate expected, boolean smart) {
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral(':')
            .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral(':')
            .appendValue(DAY_OF_WEEK)
            .toFormatter().withResolverStyle(ResolverStyle.SMART);
    if (smart) {
        LocalDate parsed = LocalDate.parse(str, f);
        assertEquals(parsed, expected);
    } else {
        try {
            LocalDate.parse(str, f);
            fail("Should have failed");
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
源代码7 项目: TencentKona-8   文件: TCKDateTimeParseResolver.java
@Test(dataProvider="resolveFourToTime")
public void test_resolveThreeToTime(ResolverStyle style,
                                   long hour, long min, long sec, long nano, LocalTime expectedTime, Period excessPeriod) {
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .parseDefaulting(HOUR_OF_DAY, hour)
            .parseDefaulting(MINUTE_OF_HOUR, min)
            .parseDefaulting(SECOND_OF_MINUTE, sec).toFormatter();

    ResolverStyle[] styles = (style != null ? new ResolverStyle[] {style} : ResolverStyle.values());
    for (ResolverStyle s : styles) {
        if (expectedTime != null) {
            TemporalAccessor accessor = f.withResolverStyle(s).parse("");
            assertEquals(accessor.query(TemporalQueries.localDate()), null, "ResolverStyle: " + s);
            assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime.minusNanos(nano), "ResolverStyle: " + s);
            assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), excessPeriod, "ResolverStyle: " + s);
        } else {
            try {
                f.withResolverStyle(style).parse("");
                fail();
            } catch (DateTimeParseException ex) {
                // expected
            }
        }
    }
}
 
源代码8 项目: dragonwell8_jdk   文件: JapanEraNameCompatTest.java
@Test
public void testFormatParseEraName() {
    LocalDate date = LocalDate.of(2019, 5, 1);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd GGGG");
    formatter = formatter.withChronology(JapaneseChronology.INSTANCE);

    int num = 0;
    for (Locale locale : Calendar.getAvailableLocales()) {
        formatter = formatter.withLocale(locale);
        try {
            LocalDate.parse(date.format(formatter), formatter);
        } catch (DateTimeParseException e) {
            // If an array is defined for Japanese eras in java.time resource,
            // but an era entry is missing, format fallback to English name
            // while parse throw DateTimeParseException.
            num++;
            System.out.println("Missing java.time resource data for locale: " + locale);
        }
    }
    if (num > 0) {
        throw new RuntimeException("Missing java.time data for " + num + " locales");
    }
}
 
源代码9 项目: openjdk-jdk9   文件: TCKDateTimeParseResolver.java
@Test(dataProvider="resolveClockHourOfDay")
public void test_resolveClockHourOfDay(ResolverStyle style, long value, Integer expectedHour, int expectedDays) {
    String str = Long.toString(value);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(CLOCK_HOUR_OF_DAY).toFormatter();

    if (expectedHour != null) {
        TemporalAccessor accessor = f.withResolverStyle(style).parse(str);
        assertEquals(accessor.query(TemporalQueries.localDate()), null);
        assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.of(expectedHour, 0));
        assertEquals(accessor.query(DateTimeFormatter.parsedExcessDays()), Period.ofDays(expectedDays));
    } else {
        try {
            f.withResolverStyle(style).parse(str);
            fail();
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
源代码10 项目: java-ilp-core   文件: OerGeneralizedTimeCodec.java
@Override
public OerGeneralizedTime read(CodecContext context, InputStream inputStream) throws IOException {
  Objects.requireNonNull(context);
  Objects.requireNonNull(inputStream);

  final String timeString = context.read(OerIA5String.class, inputStream).getValue();

  if (timeString.length() != 19 || !timeString.endsWith("Z")) {
    throw new IllegalArgumentException(
        "Interledger GeneralizedTime only supports values in the format 'YYYYMMDDTHHMMSS.fffZ',"
            + " value " + timeString + " is invalid.");
  }

  try {
    final Instant value = Instant.from(generalizedTimeFormatter.parse(timeString));
    return new OerGeneralizedTime(value);
  } catch (DateTimeParseException dtp) {
    throw new IllegalArgumentException(
        "Interledger GeneralizedTime only supports values in the format 'YYYYMMDDTHHMMSS.fffZ', "
            + "value " + timeString + " is invalid.",
        dtp);
  }
}
 
源代码11 项目: dragonwell8_jdk   文件: TCKIsoFields.java
@Test(dataProvider = "parseLenientQuarter")
public void test_parse_parseLenientQuarter_SMART(String str, LocalDate expected, boolean smart) {
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(YEAR).appendLiteral(':')
            .appendValue(IsoFields.QUARTER_OF_YEAR).appendLiteral(':')
            .appendValue(IsoFields.DAY_OF_QUARTER)
            .toFormatter().withResolverStyle(ResolverStyle.SMART);
    if (smart) {
        LocalDate parsed = LocalDate.parse(str, f);
        assertEquals(parsed, expected);
    } else {
        try {
            LocalDate.parse(str, f);
            fail("Should have failed");
        } catch (DateTimeParseException ex) {
            // expected
        }
    }
}
 
源代码12 项目: rya   文件: TemporalIntervalRelationFunction.java
@Override
public Value evaluate(final ValueFactory valueFactory, final Value... args) throws ValueExprEvaluationException {
    if (args.length != 2) {
        throw new ValueExprEvaluationException(getURI() + " requires exactly 2 arguments, got " + args.length);
    }

    final String[] strInterval = args[1].stringValue().split("/");
    if (strInterval.length != 2) {
        throw new ValueExprEvaluationException(getURI() + " requires the second argument: " + args[1] + " to be 2 dates seperated by a \'/\'");
    }
    try {
        final ZonedDateTime date1 = ZonedDateTime.parse(args[0].stringValue());
        final ZonedDateTime[] interval = new ZonedDateTime[] {
                ZonedDateTime.parse(strInterval[0]),
                ZonedDateTime.parse(strInterval[1])
        };
        final boolean result = relation(date1, interval);

        return valueFactory.createLiteral(result);
    } catch (final DateTimeParseException e) {
        throw new ValueExprEvaluationException("Date/Times provided must be of the ISO-8601 format. Example: 2007-04-05T14:30Z");
    }
}
 
private void expectFailure(String json) throws Throwable {
    try {
        READER.readValue(aposToQuotes(json));
        fail("expected DateTimeParseException");
    } catch (JsonProcessingException e) {
        if (e.getCause() == null) {
            throw e;
        }
        if (!(e.getCause() instanceof DateTimeParseException)) {
            throw e.getCause();
        }
    }
}
 
源代码14 项目: openjdk-jdk8u-backup   文件: TCKPeriod.java
@Test(dataProvider="parseSuccess")
public void factory_parse_minus(String text, Period expected) {
    Period p = null;
    try {
        p = Period.parse("-" + text);
    } catch (DateTimeParseException ex) {
        assertEquals(expected.getYears() == Integer.MIN_VALUE ||
                expected.getMonths() == Integer.MIN_VALUE ||
                expected.getDays() == Integer.MIN_VALUE, true);
        return;
    }
    // not inside try/catch or it breaks test
    assertEquals(p, expected.negated());
}
 
源代码15 项目: gcp-ingestion   文件: Time.java
/**
 * Attempts to parse a string in format '2011-12-03T10:15:30Z', returning null in case of error.
 */
public static Instant parseAsInstantOrNull(String timestamp) {
  try {
    return Instant.from(DateTimeFormatter.ISO_INSTANT.parse(timestamp));
  } catch (DateTimeParseException | NullPointerException ignore) {
    return null;
  }
}
 
源代码16 项目: openvsx   文件: AdminAPI.java
@GetMapping(
    path = "/admin/log",
    produces = MediaType.TEXT_PLAIN_VALUE
)
public String getLog(@RequestParam("token") String tokenValue,
                     @RequestParam(name = "period", required = false) String periodString) {
    var token = users.useAccessToken(tokenValue);
    if (token == null) {
        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Invalid access token.");
    }
    if (!UserData.ROLE_ADMIN.equals(token.getUser().getRole())) {
        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Administration role is required.");
    }

    Streamable<PersistedLog> logs;
    if (Strings.isNullOrEmpty(periodString)) {
        logs = repositories.findAllPersistedLogs();
    } else {
        try {
            var period = Period.parse(periodString);
            var now = TimeUtil.getCurrentUTC();
            logs = repositories.findPersistedLogsAfter(now.minus(period));
        } catch (DateTimeParseException exc) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid period");
        }
    }
    return logs.stream()
            .map(this::toString)
            .collect(Collectors.joining("\n")) + "\n";
}
 
源代码17 项目: Recaf   文件: SelfUpdater.java
/**
 * Fetch the {@link #latestVersion latest version}
 * and {@link #latestArtifact latest artifact url}.
 *
 * @throws IOException
 * 		When opening a connection to the API url fails.
 */
private static void fetchLatestInfo() throws IOException {
	URL updateURL = new URL(API);
	String content = IOUtils.toString(updateURL.openStream(), StandardCharsets.UTF_8);
	JsonObject updateJson = Json.parse(content).asObject();
	// compare versions
	latestVersion = updateJson.getString("tag_name", "2.0.0");
	latestPatchnotes = updateJson.getString("body", "#Error\nCould not fetch update notes.");
	if (isOutdated()) {
		Log.info(LangUtil.translate("update.outdated"));
		JsonArray assets = updateJson.get("assets").asArray();
		for(JsonValue assetValue : assets.values()) {
			JsonObject assetObj = assetValue.asObject();
			String file = assetObj.getString("name", "invalid");
			// Skip non-jars
			if (!file.endsWith(".jar")) {
				continue;
			}
			// Find the largest jar
			int size = assetObj.getInt("size", 0);
			if (size > latestArtifactSize) {
				latestArtifactSize = size;
				String fileURL = assetObj.getString("browser_download_url", null);
				if (fileURL != null)
					latestArtifact = fileURL;
			}
		}
		try {
			String date = updateJson.getString("published_at", null);
			if (date != null)
				latestVersionDate = Instant.parse(date);
		} catch(DateTimeParseException ex) {
			Log.warn("Failed to parse timestamp for latest release");
		}
		if (latestArtifact == null)
			Log.warn(LangUtil.translate("update.fail.nodownload"));
	}
}
 
源代码18 项目: ditto   文件: TimeoutValueValidator.java
@SuppressWarnings("squid:S2201")
@Override
protected void validateValue(final HeaderDefinition definition, final CharSequence value) {
    try {
        Duration.ofSeconds(parseLong(value));
    } catch (final DateTimeParseException e) {
        throw DittoHeaderInvalidException.newInvalidTypeBuilder(definition, value, "timeout").build();
    }
}
 
源代码19 项目: jdk8u-jdk   文件: TCKDateTimeParseResolver.java
@Test(expectedExceptions = DateTimeParseException.class)
public void test_fieldResolvesToChronoLocalDateTime_overrideChrono_wrongChrono() {
    ChronoLocalDateTime<?> cldt = ThaiBuddhistChronology.INSTANCE.dateNow().atTime(LocalTime.NOON);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(cldt)).toFormatter();
    f = f.withChronology(MinguoChronology.INSTANCE);
    f.parse("1234567890");
}
 
源代码20 项目: TAcharting   文件: SqlLiteConnector.java
/**
 *
 * @param rset the result set
 * @return a BarSeries object
 * @throws SQLException d
 */
private TaBarSeries transformResultSet(ResultSet rset, GeneralTimePeriod timeFormatType) throws SQLException {
    List<Bar> ticks = new ArrayList<>();

    String name=null;
    Currency currency=null;

    while (rset.next()){
        try {
            Instant i = Instant.ofEpochSecond(Long.parseLong(rset.getString("Date")));
            ZonedDateTime time = ZonedDateTime.ofInstant(i, ZoneId.systemDefault());
            name = rset.getString("Symbol");
            currency = Currency.getInstance(rset.getString("Currency"));
            BaseBar line = new BaseBar(Duration.ZERO, time,
                CalculationUtils.integerToCurrencyValue(rset.getInt("Open"), currency),
                CalculationUtils.integerToCurrencyValue(rset.getInt("High"), currency),
                CalculationUtils.integerToCurrencyValue(rset.getInt("Low"), currency),
                CalculationUtils.integerToCurrencyValue(rset.getInt("Close"), currency),
                Parameter.numFunction.apply(rset.getInt("Volume")),
                Parameter.numFunction.apply(0) ); //TODO amount is 0
            ticks.add(line);
        } catch (DateTimeParseException dte){
            dte.printStackTrace();
            log.error("Could not be transformed: {} {}",
                    name==null?"unnamed":name,
                    rset.getString("Datum"));

        }
    }
    return new TaBarSeries(name,ticks,currency,timeFormatType);
}
 
源代码21 项目: jdk8u-jdk   文件: TCKDateTimeFormatters.java
@Test(expectedExceptions=DateTimeParseException.class)
public void test_parse_basicIsoDate_largeYear() {
    try {
        LocalDate expected = LocalDate.of(123456, 6, 3);
        assertEquals(DateTimeFormatter.BASIC_ISO_DATE.parse("+1234560603", LocalDate::from), expected);
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getErrorIndex(), 0);
        assertEquals(ex.getParsedString(), "+1234560603");
        throw ex;
    }
}
 
源代码22 项目: e-commerce-microservice   文件: TestUtil.java
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
    try {
        if (!date.isEqual(ZonedDateTime.parse(item))) {
            mismatchDescription.appendText("was ").appendValue(item);
            return false;
        }
        return true;
    } catch (DateTimeParseException e) {
        mismatchDescription.appendText("was ").appendValue(item)
            .appendText(", which could not be parsed as a ZonedDateTime");
        return false;
    }

}
 
源代码23 项目: dragonwell8_jdk   文件: TCKPeriod.java
@Test(dataProvider="parseSuccess")
public void factory_parse_minus(String text, Period expected) {
    Period p = null;
    try {
        p = Period.parse("-" + text);
    } catch (DateTimeParseException ex) {
        assertEquals(expected.getYears() == Integer.MIN_VALUE ||
                expected.getMonths() == Integer.MIN_VALUE ||
                expected.getDays() == Integer.MIN_VALUE, true);
        return;
    }
    // not inside try/catch or it breaks test
    assertEquals(p, expected.negated());
}
 
private void expectFailure(String json) throws Throwable {
    try {
        READER.readValue(aposToQuotes(json));
        fail("expected DateTimeParseException");
    } catch (JsonProcessingException e) {
        if (e.getCause() == null) {
            throw e;
        }
        if (!(e.getCause() instanceof DateTimeParseException)) {
            throw e.getCause();
        }
    }
}
 
源代码25 项目: openjdk-jdk8u   文件: TCKYear.java
@Test(dataProvider="badParseData", expectedExceptions=DateTimeParseException.class)
public void factory_parse_fail(String text, int pos) {
    try {
        Year.parse(text);
        fail(String.format("Parse should have failed for %s at position %d", text, pos));
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getParsedString(), text);
        assertEquals(ex.getErrorIndex(), pos);
        throw ex;
    }
}
 
源代码26 项目: graphql-jpa   文件: JavaScalars.java
private LocalDate parseStringToLocalDate(String input) {
    try {
        return LocalDate.parse(input);
    } catch (DateTimeParseException e) {
        log.warn("Failed to parse Date from input: " + input, e);
        return null;
    }
}
 
源代码27 项目: edison-microservice   文件: InstantValidator.java
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }
    try {
        Instant.parse(value);
    } catch (DateTimeParseException e){
        return false;
    }
    return true;
}
 
源代码28 项目: jdk8u60   文件: Duration.java
private static long parseNumber(CharSequence text, String parsed, int multiplier, String errorText) {
    // regex limits to [-+]?[0-9]+
    if (parsed == null) {
        return 0;
    }
    try {
        long val = Long.parseLong(parsed);
        return Math.multiplyExact(val, multiplier);
    } catch (NumberFormatException | ArithmeticException ex) {
        throw (DateTimeParseException) new DateTimeParseException("Text cannot be parsed to a Duration: " + errorText, text, 0).initCause(ex);
    }
}
 
源代码29 项目: Hyperium   文件: MigrationManager.java
private LocalDate getUpgradeDate() {
    if (!upgradeDateFile.exists()) return xpChangeDate;
    try {
        String date = FileUtils.readFileToString(upgradeDateFile, StandardCharsets.UTF_8);
        return LocalDate.parse(date, OLD_FORMAT);
    } catch (IOException | DateTimeParseException | NullPointerException e) {
        return xpChangeDate;
    }
}
 
源代码30 项目: htmlunit   文件: HtmlTimeInput.java
/**
 * {@inheritDoc}
 */
@Override
public void setValueAttribute(final String newValue) {
    try {
        if (hasFeature(HTMLINPUT_TYPE_DATETIME_SUPPORTED)
                && StringUtils.isNotEmpty(newValue)) {
            FORMATTER_.parse(newValue);
        }
        super.setValueAttribute(newValue);
    }
    catch (final DateTimeParseException e) {
        // ignore
    }
}
 
 类所在包
 类方法
 同包方法