Example usage for org.joda.time DateTimeZone forOffsetHours

List of usage examples for org.joda.time DateTimeZone forOffsetHours

Introduction

In this page you can find the example usage for org.joda.time DateTimeZone forOffsetHours.

Prototype

public static DateTimeZone forOffsetHours(int hoursOffset) throws IllegalArgumentException 

Source Link

Document

Gets a time zone instance for the specified offset to UTC in hours.

Usage

From source file:org.codelibs.elasticsearch.search.aggregations.support.ValuesSourceParserHelper.java

License:Apache License

private static <VS extends ValuesSource> void declareFields(
        ObjectParser<? extends ValuesSourceAggregationBuilder<VS, ?>, QueryParseContext> objectParser,
        boolean scriptable, boolean formattable, boolean timezoneAware, ValuesSourceType valuesSourceType,
        ValueType targetValueType) {/*  ww w  .  java  2 s  .c  o  m*/

    objectParser.declareField(ValuesSourceAggregationBuilder::field, XContentParser::text,
            new ParseField("field"), ObjectParser.ValueType.STRING);

    objectParser.declareField(ValuesSourceAggregationBuilder::missing, XContentParser::objectText,
            new ParseField("missing"), ObjectParser.ValueType.VALUE);

    objectParser.declareField(ValuesSourceAggregationBuilder::valueType, p -> {
        ValueType valueType = ValueType.resolveForScript(p.text());
        if (targetValueType != null && valueType.isNotA(targetValueType)) {
            throw new ParsingException(p.getTokenLocation(),
                    "Aggregation [" + objectParser.getName()
                            + "] was configured with an incompatible value type [" + valueType
                            + "]. It can only work on value of type [" + targetValueType + "]");
        }
        return valueType;
    }, new ParseField("value_type", "valueType"), ObjectParser.ValueType.STRING);

    if (formattable) {
        objectParser.declareField(ValuesSourceAggregationBuilder::format, XContentParser::text,
                new ParseField("format"), ObjectParser.ValueType.STRING);
    }

    if (scriptable) {
        objectParser.declareField(ValuesSourceAggregationBuilder::script,
                org.codelibs.elasticsearch.script.Script::parse, Script.SCRIPT_PARSE_FIELD,
                ObjectParser.ValueType.OBJECT_OR_STRING);
    }

    if (timezoneAware) {
        objectParser.declareField(ValuesSourceAggregationBuilder::timeZone, p -> {
            if (p.currentToken() == XContentParser.Token.VALUE_STRING) {
                return DateTimeZone.forID(p.text());
            } else {
                return DateTimeZone.forOffsetHours(p.intValue());
            }
        }, TIME_ZONE, ObjectParser.ValueType.LONG);
    }
}

From source file:org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramParser.java

License:Apache License

