aboutsummaryrefslogtreecommitdiffstats
path: root/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/TimeParser.java
blob: 71367d54c7dbb3cea8c24abda8d4b58f98795099 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.builder.xml.dom.chains.search;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Utility class for parsing timeout fields.
 *
 * @author Tony Vaagenes
 * @author Steinar Knutsen
 */
public class TimeParser {

    private static final Pattern timeoutPattern = Pattern.compile("(\\d+(\\.\\d*)?)\\s*(m)?s");
    private static final double milliSecondsPerSecond = 1000.0d;

    public static Double seconds(String timeout) {
        Matcher matcher = timeoutPattern.matcher(timeout);
        if (!matcher.matches()) {
            throw new RuntimeException("Timeout pattern not in sync with schema");
        }

        double value = Double.parseDouble(matcher.group(1));
        if (matcher.group(3) != null) {
            value /= milliSecondsPerSecond;
        }
        return value;
    }

    public static int asMilliSeconds(String timeout) {
        Matcher matcher = timeoutPattern.matcher(timeout);
        if (!matcher.matches()) {
            throw new RuntimeException("Timeout pattern not in sync with schema");
        }

        double value = Double.parseDouble(matcher.group(1));
        if (matcher.group(3) == null) {
            value *= milliSecondsPerSecond;
        }

        return (int) value;
    }

}