Java Code Examples for java.time.Duration#parse()

The following examples show how to use java.time.Duration#parse() . 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 File: TimeUtil.java    From styx with Apache License 2.0 6 votes vote down vote up
/**
 * Applies an ISO 8601 Duration to a {@link ZonedDateTime}.
 *
 * <p>Since the JDK defined different types for the different parts of a Duration
 * specification, this utility method is needed when a full Duration is to be applied to a
 * {@link ZonedDateTime}. See {@link Period} and {@link Duration}.
 *
 * <p>All date-based parts of a Duration specification (Year, Month, Day or Week) are parsed
 * using {@link Period#parse(CharSequence)} and added to the time. The remaining parts (Hour,
 * Minute, Second) are parsed using {@link Duration#parse(CharSequence)} and added to the time.
 *
 * @param time   A zoned date time to apply the offset to
 * @param offset The offset in ISO 8601 Duration format
 * @return A zoned date time with the offset applied
 */
public static ZonedDateTime addOffset(ZonedDateTime time, String offset) {
  final Matcher matcher = OFFSET_PATTERN.matcher(offset);

  if (!matcher.matches()) {
    throw new DateTimeParseException("Unable to parse offset period", offset, 0);
  }
  final String sign = matcher.group(1);

  final String periodOffset = sign + "P" + Optional.ofNullable(matcher.group(2)).orElse("0D");
  final String durationOffset = sign + "PT" + Optional.ofNullable(matcher.group(4)).orElse("0S");

  final TemporalAmount dateAmount = Period.parse(periodOffset);
  final TemporalAmount timeAmount = Duration.parse(durationOffset);

  return time.plus(dateAmount).plus(timeAmount);
}
 
Example 2
Source File: TCKDuration.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="parseSuccess")
public void factory_parse_minus(String text, long expectedSeconds, int expectedNanoOfSecond) {
    Duration test;
    try {
        test = Duration.parse("-" + text);
    } catch (DateTimeParseException ex) {
        assertEquals(expectedSeconds == Long.MIN_VALUE, true);
        return;
    }
    // not inside try/catch or it breaks test
    assertEquals(test, Duration.ofSeconds(expectedSeconds, expectedNanoOfSecond).negated());
}
 
Example 3
Source File: KPIRepository.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
private KPI createKPI(final I_WEBUI_KPI kpiDef)
{
	final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(kpiDef);

	Duration compareOffset = null;
	if (kpiDef.isGenerateComparation())
	{
		final String compareOffetStr = kpiDef.getCompareOffset();
		compareOffset = Duration.parse(compareOffetStr);
	}

	return KPI.builder()
			.setId(kpiDef.getWEBUI_KPI_ID())
			.setCaption(trls.getColumnTrl(I_WEBUI_KPI.COLUMNNAME_Name, kpiDef.getName()))
			.setDescription(trls.getColumnTrl(I_WEBUI_KPI.COLUMNNAME_Description, kpiDef.getDescription()))
			.setChartType(KPIChartType.forCode(kpiDef.getChartType()))
			.setFields(retrieveKPIFields(kpiDef.getWEBUI_KPI_ID(), kpiDef.isGenerateComparation()))
			//
			.setCompareOffset(compareOffset)
			//
			.setTimeRangeDefaults(KPITimeRangeDefaults.builder()
					.defaultTimeRangeFromString(kpiDef.getES_TimeRange())
					.defaultTimeRangeEndOffsetFromString(kpiDef.getES_TimeRange_End())
					.build())
			//
			.setPollIntervalSec(kpiDef.getPollIntervalSec())
			//
			.setESSearchIndex(kpiDef.getES_Index())
			.setESSearchTypes(kpiDef.getES_Type())
			.setESQuery(kpiDef.getES_Query())
			//
			.build();
}
 
Example 4
Source File: DropWizardMetricRegistry.java    From vertexium with Apache License 2.0 5 votes vote down vote up
static Duration parseDuration(String period) {
    period = period.trim();
    try {
        return Duration.parse(period.toUpperCase());
    } catch (Exception ex) {
        return Duration.parse("PT" + period.toUpperCase());
    }
}
 
