Search in sources :

Example 6 with TemporalUnit

use of java.time.temporal.TemporalUnit in project jdk8u_jdk by JetBrains.

the class TCKChronoLocalDateTime method test_badPlusTemporalUnitChrono.

@Test(dataProvider = "calendars")
public void test_badPlusTemporalUnitChrono(Chronology chrono) {
    LocalDate refDate = LocalDate.of(2013, 1, 1);
    ChronoLocalDateTime<?> cdt = chrono.date(refDate).atTime(LocalTime.NOON);
    for (Chronology[] clist : data_of_calendars()) {
        Chronology chrono2 = clist[0];
        ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
        TemporalUnit adjuster = new FixedTemporalUnit(cdt2);
        if (chrono != chrono2) {
            try {
                cdt.plus(1, adjuster);
                Assert.fail("TemporalUnit.doPlus plus should have thrown a ClassCastException" + cdt + ", can not be cast to " + cdt2);
            } catch (ClassCastException cce) {
            // Expected exception; not an error
            }
        } else {
            // Same chronology,
            ChronoLocalDateTime<?> result = cdt.plus(1, adjuster);
            assertEquals(result, cdt2, "WithAdjuster failed to replace date");
        }
    }
}
Also used : TemporalUnit(java.time.temporal.TemporalUnit) HijrahChronology(java.time.chrono.HijrahChronology) ThaiBuddhistChronology(java.time.chrono.ThaiBuddhistChronology) IsoChronology(java.time.chrono.IsoChronology) Chronology(java.time.chrono.Chronology) MinguoChronology(java.time.chrono.MinguoChronology) JapaneseChronology(java.time.chrono.JapaneseChronology) LocalDate(java.time.LocalDate) Test(org.testng.annotations.Test)

Example 7 with TemporalUnit

use of java.time.temporal.TemporalUnit in project titan by thinkaurelius.

the class CommonsConfiguration method get.

@Override
public <O> O get(String key, Class<O> datatype) {
    if (!config.containsKey(key))
        return null;
    if (datatype.isArray()) {
        Preconditions.checkArgument(datatype.getComponentType() == String.class, "Only string arrays are supported: %s", datatype);
        return (O) config.getStringArray(key);
    } else if (Number.class.isAssignableFrom(datatype)) {
        // A properties file configuration returns Strings even for numeric
        // values small enough to fit inside Integer (e.g. 5000). In-memory
        // configuration impls seem to be able to store and return actual
        // numeric types rather than String
        //
        // We try to handle either case here
        Object o = config.getProperty(key);
        if (datatype.isInstance(o)) {
            return (O) o;
        } else {
            return constructFromStringArgument(datatype, o.toString());
        }
    } else if (datatype == String.class) {
        return (O) config.getString(key);
    } else if (datatype == Boolean.class) {
        return (O) new Boolean(config.getBoolean(key));
    } else if (datatype.isEnum()) {
        Enum[] constants = (Enum[]) datatype.getEnumConstants();
        Preconditions.checkState(null != constants && 0 < constants.length, "Zero-length or undefined enum");
        String estr = config.getProperty(key).toString();
        for (Enum ec : constants) if (ec.toString().equals(estr))
            return (O) ec;
        throw new IllegalArgumentException("No match for string \"" + estr + "\" in enum " + datatype);
    } else if (datatype == Object.class) {
        return (O) config.getProperty(key);
    } else if (Duration.class.isAssignableFrom(datatype)) {
        // This is a conceptual leak; the config layer should ideally only handle standard library types
        Object o = config.getProperty(key);
        if (Duration.class.isInstance(o)) {
            return (O) o;
        } else {
            String[] comps = o.toString().split("\\s");
            TemporalUnit unit = null;
            if (comps.length == 1) {
                //By default, times are in milli seconds
                unit = ChronoUnit.MILLIS;
            } else if (comps.length == 2) {
                unit = Durations.parse(comps[1]);
            } else {
                throw new IllegalArgumentException("Cannot parse time duration from: " + o.toString());
            }
            return (O) Duration.of(Long.valueOf(comps[0]), unit);
        }
    // Lists are deliberately not supported.  List's generic parameter
    // is subject to erasure and can't be checked at runtime.  Someone
    // could create a ConfigOption<List<Number>>; we would instead return
    // a List<String> like we always do at runtime, and it wouldn't break
    // until the client tried to use the contents of the list.
    //
    // We could theoretically get around this by adding a type token to
    // every declaration of a List-typed ConfigOption, but it's just
    // not worth doing since we only actually use String[] anyway.
    //        } else if (List.class.isAssignableFrom(datatype)) {
    //            return (O) config.getProperty(key);
    } else
        throw new IllegalArgumentException("Unsupported data type: " + datatype);
}
Also used : TemporalUnit(java.time.temporal.TemporalUnit)