@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context)
        throws IOException {

    ValuesSourceConfig<NumericValuesSource> config = new ValuesSourceConfig<NumericValuesSource>(
            NumericValuesSource.class);

    String field = null;/*from  ww w. j  av  a 2s. c o m*/
    String script = null;
    String scriptLang = null;
    Map<String, Object> scriptParams = null;
    boolean keyed = false;
    long minDocCount = 1;
    InternalOrder order = (InternalOrder) Histogram.Order.KEY_ASC;
    String interval = null;
    boolean preZoneAdjustLargeInterval = false;
    DateTimeZone preZone = DateTimeZone.UTC;
    DateTimeZone postZone = DateTimeZone.UTC;
    String format = null;
    long preOffset = 0;
    long postOffset = 0;
    boolean assumeSorted = false;

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if ("field".equals(currentFieldName)) {
                field = parser.text();
            } else if ("script".equals(currentFieldName)) {
                script = parser.text();
            } else if ("lang".equals(currentFieldName)) {
                scriptLang = parser.text();
            } else if ("time_zone".equals(currentFieldName) || "timeZone".equals(currentFieldName)) {
                preZone = parseZone(parser.text());
            } else if ("pre_zone".equals(currentFieldName) || "preZone".equals(currentFieldName)) {
                preZone = parseZone(parser.text());
            } else if ("pre_zone_adjust_large_interval".equals(currentFieldName)
                    || "preZoneAdjustLargeInterval".equals(currentFieldName)) {
                preZoneAdjustLargeInterval = parser.booleanValue();
            } else if ("post_zone".equals(currentFieldName) || "postZone".equals(currentFieldName)) {
                postZone = parseZone(parser.text());
            } else if ("pre_offset".equals(currentFieldName) || "preOffset".equals(currentFieldName)) {
                preOffset = parseOffset(parser.text());
            } else if ("post_offset".equals(currentFieldName) || "postOffset".equals(currentFieldName)) {
                postOffset = parseOffset(parser.text());
            } else if ("interval".equals(currentFieldName)) {
                interval = parser.text();
            } else if ("format".equals(currentFieldName)) {
                format = parser.text();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName
                        + "]: [" + currentFieldName + "].");
            }
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("keyed".equals(currentFieldName)) {
                keyed = parser.booleanValue();
            } else if ("script_values_sorted".equals(currentFieldName)
                    || "scriptValuesSorted".equals(currentFieldName)) {
                assumeSorted = parser.booleanValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName
                        + "]: [" + currentFieldName + "].");
            }
        } else if (token == XContentParser.Token.VALUE_NUMBER) {
            if ("min_doc_count".equals(currentFieldName) || "minDocCount".equals(currentFieldName)) {
                minDocCount = parser.longValue();
            } else if ("time_zone".equals(currentFieldName) || "timeZone".equals(currentFieldName)) {
                preZone = DateTimeZone.forOffsetHours(parser.intValue());
            } else if ("pre_zone".equals(currentFieldName) || "preZone".equals(currentFieldName)) {
                preZone = DateTimeZone.forOffsetHours(parser.intValue());
            } else if ("post_zone".equals(currentFieldName) || "postZone".equals(currentFieldName)) {
                postZone = DateTimeZone.forOffsetHours(parser.intValue());
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName
                        + "]: [" + currentFieldName + "].");
            }
        } else if (token == XContentParser.Token.START_OBJECT) {
            if ("params".equals(currentFieldName)) {
                scriptParams = parser.map();
            } else if ("order".equals(currentFieldName)) {
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else if (token == XContentParser.Token.VALUE_STRING) {
                        String dir = parser.text();
                        boolean asc = "asc".equals(dir);
                        order = resolveOrder(currentFieldName, asc);
                        //TODO should we throw an error if the value is not "asc" or "desc"???
                    }
                }
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName
                        + "]: [" + currentFieldName + "].");
            }
        } else {
            throw new SearchParseException(context,
                    "Unexpected token " + token + " in [" + aggregationName + "].");
        }
    }

    if (interval == null) {
        throw new SearchParseException(context,
                "Missing required field [interval] for histogram aggregation [" + aggregationName + "]");
    }

    SearchScript searchScript = null;
    if (script != null) {
        searchScript = context.scriptService().search(context.lookup(), scriptLang, script, scriptParams);
        config.script(searchScript);
    }

    if (!assumeSorted) {
        // we need values to be sorted and unique for efficiency
        config.ensureSorted(true);
    }

    TimeZoneRounding.Builder tzRoundingBuilder;
    DateTimeUnit dateTimeUnit = dateFieldUnits.get(interval);
    if (dateTimeUnit != null) {
        tzRoundingBuilder = TimeZoneRounding.builder(dateTimeUnit);
    } else {
        // the interval is a time value?
        tzRoundingBuilder = TimeZoneRounding.builder(TimeValue.parseTimeValue(interval, null));
    }

    TimeZoneRounding rounding = tzRoundingBuilder.preZone(preZone).postZone(postZone)
            .preZoneAdjustLargeInterval(preZoneAdjustLargeInterval).preOffset(preOffset).postOffset(postOffset)
            .build();

    if (format != null) {
        config.formatter(new ValueFormatter.DateTime(format));
    }

    if (field == null) {

        if (searchScript != null) {
            ValueParser valueParser = new ValueParser.DateMath(new DateMathParser(
                    DateFieldMapper.Defaults.DATE_TIME_FORMATTER, DateFieldMapper.Defaults.TIME_UNIT));
            config.parser(valueParser);
            return new HistogramAggregator.Factory(aggregationName, config, rounding, order, keyed, minDocCount,
                    InternalDateHistogram.FACTORY);
        }

        // falling back on the get field data context
        return new HistogramAggregator.Factory(aggregationName, config, rounding, order, keyed, minDocCount,
                InternalDateHistogram.FACTORY);
    }

    FieldMapper<?> mapper = context.smartNameFieldMapper(field);
    if (mapper == null) {
        config.unmapped(true);
        return new HistogramAggregator.Factory(aggregationName, config, rounding, order, keyed, minDocCount,
                InternalDateHistogram.FACTORY);
    }

    if (!(mapper instanceof DateFieldMapper)) {
        throw new SearchParseException(context,
                "date histogram can only be aggregated on date fields but [" + field + "] is not a date field");
    }

    IndexFieldData<?> indexFieldData = context.fieldData().getForField(mapper);
    config.fieldContext(new FieldContext(field, indexFieldData));
    return new HistogramAggregator.Factory(aggregationName, config, rounding, order, keyed, minDocCount,
            InternalDateHistogram.FACTORY);
}