Example 5
Source File: PerfCucumberRunnerTest.java    From cucumber-performance with MIT License 5 votes vote down vote up
@Test
public void testPerfCucumberRunnerCucumberFeatureListOfStringSliceDuration() {
	PerfRuntimeOptionsFactory optf = new PerfRuntimeOptionsFactory(options1.class);
	PerfRuntimeOptions opt = optf.create();
	PlanParser parser = new PlanParser(UUID::randomUUID);
	Supplier<ClassLoader> classLoader = this.getClass()::getClassLoader;
	List<PerfPlan> res =  new PathPlanSupplier(classLoader, opt.getPlanPaths(), parser).get();
	List <PerfGroup> pg =buildGroups(res.get(0).getSaladPlan().getPlan().getChildren().get(0));
	RunnerOptions ro = new RunnerOptions(pg.get(1));
	ro.setFeatures(FeatureBuilder.getFeatures(FeatureBuilder.createRuntimeOptions(options1.class)));
	CucumberRunner runner = new CucumberRunner(ro,opt.getCucumberOptions(),Duration.parse("PT5.1S"),false);
	assertEquals("test",runner.getFeatures().get(2).getName());
}
 
Example 6
Source File: TCKDuration.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="parseSuccess")
public void factory_parse_comma(String text, long expectedSeconds, int expectedNanoOfSecond) {
    text = text.replace('.', ',');
    Duration test = Duration.parse(text);
    assertEquals(test.getSeconds(), expectedSeconds);
    assertEquals(test.getNano(), expectedNanoOfSecond);
}
 
Example 7
Source File: TCKDuration.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="parseSuccess")
public void factory_parse_comma(String text, long expectedSeconds, int expectedNanoOfSecond) {
    text = text.replace('.', ',');
    Duration test = Duration.parse(text);
    assertEquals(test.getSeconds(), expectedSeconds);
    assertEquals(test.getNano(), expectedNanoOfSecond);
}
 
Example 8
Source File: TCKDuration.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void factory_parse_nullText() {
    Duration.parse(null);
}
 
Example 9
Source File: TCKDuration.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeParseException.class)
public void factory_parse_tooBig_decimal() {
    Duration.parse("PT" + Long.MAX_VALUE + "1.1S");
}
 
Example 10
Source File: TCKDuration.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeParseException.class)
public void factory_parse_tooBig_decimal() {
    Duration.parse("PT" + Long.MAX_VALUE + "1.1S");
}
 