Example 8 with TemporalUnit

use of java.time.temporal.TemporalUnit in project jdk8u_jdk by JetBrains.

the class Duration method from.

//-----------------------------------------------------------------------
/**
     * Obtains an instance of {@code Duration} from a temporal amount.
     * <p>
     * This obtains a duration based on the specified amount.
     * A {@code TemporalAmount} represents an  amount of time, which may be
     * date-based or time-based, which this factory extracts to a duration.
     * <p>
     * The conversion loops around the set of units from the amount and uses
     * the {@linkplain TemporalUnit#getDuration() duration} of the unit to
     * calculate the total {@code Duration}.
     * Only a subset of units are accepted by this method. The unit must either
     * have an {@linkplain TemporalUnit#isDurationEstimated() exact duration}
     * or be {@link ChronoUnit#DAYS} which is treated as 24 hours.
     * If any other units are found then an exception is thrown.
     *
     * @param amount  the temporal amount to convert, not null
     * @return the equivalent duration, not null
     * @throws DateTimeException if unable to convert to a {@code Duration}
     * @throws ArithmeticException if numeric overflow occurs
     */
public static Duration from(TemporalAmount amount) {
    Objects.requireNonNull(amount, "amount");
    Duration duration = ZERO;
    for (TemporalUnit unit : amount.getUnits()) {
        duration = duration.plus(amount.get(unit), unit);
    }
    return duration;
}
Also used : TemporalUnit(java.time.temporal.TemporalUnit)

Example 9 with TemporalUnit

use of java.time.temporal.TemporalUnit in project jdk8u_jdk by JetBrains.

the class Period method from.

//-----------------------------------------------------------------------
/**
     * Obtains an instance of {@code Period} from a temporal amount.
     * <p>
     * This obtains a period based on the specified amount.
     * A {@code TemporalAmount} represents an  amount of time, which may be
     * date-based or time-based, which this factory extracts to a {@code Period}.
     * <p>
     * The conversion loops around the set of units from the amount and uses
     * the {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS}
     * and {@link ChronoUnit#DAYS DAYS} units to create a period.
     * If any other units are found then an exception is thrown.
     * <p>
     * If the amount is a {@code ChronoPeriod} then it must use the ISO chronology.
     *
     * @param amount  the temporal amount to convert, not null
     * @return the equivalent period, not null
     * @throws DateTimeException if unable to convert to a {@code Period}
     * @throws ArithmeticException if the amount of years, months or days exceeds an int
     */