From source file:org.elasticsearch.search.aggregations.support.AbstractValuesSourceParser.java

License:Apache License

@Override
public final ValuesSourceAggregationBuilder<VS, ?> parse(String aggregationName, QueryParseContext context)
        throws IOException {

    XContentParser parser = context.parser();
    String field = null;/*from   w  w  w  .ja v  a2  s .c o m*/
    Script script = null;
    ValueType valueType = null;
    String format = null;
    Object missing = null;
    DateTimeZone timezone = null;
    Map<ParseField, Object> otherOptions = new HashMap<>();

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if ("missing".equals(currentFieldName) && token.isValue()) {
            missing = parser.objectText();
        } else if (timezoneAware && context.getParseFieldMatcher().match(currentFieldName, TIME_ZONE)) {
            if (token == XContentParser.Token.VALUE_STRING) {
                timezone = DateTimeZone.forID(parser.text());
            } else if (token == XContentParser.Token.VALUE_NUMBER) {
                timezone = DateTimeZone.forOffsetHours(parser.intValue());
            } else {
                throw new ParsingException(parser.getTokenLocation(), "Unexpected token " + token + " ["
                        + currentFieldName + "] in [" + aggregationName + "].");
            }
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if ("field".equals(currentFieldName)) {
                field = parser.text();
            } else if (formattable && "format".equals(currentFieldName)) {
                format = parser.text();
            } else if (scriptable) {
                if ("value_type".equals(currentFieldName) || "valueType".equals(currentFieldName)) {
                    valueType = ValueType.resolveForScript(parser.text());
                    if (targetValueType != null && valueType.isNotA(targetValueType)) {
                        throw new ParsingException(parser.getTokenLocation(),
                                "Aggregation [" + aggregationName
                                        + "] was configured with an incompatible value type [" + valueType
                                        + "]. It can only work on value of type [" + targetValueType + "]");
                    }
                } else if (!token(aggregationName, currentFieldName, token, parser,
                        context.getParseFieldMatcher(), otherOptions)) {
                    throw new ParsingException(parser.getTokenLocation(), "Unexpected token " + token + " ["
                            + currentFieldName + "] in [" + aggregationName + "].");
                }
            } else if (!token(aggregationName, currentFieldName, token, parser, context.getParseFieldMatcher(),
                    otherOptions)) {
                throw new ParsingException(parser.getTokenLocation(), "Unexpected token " + token + " ["
                        + currentFieldName + "] in [" + aggregationName + "].");
            }
        } else if (scriptable && token == XContentParser.Token.START_OBJECT) {
            if (context.getParseFieldMatcher().match(currentFieldName, ScriptField.SCRIPT)) {
                script = Script.parse(parser, context.getParseFieldMatcher());
            } else if (!token(aggregationName, currentFieldName, token, parser, context.getParseFieldMatcher(),
                    otherOptions)) {
                throw new ParsingException(parser.getTokenLocation(), "Unexpected token " + token + " ["
                        + currentFieldName + "] in [" + aggregationName + "].");
            }
        } else if (!token(aggregationName, currentFieldName, token, parser, context.getParseFieldMatcher(),
                otherOptions)) {
            throw new ParsingException(parser.getTokenLocation(),
                    "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName + "].");
        }
    }

    ValuesSourceAggregationBuilder<VS, ?> factory = createFactory(aggregationName, this.valuesSourceType,
            this.targetValueType, otherOptions);
    if (field != null) {
        factory.field(field);
    }
    if (script != null) {
        factory.script(script);
    }
    if (valueType != null) {
        factory.valueType(valueType);
    }
    if (format != null) {
        factory.format(format);
    }
    if (missing != null) {
        factory.missing(missing);
    }
    if (timezone != null) {
        factory.timeZone(timezone);
    }
    return factory;
}