Example 11
Source File: MailingListBridgeBotFactory.java    From skara with GNU General Public License v2.0 4 votes vote down vote up
@Override
public List<Bot> create(BotConfiguration configuration) {
    var ret = new ArrayList<Bot>();
    var specific = configuration.specific();

    var from = EmailAddress.from(specific.get("name").asString(), specific.get("mail").asString());
    var ignoredUsers = specific.get("ignored").get("users").stream()
                               .map(JSONValue::asString)
                               .collect(Collectors.toSet());
    var ignoredComments = specific.get("ignored").get("comments").stream()
                                  .map(JSONValue::asString)
                                  .map(pattern -> Pattern.compile(pattern, Pattern.MULTILINE | Pattern.DOTALL))
                                  .collect(Collectors.toSet());
    var listArchive = URIBuilder.base(specific.get("server").get("archive").asString()).build();
    var listSmtp = specific.get("server").get("smtp").asString();
    var interval = specific.get("server").contains("interval") ? Duration.parse(specific.get("server").get("interval").asString()) : Duration.ofSeconds(1);

    var webrevRepo = configuration.repository(specific.get("webrevs").get("repository").asString());
    var webrevRef = configuration.repositoryRef(specific.get("webrevs").get("repository").asString());
    var webrevWeb = specific.get("webrevs").get("web").asString();

    var archiveRepo = configuration.repository(specific.get("archive").asString());
    var archiveRef = configuration.repositoryRef(specific.get("archive").asString());
    var issueTracker = URIBuilder.base(specific.get("issues").asString()).build();

    var listNamesForReading = new HashSet<EmailAddress>();
    var allRepositories = new HashSet<HostedRepository>();

    var readyLabels = specific.get("ready").get("labels").stream()
            .map(JSONValue::asString)
            .collect(Collectors.toSet());
    var readyComments = specific.get("ready").get("comments").stream()
            .map(JSONValue::asObject)
            .collect(Collectors.toMap(obj -> obj.get("user").asString(),
                                      obj -> Pattern.compile(obj.get("pattern").asString())));
    var cooldown = specific.contains("cooldown") ? Duration.parse(specific.get("cooldown").asString()) : Duration.ofMinutes(1);

    for (var repoConfig : specific.get("repositories").asArray()) {
        var repo = repoConfig.get("repository").asString();
        var censusRepo = configuration.repository(repoConfig.get("census").asString());
        var censusRef = configuration.repositoryRef(repoConfig.get("census").asString());

        Map<String, String> headers = repoConfig.contains("headers") ?
                repoConfig.get("headers").fields().stream()
                          .collect(Collectors.toMap(JSONObject.Field::name, field -> field.value().asString())) :
                Map.of();
        var lists = parseLists(repoConfig.get("lists"));
        var folder = repoConfig.contains("folder") ? repoConfig.get("folder").asString() : configuration.repositoryName(repo);
        var botBuilder = MailingListBridgeBot.newBuilder().from(from)
                                             .repo(configuration.repository(repo))
                                             .archive(archiveRepo)
                                             .archiveRef(archiveRef)
                                             .censusRepo(censusRepo)
                                             .censusRef(censusRef)
                                             .lists(lists)
                                             .ignoredUsers(ignoredUsers)
                                             .ignoredComments(ignoredComments)
                                             .listArchive(listArchive)
                                             .smtpServer(listSmtp)
                                             .webrevStorageRepository(webrevRepo)
                                             .webrevStorageRef(webrevRef)
                                             .webrevStorageBase(Path.of(folder))
                                             .webrevStorageBaseUri(URIBuilder.base(webrevWeb).build())
                                             .readyLabels(readyLabels)
                                             .readyComments(readyComments)
                                             .issueTracker(issueTracker)
                                             .headers(headers)
                                             .sendInterval(interval)
                                             .cooldown(cooldown)
                                             .seedStorage(configuration.storageFolder().resolve("seeds"));

        if (repoConfig.contains("reponame")) {
            botBuilder.repoInSubject(repoConfig.get("reponame").asBoolean());
        }
        if (repoConfig.contains("branchname")) {
            botBuilder.branchInSubject(Pattern.compile(repoConfig.get("branchname").asString()));
        }
        ret.add(botBuilder.build());

        if (!repoConfig.contains("bidirectional") || repoConfig.get("bidirectional").asBoolean()) {
            for (var list : lists) {
                listNamesForReading.add(list.list());
            }
        }
        allRepositories.add(configuration.repository(repo));
    }

    var mailmanServer = MailingListServerFactory.createMailmanServer(listArchive, listSmtp, Duration.ZERO);
    var listsForReading = listNamesForReading.stream()
                               .map(name -> mailmanServer.getList(name.toString()))
                               .collect(Collectors.toSet());

    var bot = new MailingListArchiveReaderBot(from, listsForReading, allRepositories);
    ret.add(bot);

    return ret;
}
 
Example 12
Source File: TCKDuration.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="parseSuccess")
public void factory_parse(String text, long expectedSeconds, int expectedNanoOfSecond) {
    Duration test = Duration.parse(text);
    assertEquals(test.getSeconds(), expectedSeconds);
    assertEquals(test.getNano(), expectedNanoOfSecond);
}
 
Example 13
Source File: TCKDuration.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeParseException.class)
public void factory_parse_tooSmall() {
    Duration.parse("PT" + Long.MIN_VALUE + "1S");
}
 
Example 14
Source File: TCKDuration.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider="parseSuccess")
public void factory_parse_lowerCase(String text, long expectedSeconds, int expectedNanoOfSecond) {
    Duration test = Duration.parse(text.toLowerCase(Locale.ENGLISH));
    assertEquals(test.getSeconds(), expectedSeconds);
    assertEquals(test.getNano(), expectedNanoOfSecond);
}
 
Example 15
Source File: TCKDuration.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void factory_parse_nullText() {
    Duration.parse(null);
}
 
Example 16
Source File: DurationFormatter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Duration parse(String text, Locale locale) throws ParseException {
	return Duration.parse(text);
}
 
Example 17
Source File: TCKDuration.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeParseException.class)
public void factory_parse_tooBig() {
    Duration.parse("PT" + Long.MAX_VALUE + "1S");
}
 
Example 18
Source File: DateExpression.java    From vividus with Apache License 2.0 4 votes vote down vote up
public ZonedDateTime processDuration(ZonedDateTime zonedDateTime)
{
    Duration duration = Duration.parse(DURATION_DESIGNATOR + getDurationString());
    return !hasMinusSign() ? zonedDateTime.plus(duration) : zonedDateTime.minus(duration);
}
 
Example 19
Source File: TCKDuration.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=DateTimeParseException.class)
public void factory_parse_tooBig() {
    Duration.parse("PT" + Long.MAX_VALUE + "1S");
}
 
Example 20
Source File: TCKDuration.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void factory_parse_nullText() {
    Duration.parse(null);
}