java.time.format.DateTimeParseException Java Examples

The following examples show how to use java.time.format.DateTimeParseException. 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 check out the related API usage on the sidebar.
Example #1
Source Project: bearchoke   Author: bjornharvold   File: ZonedDateTimeReadConverter.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source Project: pt2matsim   Author: matsim-org   File: HafasConverter.java    License: GNU General Public License v2.0 6 votes vote down vote up
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
		);
	}
}
 
Example #3
Source Project: dragonwell8_jdk   Author: alibaba   File: TCKDateTimeParseResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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
        }
    }
}
 
Example #4
Source Project: hmftools   Author: hartwigmedical   File: LimsFactory.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #5
Source Project: jdk8u-jdk   Author: frohoff   File: TCKDateTimeParseResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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
        }
    }
}
 
Example #6
Source Project: TencentKona-8   Author: Tencent   File: TCKIsoFields.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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
        }
    }
}
 
Example #7
Source Project: TencentKona-8   Author: Tencent   File: TCKDateTimeParseResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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
            }
        }
    }
}
 
Example #8
Source Project: dragonwell8_jdk   Author: alibaba   File: JapanEraNameCompatTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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");
    }
}
 
Example #9
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: TCKDateTimeParseResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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
        }
    }
}
 
Example #10
Source Project: java-ilp-core   Author: interledger-deprecated   File: OerGeneralizedTimeCodec.java    License: Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #11
Source Project: dragonwell8_jdk   Author: alibaba   File: TCKIsoFields.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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
        }
    }
}
 
Example #12
Source Project: rya   Author: apache   File: TemporalIntervalRelationFunction.java    License: Apache License 2.0 6 votes vote down vote up
@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");
    }
}
 
Example #13
Source Project: jackson-modules-java8   Author: FasterXML   File: ZonedDateTimeDeserTest.java    License: Apache License 2.0 5 votes vote down vote up
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();
        }
    }
}
 
Example #14
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: TCKPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example #15
Source Project: gcp-ingestion   Author: mozilla   File: Time.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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;
  }
}
 
Example #16
Source Project: openvsx   Author: eclipse   File: AdminAPI.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@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";
}
 
Example #17
Source Project: Recaf   Author: Col-E   File: SelfUpdater.java    License: MIT License 5 votes vote down vote up
/**
 * 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"));
	}
}
 
Example #18
Source Project: ditto   Author: eclipse   File: TimeoutValueValidator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example #19
Source Project: jdk8u-jdk   Author: frohoff   File: TCKDateTimeParseResolver.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #20
Source Project: TAcharting   Author: team172011   File: SqlLiteConnector.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 *
 * @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);
}
 
Example #21
Source Project: jdk8u-jdk   Author: frohoff   File: TCKDateTimeFormatters.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
    }
}
 
Example #22
Source Project: e-commerce-microservice   Author: xebialabs   File: TestUtil.java    License: Apache License 2.0 5 votes vote down vote up
@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;
    }

}
 
Example #23
Source Project: dragonwell8_jdk   Author: alibaba   File: TCKPeriod.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example #24
Source Project: jackson-modules-java8   Author: FasterXML   File: TestYearDeserialization.java    License: Apache License 2.0 5 votes vote down vote up
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();
        }
    }
}
 
Example #25
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: TCKYear.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
    }
}
 
Example #26
Source Project: graphql-jpa   Author: jcrygier   File: JavaScalars.java    License: MIT License 5 votes vote down vote up
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;
    }
}
 
Example #27
Source Project: edison-microservice   Author: otto-de   File: InstantValidator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }
    try {
        Instant.parse(value);
    } catch (DateTimeParseException e){
        return false;
    }
    return true;
}
 
Example #28
Source Project: jdk8u60   Author: chenghanpeng   File: Duration.java    License: GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #29
Source Project: Hyperium   Author: HyperiumClient   File: MigrationManager.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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;
    }
}
 
Example #30
Source Project: htmlunit   Author: HtmlUnit   File: HtmlTimeInput.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@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
    }
}