From source file:org.elasticsearch.search.aggregations.support.ValuesSourceParser.java

License:Apache License

public boolean token(String currentFieldName, XContentParser.Token token, XContentParser parser)
        throws IOException {
    if ("missing".equals(currentFieldName) && token.isValue()) {
        input.missing = parser.objectText();
        return true;
    }/*from w  ww.j  av  a  2  s .c o m*/
    if (token == XContentParser.Token.VALUE_STRING) {
        if ("field".equals(currentFieldName)) {
            input.field = parser.text();
        } else if (formattable && "format".equals(currentFieldName)) {
            input.format = parser.text();
        } else if (timezoneAware && context.parseFieldMatcher().match(currentFieldName, TIME_ZONE)) {
            input.timezone = DateTimeZone.forID(parser.text());
        } else if (scriptable) {
            if ("value_type".equals(currentFieldName) || "valueType".equals(currentFieldName)) {
                input.valueType = ValueType.resolveForScript(parser.text());
                if (targetValueType != null && input.valueType.isNotA(targetValueType)) {
                    throw new SearchParseException(context,
                            aggType.name() + " aggregation [" + aggName
                                    + "] was configured with an incompatible value type [" + input.valueType
                                    + "]. [" + aggType + "] aggregation can only work on value of type ["
                                    + targetValueType + "]",
                            parser.getTokenLocation());
                }
            } else if (!scriptParameterParser.token(currentFieldName, token, parser,
                    context.parseFieldMatcher())) {
                return false;
            }
            return true;
        } else {
            return false;
        }
        return true;
    }
    if (token == XContentParser.Token.VALUE_NUMBER) {
        if (timezoneAware && context.parseFieldMatcher().match(currentFieldName, TIME_ZONE)) {
            input.timezone = DateTimeZone.forOffsetHours(parser.intValue());
        } else {
            return false;
        }
        return true;
    }
    if (scriptable && token == XContentParser.Token.START_OBJECT) {
        if (context.parseFieldMatcher().match(currentFieldName, ScriptField.SCRIPT)) {
            input.script = Script.parse(parser, context.parseFieldMatcher());
            return true;
        } else if ("params".equals(currentFieldName)) {
            input.params = parser.map();
            return true;
        }
        return false;
    }

    return false;
}

From source file:org.elasticsearch.search.aggregations.support.ValuesSourceParserHelper.java

License:Apache License

private static <VS extends ValuesSource> void declareFields(
        ObjectParser<? extends ValuesSourceAggregationBuilder<VS, ?>, QueryParseContext> objectParser,
        boolean scriptable, boolean formattable, boolean timezoneAware, ValueType targetValueType) {

    objectParser.declareField(ValuesSourceAggregationBuilder::field, XContentParser::text,
            new ParseField("field"), ObjectParser.ValueType.STRING);

    objectParser.declareField(ValuesSourceAggregationBuilder::missing, XContentParser::objectText,
            new ParseField("missing"), ObjectParser.ValueType.VALUE);

    objectParser.declareField(ValuesSourceAggregationBuilder::valueType, p -> {
        ValueType valueType = ValueType.resolveForScript(p.text());
        if (targetValueType != null && valueType.isNotA(targetValueType)) {
            throw new ParsingException(p.getTokenLocation(),
                    "Aggregation [" + objectParser.getName()
                            + "] was configured with an incompatible value type [" + valueType
                            + "]. It can only work on value of type [" + targetValueType + "]");
        }/*from   www.  java  2 s .c  o  m*/
        return valueType;
    }, new ParseField("value_type", "valueType"), ObjectParser.ValueType.STRING);

    if (formattable) {
        objectParser.declareField(ValuesSourceAggregationBuilder::format, XContentParser::text,
                new ParseField("format"), ObjectParser.ValueType.STRING);
    }

    if (scriptable) {
        objectParser.declareField(ValuesSourceAggregationBuilder::script,
                (parser, context) -> Script.parse(parser), Script.SCRIPT_PARSE_FIELD,
                ObjectParser.ValueType.OBJECT_OR_STRING);
    }

    if (timezoneAware) {
        objectParser.declareField(ValuesSourceAggregationBuilder::timeZone, p -> {
            if (p.currentToken() == XContentParser.Token.VALUE_STRING) {
                return DateTimeZone.forID(p.text());
            } else {
                return DateTimeZone.forOffsetHours(p.intValue());
            }
        }, TIME_ZONE, ObjectParser.ValueType.LONG);
    }
}