public static Period from(TemporalAmount amount) {
    if (amount instanceof Period) {
        return (Period) amount;
    }
    if (amount instanceof ChronoPeriod) {
        if (IsoChronology.INSTANCE.equals(((ChronoPeriod) amount).getChronology()) == false) {
            throw new DateTimeException("Period requires ISO chronology: " + amount);
        }
    }
    Objects.requireNonNull(amount, "amount");
    int years = 0;
    int months = 0;
    int days = 0;
    for (TemporalUnit unit : amount.getUnits()) {
        long unitAmount = amount.get(unit);
        if (unit == ChronoUnit.YEARS) {
            years = Math.toIntExact(unitAmount);
        } else if (unit == ChronoUnit.MONTHS) {
            months = Math.toIntExact(unitAmount);
        } else if (unit == ChronoUnit.DAYS) {
            days = Math.toIntExact(unitAmount);
        } else {
            throw new DateTimeException("Unit must be Years, Months or Days, but was " + unit);
        }
    }
    return create(years, months, days);
}
Also used : ChronoPeriod(java.time.chrono.ChronoPeriod) TemporalUnit(java.time.temporal.TemporalUnit) ChronoPeriod(java.time.chrono.ChronoPeriod)

Example 10 with TemporalUnit

use of java.time.temporal.TemporalUnit in project janusgraph by JanusGraph.

the class HadoopConfiguration method get.

@Override
public <O> O get(String key, Class<O> dataType) {
    final String internalKey = getInternalKey(key);
    if (null == config.get(internalKey))
        return null;
    if (dataType.isArray()) {
        Preconditions.checkArgument(dataType.getComponentType() == String.class, "Only string arrays are supported: %s", dataType);
        return (O) config.getStrings(internalKey);
    } else if (Number.class.isAssignableFrom(dataType)) {
        String s = config.get(internalKey);
        return constructFromStringArgument(dataType, s);
    } else if (dataType == String.class) {
        return (O) config.get(internalKey);
    } else if (dataType == Boolean.class) {
        return (O) Boolean.valueOf(config.get(internalKey));
    } else if (dataType.isEnum()) {
        O[] constants = dataType.getEnumConstants();
        Preconditions.checkState(null != constants && 0 < constants.length, "Zero-length or undefined enum");
        String estr = config.get(internalKey);
        for (O c : constants) if (c.toString().equals(estr))
            return c;
        throw new IllegalArgumentException("No match for string \"" + estr + "\" in enum " + dataType);
    } else if (dataType == Object.class) {
        // Object.class must be supported for the sake of AbstractConfiguration's getSubset impl
        return (O) config.get(internalKey);
    } else if (Duration.class.isAssignableFrom(dataType)) {
        // This is a conceptual leak; the config layer should ideally only handle standard library types
        String s = config.get(internalKey);
        String[] comps = s.split("\\s");
        final TemporalUnit unit;
        switch(comps.length) {
            case 1:
                // By default, times are in milli seconds
                unit = ChronoUnit.MILLIS;
                break;
            case 2:
                unit = Durations.parse(comps[1]);
                break;
            default:
                throw new IllegalArgumentException("Cannot parse time duration from: " + s);
        }
        return (O) Duration.of(Long.valueOf(comps[0]), unit);
    } else
        throw new IllegalArgumentException("Unsupported data type: " + dataType);
}
Also used : TemporalUnit(java.time.temporal.TemporalUnit)

Aggregations

TemporalUnit (java.time.temporal.TemporalUnit)60 LocalDate (java.time.LocalDate)18 Test (org.junit.Test)18 Test (org.testng.annotations.Test)17 Temporal (java.time.temporal.Temporal)16 TemporalAmount (java.time.temporal.TemporalAmount)15 Chronology (java.time.chrono.Chronology)12 IsoChronology (java.time.chrono.IsoChronology)12 ArrayList (java.util.ArrayList)12 UseDataProvider (com.tngtech.java.junit.dataprovider.UseDataProvider)6 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)6 DateTimeException (java.time.DateTimeException)6 HijrahChronology (java.time.chrono.HijrahChronology)6 JapaneseChronology (java.time.chrono.JapaneseChronology)6 MinguoChronology (java.time.chrono.MinguoChronology)6 ThaiBuddhistChronology (java.time.chrono.ThaiBuddhistChronology)6 Matcher (java.util.regex.Matcher)6 Pattern (java.util.regex.Pattern)6 Duration (java.time.Duration)5 ChronoLocalDate (java.time.chrono.ChronoLocalDate)4