Search in sources :

Example 11 with TemporalUnit

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

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 implementations 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) Boolean.valueOf(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 enumString = config.getProperty(key).toString();
        for (Enum ec : constants) if (ec.toString().equals(enumString))
            return (O) ec;
        throw new IllegalArgumentException("No match for string \"" + enumString + "\" 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");
            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: " + 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 12 with TemporalUnit

use of java.time.temporal.TemporalUnit in project data-prep by Talend.

the class ComputeTimeSince method applyOnColumn.

@Override
public void applyOnColumn(DataSetRow row, ActionContext context) {
    RowMetadata rowMetadata = context.getRowMetadata();
    Map<String, String> parameters = context.getParameters();
    String columnId = context.getColumnId();
    TemporalUnit unit = ChronoUnit.valueOf(parameters.get(TIME_UNIT_PARAMETER).toUpperCase());
    String newValue;
    try {
        String mode = context.get(SINCE_WHEN_PARAMETER);
        LocalDateTime since;
        switch(mode) {
            case OTHER_COLUMN_MODE:
                ColumnMetadata selectedColumn = rowMetadata.getById(parameters.get(SELECTED_COLUMN_PARAMETER));
                String dateToCompare = row.get(selectedColumn.getId());
                since = Providers.get().parse(dateToCompare, selectedColumn);
                break;
            case SPECIFIC_DATE_MODE:
            case NOW_SERVER_SIDE_MODE:
            default:
                since = context.get(SINCE_DATE_PARAMETER);
                break;
        }
        // parse the date
        if (since == null) {
            newValue = StringUtils.EMPTY;
        } else {
            String value = row.get(columnId);
            LocalDateTime temporalAccessor = Providers.get().parse(value, context.getRowMetadata().getById(columnId));
            Temporal valueAsDate = LocalDateTime.from(temporalAccessor);
            newValue = String.valueOf(unit.between(valueAsDate, since));
        }
    } catch (DateTimeException e) {
        LOGGER.trace("Error on dateTime parsing", e);
        // Nothing to do: in this case, temporalAccessor is left null
        newValue = StringUtils.EMPTY;
    }
    row.set(ActionsUtils.getTargetColumnId(context), newValue);
}
Also used : LocalDateTime(java.time.LocalDateTime) ColumnMetadata(org.talend.dataprep.api.dataset.ColumnMetadata) DateTimeException(java.time.DateTimeException) Temporal(java.time.temporal.Temporal) TemporalUnit(java.time.temporal.TemporalUnit) RowMetadata(org.talend.dataprep.api.dataset.RowMetadata)

Example 13 with TemporalUnit

use of java.time.temporal.TemporalUnit in project data-prep by Talend.

the class ComputeTimeSince method getAdditionalColumns.

protected List<ActionsUtils.AdditionalColumn> getAdditionalColumns(ActionContext context) {
    final List<ActionsUtils.AdditionalColumn> additionalColumns = new ArrayList<>();
    TemporalUnit unit = ChronoUnit.valueOf(context.getParameters().get(TIME_UNIT_PARAMETER).toUpperCase());
    additionalColumns.add(ActionsUtils.additionalColumn().withName(PREFIX + context.getColumnName() + SUFFIX + unit.toString().toLowerCase()).withType(Type.INTEGER));
    return additionalColumns;
}
Also used : TemporalUnit(java.time.temporal.TemporalUnit) ArrayList(java.util.ArrayList)

Example 14 with TemporalUnit

use of java.time.temporal.TemporalUnit in project Bytecoder by mirkosertic.

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 15 with TemporalUnit

use of java.time.temporal.TemporalUnit in project Bytecoder by mirkosertic.

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)

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