From source file:org.elasticsearch.search.facet.datehistogram.DateHistogramFacetParser.java

License:Apache License

private DateTimeZone parseZone(XContentParser parser, XContentParser.Token token) throws IOException {
    if (token == XContentParser.Token.VALUE_NUMBER) {
        return DateTimeZone.forOffsetHours(parser.intValue());
    } else {/*w w w  .  jav a2s  .  c  om*/
        String text = parser.text();
        int index = text.indexOf(':');
        if (index != -1) {
            int beginIndex = text.charAt(0) == '+' ? 1 : 0;
            // format like -02:30
            return DateTimeZone.forOffsetHoursMinutes(Integer.parseInt(text.substring(beginIndex, index)),
                    Integer.parseInt(text.substring(index + 1)));
        } else {
            // id, listed here: http://joda-time.sourceforge.net/timezones.html
            return DateTimeZone.forID(text);
        }
    }
}

From source file:org.elasticsearch.test.ESIntegTestCase.java

License:Apache License

/**
 * Returns a random JODA Time Zone based on Java Time Zones
 *///from   ww w.  jav  a  2  s .  c o m
public static DateTimeZone randomDateTimeZone() {
    DateTimeZone timeZone;

    // It sounds like some Java Time Zones are unknown by JODA. For example: Asia/Riyadh88
    // We need to fallback in that case to a known time zone
    try {
        timeZone = DateTimeZone.forTimeZone(RandomizedTest.randomTimeZone());
    } catch (IllegalArgumentException e) {
        timeZone = DateTimeZone.forOffsetHours(randomIntBetween(-12, 12));
    }

    return timeZone;
}

From source file:org.elasticsearch.xpack.core.rollup.job.DateHistogramGroupConfig.java

License:Open Source License

private static DateTimeZone toDateTimeZone(final String timezone) {
    try {/*from w  w  w.  j av a2 s  .  c  o  m*/
        return DateTimeZone.forOffsetHours(Integer.parseInt(timezone));
    } catch (NumberFormatException e) {
        return DateTimeZone.forID(timezone);
    }
}

From source file:org.envirocar.analyse.categories.DEBasedCategory.java

License:Apache License

@Override
public void updateTimeZone(DateTime trackTime) {
    int moy = trackTime.getMonthOfYear();
    String utcOffset;/* w ww.j ava2  s.  c  o m*/

    if (moy > 3 && moy < 10) {
        utcOffset = "+02:00";
    } else if (moy < 3 || moy > 10) {
        utcOffset = "+01:00";
    }

    else if (moy == 3) {
        DateTime lastSundayOfMarch = new DateTime(getLastSundayOfMarch(trackTime.getYear()),
                DateTimeZone.forOffsetHours(1)).plusHours(1);
        logger.info("lastSundayOfMarch: " + lastSundayOfMarch.toString());
        logger.info("trackTime: " + trackTime.toString());
        if (trackTime.isBefore(lastSundayOfMarch)) {
            utcOffset = "+01:00";
        } else {
            utcOffset = "+02:00";
        }
    } else if (moy == 10) {
        DateTime lastSundayOfMarch = new DateTime(getLastSundayOfOctober(trackTime.getYear()),
                DateTimeZone.forOffsetHours(2)).plusHours(3);
        if (trackTime.isBefore(lastSundayOfMarch)) {
            utcOffset = "+02:00";
        } else {
            utcOffset = "+01:00";
        }
    } else {
        utcOffset = "+01:00";
    }

    this.timeZone = DateTimeZone.forID(utcOffset);
}

From source file:org.modeshape.graph.property.basic.JodaDateTime.java

License:Open Source License

public JodaDateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour,
        int secondOfMinute, int millisecondsOfSecond, int timeZoneOffsetHours) {
    this.instance = new DateTime(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute,
            millisecondsOfSecond, DateTimeZone.forOffsetHours(timeZoneOffsetHours));
    this.millisInUtc = instance.withZone(UTC_ZONE).getMillis();
}