Example usage for org.joda.time DateTimeZone forID

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

Introduction

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

Prototype

@FromString
public static DateTimeZone forID(String id) 

Source Link

Document

Gets a time zone instance for the specified time zone id.

Usage

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 + "]");
        }/*ww  w  .ja  va 2  s.  co  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 {//from   w ww  .j av  a  2 s .com
        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.ESTestCase.java

License:Apache License

/**
 * generate a random DateTimeZone from the ones available in joda library
 *//*from w w  w  .j  a va2  s. c o  m*/
public static DateTimeZone randomDateTimeZone() {
    List<String> ids = new ArrayList<>(DateTimeZone.getAvailableIDs());
    Collections.sort(ids);
    return DateTimeZone.forID(randomFrom(ids));
}

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 ww.  j a  v  a  2s  . c o m
        return DateTimeZone.forOffsetHours(Integer.parseInt(timezone));
    } catch (NumberFormatException e) {
        return DateTimeZone.forID(timezone);
    }
}

From source file:org.elasticsearch.xpack.watcher.actions.index.IndexAction.java

License:Open Source License

public static IndexAction parse(String watchId, String actionId, XContentParser parser) throws IOException {
    String index = null;/*ww  w.j a va2 s  .c om*/
    String docType = null;
    String docId = null;
    String executionTimeField = null;
    TimeValue timeout = null;
    DateTimeZone dynamicNameTimeZone = null;
    RefreshPolicy refreshPolicy = null;

    String currentFieldName = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (Field.INDEX.match(currentFieldName, parser.getDeprecationHandler())) {
            try {
                index = parser.text();
            } catch (ElasticsearchParseException pe) {
                throw new ElasticsearchParseException(
                        "could not parse [{}] action [{}/{}]. failed to parse index name value for "
                                + "field [{}]",
                        pe, TYPE, watchId, actionId, currentFieldName);
            }
        } else if (token == XContentParser.Token.VALUE_NUMBER) {
            if (Field.TIMEOUT.match(currentFieldName, parser.getDeprecationHandler())) {
                timeout = timeValueMillis(parser.longValue());
            } else {
                throw new ElasticsearchParseException(
                        "could not parse [{}] action [{}/{}]. unexpected number field [{}]", TYPE, watchId,
                        actionId, currentFieldName);
            }
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if (Field.DOC_TYPE.match(currentFieldName, parser.getDeprecationHandler())) {
                docType = parser.text();
            } else if (Field.DOC_ID.match(currentFieldName, parser.getDeprecationHandler())) {
                docId = parser.text();
            } else if (Field.EXECUTION_TIME_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                executionTimeField = parser.text();
            } else if (Field.TIMEOUT_HUMAN.match(currentFieldName, parser.getDeprecationHandler())) {
                // Parser for human specified timeouts and 2.x compatibility
                timeout = WatcherDateTimeUtils.parseTimeValue(parser, Field.TIMEOUT_HUMAN.toString());
            } else if (Field.DYNAMIC_NAME_TIMEZONE.match(currentFieldName, parser.getDeprecationHandler())) {
                if (token == XContentParser.Token.VALUE_STRING) {
                    dynamicNameTimeZone = DateTimeZone.forID(parser.text());
                } else {
                    throw new ElasticsearchParseException(
                            "could not parse [{}] action for watch [{}]. failed to parse [{}]. must be "
                                    + "a string value (e.g. 'UTC' or '+01:00').",
                            TYPE, watchId, currentFieldName);
                }
            } else if (Field.REFRESH.match(currentFieldName, parser.getDeprecationHandler())) {
                refreshPolicy = RefreshPolicy.parse(parser.text());
            } else {
                throw new ElasticsearchParseException(
                        "could not parse [{}] action [{}/{}]. unexpected string field [{}]", TYPE, watchId,
                        actionId, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException("could not parse [{}] action [{}/{}]. unexpected token [{}]",
                    TYPE, watchId, actionId, token);
        }
    }

    return new IndexAction(index, docType, docId, executionTimeField, timeout, dynamicNameTimeZone,
            refreshPolicy);
}

From source file:org.elasticsearch.xpack.watcher.input.search.SearchInput.java

License:Open Source License

public static SearchInput parse(String watchId, XContentParser parser) throws IOException {
    WatcherSearchTemplateRequest request = null;
    Set<String> extract = null;
    TimeValue timeout = null;// w w w  .ja  va  2 s.c o m
    DateTimeZone dynamicNameTimeZone = null;

    String currentFieldName = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (Field.REQUEST.match(currentFieldName, parser.getDeprecationHandler())) {
            try {
                request = WatcherSearchTemplateRequest.fromXContent(parser,
                        ExecutableSearchInput.DEFAULT_SEARCH_TYPE);
            } catch (ElasticsearchParseException srpe) {
                throw new ElasticsearchParseException(
                        "could not parse [{}] input for watch [{}]. failed to parse [{}]", srpe, TYPE, watchId,
                        currentFieldName);
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            if (Field.EXTRACT.match(currentFieldName, parser.getDeprecationHandler())) {
                extract = new HashSet<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    if (token == XContentParser.Token.VALUE_STRING) {
                        extract.add(parser.text());
                    } else {
                        throw new ElasticsearchParseException(
                                "could not parse [{}] input for watch [{}]. expected a string value in "
                                        + "[{}] array, but found [{}] instead",
                                TYPE, watchId, currentFieldName, token);
                    }
                }
            } else {
                throw new ElasticsearchParseException(
                        "could not parse [{}] input for watch [{}]. unexpected array field [{}]", TYPE, watchId,
                        currentFieldName);
            }
        } else if (Field.TIMEOUT.match(currentFieldName, parser.getDeprecationHandler())) {
            timeout = timeValueMillis(parser.longValue());
        } else if (Field.TIMEOUT_HUMAN.match(currentFieldName, parser.getDeprecationHandler())) {
            // Parser for human specified timeouts and 2.x compatibility
            timeout = WatcherDateTimeUtils.parseTimeValue(parser, Field.TIMEOUT_HUMAN.toString());
        } else if (Field.DYNAMIC_NAME_TIMEZONE.match(currentFieldName, parser.getDeprecationHandler())) {
            if (token == XContentParser.Token.VALUE_STRING) {
                dynamicNameTimeZone = DateTimeZone.forID(parser.text());
            } else {
                throw new ElasticsearchParseException(
                        "could not parse [{}] input for watch [{}]. failed to parse [{}]. must be a "
                                + "string value (e.g. 'UTC' or '+01:00').",
                        TYPE, watchId, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException(
                    "could not parse [{}] input for watch [{}]. unexpected token [{}]", TYPE, watchId, token);
        }
    }

    if (request == null) {
        throw new ElasticsearchParseException(
                "could not parse [{}] input for watch [{}]. missing required [{}] field", TYPE, watchId,
                Field.REQUEST.getPreferredName());
    }
    return new SearchInput(request, extract, timeout, dynamicNameTimeZone);
}

From source file:org.elasticsearch.xpack.watcher.transform.search.SearchTransform.java

License:Open Source License

public static SearchTransform parse(String watchId, XContentParser parser) throws IOException {
    WatcherSearchTemplateRequest request = null;
    TimeValue timeout = null;/*  www.j a v a2 s  . c  o  m*/
    DateTimeZone dynamicNameTimeZone = null;

    String currentFieldName = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (Field.REQUEST.match(currentFieldName, parser.getDeprecationHandler())) {
            try {
                request = WatcherSearchTemplateRequest.fromXContent(parser,
                        ExecutableSearchTransform.DEFAULT_SEARCH_TYPE);
            } catch (ElasticsearchParseException srpe) {
                throw new ElasticsearchParseException(
                        "could not parse [{}] transform for watch [{}]. failed to parse [{}]", srpe, TYPE,
                        watchId, currentFieldName);
            }
        } else if (Field.TIMEOUT.match(currentFieldName, parser.getDeprecationHandler())) {
            timeout = timeValueMillis(parser.longValue());
        } else if (Field.TIMEOUT_HUMAN.match(currentFieldName, parser.getDeprecationHandler())) {
            // Parser for human specified timeouts and 2.x compatibility
            timeout = WatcherDateTimeUtils.parseTimeValue(parser, Field.TIMEOUT_HUMAN.toString());
        } else if (Field.DYNAMIC_NAME_TIMEZONE.match(currentFieldName, parser.getDeprecationHandler())) {
            if (token == XContentParser.Token.VALUE_STRING) {
                dynamicNameTimeZone = DateTimeZone.forID(parser.text());
            } else {
                throw new ElasticsearchParseException(
                        "could not parse [{}] transform for watch [{}]. failed to parse [{}]. must be a"
                                + " string value (e.g. 'UTC' or '+01:00').",
                        TYPE, watchId, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException(
                    "could not parse [{}] transform for watch [{}]. unexpected field [{}]", TYPE, watchId,
                    currentFieldName);
        }
    }

    if (request == null) {
        throw new ElasticsearchParseException(
                "could not parse [{}] transform for watch [{}]. missing required [{}] field", TYPE, watchId,
                Field.REQUEST.getPreferredName());
    }
    return new SearchTransform(request, timeout, dynamicNameTimeZone);
}

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

License:Apache License

@Override
public void updateTimeZone(DateTime trackTime) {
    int moy = trackTime.getMonthOfYear();
    String utcOffset;// ww  w .  j a v  a 2 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.fao.geonet.api.harvesting.HarvestersApi.java

License:Open Source License

@ApiOperation(value = "Assign harvester records to a new source", notes = "", authorizations = {
        @Authorization(value = "basicAuth") }, nickname = "assignHarvestedRecordToSource")
@RequestMapping(value = "/{harvesterUuid}/assign", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@PreAuthorize("hasRole('UserAdmin')")
@ApiResponses(value = { @ApiResponse(code = 204, message = "Harvester records transfered to new source."),
        @ApiResponse(code = 404, message = ApiParams.API_RESPONSE_RESOURCE_NOT_FOUND),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_USER_ADMIN) })
@ResponseBody/*from   w w w  . j  a v a2  s . c  om*/
public HttpEntity<HttpStatus> assignHarvestedRecordToSource(
        @ApiParam(value = "The harvester UUID") @PathVariable String harvesterUuid,
        @ApiParam(value = "The target source UUID") @RequestParam String source, HttpServletRequest request)
        throws Exception {
    final long elapsedTime = System.currentTimeMillis();
    final ApplicationContext applicationContext = ApplicationContextHolder.get();
    final AbstractHarvester harvester = harvestManager.getHarvester(harvesterUuid);
    if (harvester == null) {
        throw new ResourceNotFoundException(
                String.format("Harvester with UUID '%s' not found. Cannot assign new source.", harvesterUuid));
    }

    final Source sourceNode = sourceRepository.findOneByUuid(source);
    if (sourceNode == null) {
        throw new ResourceNotFoundException(String
                .format("Source with UUID '%s' not found. Cannot assign source to harvester records.", source));
    }

    final List<? extends AbstractMetadata> allHarvestedRecords = metadataRepository
            .findAllByHarvestInfo_Uuid(harvesterUuid);
    List<String> records = new ArrayList<>(allHarvestedRecords.size());

    if (allHarvestedRecords.size() < 1) {
        throw new NoResultsFoundException(String.format(
                "Harvester with UUID '%s' has no record to assign to source '%s'.", harvesterUuid, source));
    }

    for (AbstractMetadata record : allHarvestedRecords) {
        record.getSourceInfo().setSourceId(source);
        record.getHarvestInfo().setHarvested(false).setUri(null).setUuid(null);
        metadataManager.save(record);
        records.add(record.getId() + "");
    }

    dataManager.indexMetadata(records);

    // Add an harvester history step
    Element historyEl = new Element("result");
    historyEl.addContent(new Element("cleared").setAttribute("recordsTransfered", records.size() + ""));
    final String lastRun = new DateTime().withZone(DateTimeZone.forID("UTC")).toString();
    final ISODate lastRunDate = new ISODate(lastRun);

    HarvestHistory history = new HarvestHistory();
    history.setDeleted(true);
    history.setElapsedTime((int) elapsedTime);
    history.setHarvestDate(lastRunDate);
    history.setHarvesterName(harvester.getParams().getName());
    history.setHarvesterType(harvester.getType());
    history.setHarvesterUuid(harvester.getParams().getUuid());
    history.setInfo(historyEl);
    history.setParams(harvester.getParams().getNodeElement());
    historyRepository.save(history);

    return new HttpEntity<>(HttpStatus.NO_CONTENT);
}

From source file:org.fao.geonet.domain.ISODate.java

License:Open Source License

public static String parseISODateTimes(String input1, String input2) {
    DateTimeFormatter dto = ISODateTimeFormat.dateTime();
    PeriodFormatter p = ISOPeriodFormat.standard();
    DateTime odt1;//from   w  ww. java  2 s.  c om
    String odt = "";

    // input1 should be some sort of ISO time
    // eg. basic: 20080909, full: 2008-09-09T12:21:00 etc
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        DateTime idt = parseBasicOrFullDateTime(input1);
        odt1 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
        odt = odt1.toString();

    } catch (Exception e) {
        Log.error("geonetwork.domain", "Error parsing ISO DateTimes, error: " + e.getMessage(), e);
        return DEFAULT_DATE_TIME;
    }

    if (input2 == null || input2.equals(""))
        return odt;

    // input2 can be an ISO time as for input1 but also an ISO time period
    // eg. -P3D or P3D - if an ISO time period then it must be added to the
    // DateTime generated for input1 (odt1)
    // convert everything to UTC so that we remove any timezone
    // problems
    try {
        boolean minus = false;
        if (input2.startsWith("-P")) {
            input2 = input2.substring(1);
            minus = true;
        }

        if (input2.startsWith("P")) {
            Period ip = p.parsePeriod(input2);
            DateTime odt2;
            if (!minus)
                odt2 = odt1.plus(ip.toStandardDuration().getMillis());
            else
                odt2 = odt1.minus(ip.toStandardDuration().getMillis());
            odt = odt + "|" + odt2.toString();
        } else {
            DateTime idt = parseBasicOrFullDateTime(input2);
            DateTime odt2 = dto.parseDateTime(idt.toString()).withZone(DateTimeZone.forID("UTC"));
            odt = odt + "|" + odt2.toString();
        }
    } catch (Exception e) {
        Log.error("geonetwork.domain", "Error parsing ISO DateTimes, error: " + e.getMessage(), e);
        return odt + "|" + DEFAULT_DATE_TIME;
    }

    return odt;
}