Search in sources :

Example 41 with XContentParseException

use of org.opensearch.common.xcontent.XContentParseException in project anomaly-detection by opensearch-project.

the class AnomalyDetector method parse.

/**
 * Parse raw json content and given detector id into anomaly detector instance.
 *
 * @param parser                      json based content parser
 * @param detectorId                  detector id
 * @param version                     detector document version
 * @param defaultDetectionInterval    default detection interval
 * @param defaultDetectionWindowDelay default detection window delay
 * @return anomaly detector instance
 * @throws IOException IOException if content can't be parsed correctly
 */
public static AnomalyDetector parse(XContentParser parser, String detectorId, Long version, TimeValue defaultDetectionInterval, TimeValue defaultDetectionWindowDelay) throws IOException {
    String name = null;
    String description = "";
    String timeField = null;
    List<String> indices = new ArrayList<String>();
    QueryBuilder filterQuery = QueryBuilders.matchAllQuery();
    TimeConfiguration detectionInterval = defaultDetectionInterval == null ? null : new IntervalTimeConfiguration(defaultDetectionInterval.getMinutes(), ChronoUnit.MINUTES);
    TimeConfiguration windowDelay = defaultDetectionWindowDelay == null ? null : new IntervalTimeConfiguration(defaultDetectionWindowDelay.getSeconds(), ChronoUnit.SECONDS);
    Integer shingleSize = null;
    List<Feature> features = new ArrayList<>();
    Integer schemaVersion = CommonValue.NO_SCHEMA_VERSION;
    Map<String, Object> uiMetadata = null;
    Instant lastUpdateTime = null;
    User user = null;
    DetectionDateRange detectionDateRange = null;
    String resultIndex = null;
    List<String> categoryField = null;
    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser);
    while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
        String fieldName = parser.currentName();
        parser.nextToken();
        switch(fieldName) {
            case NAME_FIELD:
                name = parser.text();
                break;
            case DESCRIPTION_FIELD:
                description = parser.text();
                break;
            case TIMEFIELD_FIELD:
                timeField = parser.text();
                break;
            case INDICES_FIELD:
                ensureExpectedToken(XContentParser.Token.START_ARRAY, parser.currentToken(), parser);
                while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                    indices.add(parser.text());
                }
                break;
            case UI_METADATA_FIELD:
                uiMetadata = parser.map();
                break;
            case CommonName.SCHEMA_VERSION_FIELD:
                schemaVersion = parser.intValue();
                break;
            case FILTER_QUERY_FIELD:
                ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser);
                try {
                    filterQuery = parseInnerQueryBuilder(parser);
                } catch (ParsingException | XContentParseException e) {
                    throw new ADValidationException("Custom query error in data filter: " + e.getMessage(), DetectorValidationIssueType.FILTER_QUERY, ValidationAspect.DETECTOR);
                } catch (IllegalArgumentException e) {
                    if (!e.getMessage().contains("empty clause")) {
                        throw e;
                    }
                }
                break;
            case DETECTION_INTERVAL_FIELD:
                try {
                    detectionInterval = TimeConfiguration.parse(parser);
                } catch (Exception e) {
                    if (e instanceof IllegalArgumentException && e.getMessage().contains(CommonErrorMessages.NEGATIVE_TIME_CONFIGURATION)) {
                        throw new ADValidationException("Detection interval must be a positive integer", DetectorValidationIssueType.DETECTION_INTERVAL, ValidationAspect.DETECTOR);
                    }
                    throw e;
                }
                break;
            case FEATURE_ATTRIBUTES_FIELD:
                try {
                    ensureExpectedToken(XContentParser.Token.START_ARRAY, parser.currentToken(), parser);
                    while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                        features.add(Feature.parse(parser));
                    }
                } catch (Exception e) {
                    if (e instanceof ParsingException || e instanceof XContentParseException) {
                        throw new ADValidationException("Custom query error: " + e.getMessage(), DetectorValidationIssueType.FEATURE_ATTRIBUTES, ValidationAspect.DETECTOR);
                    }
                    throw e;
                }
                break;
            case WINDOW_DELAY_FIELD:
                try {
                    windowDelay = TimeConfiguration.parse(parser);
                } catch (Exception e) {
                    if (e instanceof IllegalArgumentException && e.getMessage().contains(CommonErrorMessages.NEGATIVE_TIME_CONFIGURATION)) {
                        throw new ADValidationException("Window delay interval must be a positive integer", DetectorValidationIssueType.WINDOW_DELAY, ValidationAspect.DETECTOR);
                    }
                    throw e;
                }
                break;
            case SHINGLE_SIZE_FIELD:
                shingleSize = parser.intValue();
                break;
            case LAST_UPDATE_TIME_FIELD:
                lastUpdateTime = ParseUtils.toInstant(parser);
                break;
            case CATEGORY_FIELD:
                categoryField = (List) parser.list();
                break;
            case USER_FIELD:
                user = User.parse(parser);
                break;
            case DETECTION_DATE_RANGE_FIELD:
                detectionDateRange = DetectionDateRange.parse(parser);
                break;
            case RESULT_INDEX_FIELD:
                resultIndex = parser.text();
                break;
            default:
                parser.skipChildren();
                break;
        }
    }
    AnomalyDetector detector = new AnomalyDetector(detectorId, version, name, description, timeField, indices, features, filterQuery, detectionInterval, windowDelay, getShingleSize(shingleSize), uiMetadata, schemaVersion, lastUpdateTime, categoryField, user, resultIndex);
    detector.setDetectionDateRange(detectionDateRange);
    return detector;
}
Also used : User(org.opensearch.commons.authuser.User) Instant(java.time.Instant) ArrayList(java.util.ArrayList) AbstractQueryBuilder.parseInnerQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder) QueryBuilder(org.opensearch.index.query.QueryBuilder) ParsingException(org.opensearch.common.ParsingException) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) IOException(java.io.IOException) XContentParseException(org.opensearch.common.xcontent.XContentParseException) ParsingException(org.opensearch.common.ParsingException) ToXContentObject(org.opensearch.common.xcontent.ToXContentObject) ADValidationException(org.opensearch.ad.common.exception.ADValidationException) XContentParseException(org.opensearch.common.xcontent.XContentParseException)

Aggregations

XContentParseException (org.opensearch.common.xcontent.XContentParseException)41 XContentParser (org.opensearch.common.xcontent.XContentParser)32 Matchers.containsString (org.hamcrest.Matchers.containsString)11 XContentType (org.opensearch.common.xcontent.XContentType)8 BytesReference (org.opensearch.common.bytes.BytesReference)7 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)5 ParsingException (org.opensearch.common.ParsingException)4 CategoryContextMapping (org.opensearch.search.suggest.completion.context.CategoryContextMapping)4 IOException (java.io.IOException)3 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)2 HasAttributeNodeSelector (org.opensearch.client.HasAttributeNodeSelector)2 Node (org.opensearch.client.Node)2 NodeSelector (org.opensearch.client.NodeSelector)2 InputStream (java.io.InputStream)1 Instant (java.time.Instant)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 ContentTooLongException (org.apache.http.ContentTooLongException)1 HttpEntity (org.apache.http.HttpEntity)1 LegacyESVersion (org.opensearch.LegacyESVersion)1