Java Code Examples for org.elasticsearch.rest.RestRequest#hasParam()

The following examples show how to use org.elasticsearch.rest.RestRequest#hasParam() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TasteActionRestAction.java    From elasticsearch-taste with Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request,
        final RestChannel channel, final Map<String, Object> params,
        final boolean acknowledged) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        if (request.hasParam("pretty")) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", acknowledged);
        if (params != null) {
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                builder.field(entry.getKey(), entry.getValue());
            }
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final Exception e) {
        sendErrorResponse(channel, e);
    }
}
 
Example 2
Source File: ReindexRestAction.java    From elasticsearch-reindexing with Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request,
        final RestChannel channel, final Map<String, Object> params) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        if (request.hasParam("pretty")) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", true);
        if (params != null) {
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                builder.field(entry.getKey(), entry.getValue());
            }
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final Exception e) {
        sendErrorResponse(channel, e);
    }
}
 
Example 3
Source File: FeatureStoreBaseRestHandler.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
protected String indexName(RestRequest request) {
    if (request.hasParam("store")) {
        return IndexFeatureStore.STORE_PREFIX + request.param("store");
    } else {
        return IndexFeatureStore.DEFAULT_STORE;
    }
}
 
Example 4
Source File: RestExtendedAnalyzeAction.java    From elasticsearch-extended-analyze with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String[] text = request.paramAsStringArrayOrEmptyIfAll("text");

    ExtendedAnalyzeRequest analyzeRequest = new ExtendedAnalyzeRequest(request.param("index"));
    analyzeRequest.text(text);
    analyzeRequest.analyzer(request.param("analyzer"));
    analyzeRequest.field(request.param("field"));
    analyzeRequest.tokenizer(request.param("tokenizer"));
    analyzeRequest.tokenFilters(request.paramAsStringArray("token_filters", request.paramAsStringArray("filters", analyzeRequest.tokenFilters())));
    analyzeRequest.charFilters(request.paramAsStringArray("char_filters", analyzeRequest.charFilters()));
    analyzeRequest.attributes(request.paramAsStringArray("attributes", null));
    analyzeRequest.shortAttributeName(request.paramAsBoolean("use_short_attr", false));

    if (request.hasContent() || request.hasParam("source")) {
        XContentType type = guessBodyContentType(request);
        if (type == null) {
            if (text == null || text.length == 0) {
                text = new String[]{ RestActions.getRestContent(request).toUtf8()};
                analyzeRequest.text(text);
            }
        } else {
            buildFromContent(RestActions.getRestContent(request), analyzeRequest);
        }
    }

    client.admin().indices().execute(ExtendedAnalyzeAction.INSTANCE, analyzeRequest, new RestToXContentListener<ExtendedAnalyzeResponse>(channel));
}
 
Example 5
Source File: XlsContent.java    From elasticsearch-dataformat with Apache License 2.0 5 votes vote down vote up
public XlsContent(final Client client, final RestRequest request, final ContentType contentType, final boolean isExcel2007) {
    super(client, request, contentType);

    appendHeader = request.paramAsBoolean("append.header", true);
    String fieldsName = "fields_name";
    if (request.hasParam("fl")) {
        fieldsName = "fl";
    }
    final String[] fields = request.paramAsStringArray(fieldsName,
            StringUtils.EMPTY_STRINGS);
    if (fields.length == 0) {
        headerSet = new LinkedHashSet<>();
        modifiableFieldSet = true;
    } else {
        final Set<String> fieldSet = new LinkedHashSet<>();
        for (final String field : fields) {
            fieldSet.add(field.trim());
        }
        headerSet = Collections.unmodifiableSet(fieldSet);
        modifiableFieldSet = false;
    }

    this.isExcel2007 = isExcel2007;

    if (logger.isDebugEnabled()) {
        logger.debug("appendHeader: {}, headerSet: {}, isExcel2007: {}",
                appendHeader, headerSet, isExcel2007);
    }
}
 
Example 6
Source File: RestAddFeatureToSet.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    String store = indexName(request);
    String setName = request.param("name");
    String routing = request.param("routing");
    String featureQuery = null;
    List<StoredFeature> features = null;
    boolean merge = request.paramAsBoolean("merge", false);
    if (request.hasParam("query")) {
        featureQuery = request.param("query");
    }
    FeatureValidation validation = null;
    if (request.hasContentOrSourceParam()) {
        FeaturesParserState featuresParser = new FeaturesParserState();
        request.applyContentParser(featuresParser::parse);
        features = featuresParser.features;
        validation = featuresParser.validation;
    }
    if (featureQuery == null && (features == null || features.isEmpty())) {
        throw new IllegalArgumentException("features must be provided as a query for the feature store " +
                "or in the body, none provided");
    }

    if (featureQuery != null && (features != null && !features.isEmpty())) {
        throw new IllegalArgumentException("features must be provided as a query for the feature store " +
                "or directly in the body not both");
    }

    AddFeaturesToSetRequestBuilder builder = new AddFeaturesToSetRequestBuilder(client);
    builder.request().setStore(store);
    builder.request().setFeatureSet(setName);
    builder.request().setFeatureNameQuery(featureQuery);
    builder.request().setRouting(routing);
    builder.request().setFeatures(features);
    builder.request().setMerge(merge);
    builder.request().setValidation(validation);
    return (channel) -> builder.execute(new RestStatusToXContentListener<>(channel, (r) -> r.getResponse().getLocation(routing)));
}
 
Example 7
Source File: RestAnomalyDetectorJobAction.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (!EnabledSetting.isADPluginEnabled()) {
        throw new IllegalStateException(CommonErrorMessages.DISABLED_ERR_MSG);
    }

    String detectorId = request.param(DETECTOR_ID);

    return channel -> {
        long seqNo = request.paramAsLong(IF_SEQ_NO, SequenceNumbers.UNASSIGNED_SEQ_NO);
        long primaryTerm = request.paramAsLong(IF_PRIMARY_TERM, SequenceNumbers.UNASSIGNED_PRIMARY_TERM);
        WriteRequest.RefreshPolicy refreshPolicy = request.hasParam(REFRESH)
            ? WriteRequest.RefreshPolicy.parse(request.param(REFRESH))
            : WriteRequest.RefreshPolicy.IMMEDIATE;

        IndexAnomalyDetectorJobActionHandler handler = new IndexAnomalyDetectorJobActionHandler(
            clusterService,
            client,
            channel,
            anomalyDetectionIndices,
            detectorId,
            seqNo,
            primaryTerm,
            refreshPolicy,
            requestTimeout
        );

        String rawPath = request.rawPath();

        if (rawPath.endsWith(START_JOB)) {
            handler.startAnomalyDetectorJob();
        } else if (rawPath.endsWith(STOP_JOB)) {
            handler.stopAnomalyDetectorJob(detectorId);
        }
    };
}
 
Example 8
Source File: RestActions.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static long parseVersion(RestRequest request) {
    if (request.hasParam("version")) {
        return request.paramAsLong("version", Versions.MATCH_ANY);
    }
    String ifMatch = request.header("If-Match");
    if (ifMatch != null) {
        return Long.parseLong(ifMatch);
    }
    return Versions.MATCH_ANY;
}
 
Example 9
Source File: RestIndexAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (!EnabledSetting.isADPluginEnabled()) {
        throw new IllegalStateException(CommonErrorMessages.DISABLED_ERR_MSG);
    }

    String detectorId = request.param(DETECTOR_ID, AnomalyDetector.NO_ID);
    logger.info("AnomalyDetector {} action for detectorId {}", request.method(), detectorId);

    XContentParser parser = request.contentParser();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
    // TODO: check detection interval < modelTTL
    AnomalyDetector detector = AnomalyDetector.parse(parser, detectorId, null, detectionInterval, detectionWindowDelay);

    long seqNo = request.paramAsLong(IF_SEQ_NO, SequenceNumbers.UNASSIGNED_SEQ_NO);
    long primaryTerm = request.paramAsLong(IF_PRIMARY_TERM, SequenceNumbers.UNASSIGNED_PRIMARY_TERM);
    WriteRequest.RefreshPolicy refreshPolicy = request.hasParam(REFRESH)
        ? WriteRequest.RefreshPolicy.parse(request.param(REFRESH))
        : WriteRequest.RefreshPolicy.IMMEDIATE;

    return channel -> new IndexAnomalyDetectorActionHandler(
        settings,
        clusterService,
        client,
        channel,
        anomalyDetectionIndices,
        detectorId,
        seqNo,
        primaryTerm,
        refreshPolicy,
        detector,
        requestTimeout,
        maxAnomalyDetectors,
        maxAnomalyFeatures
    ).start();
}
 
Example 10
Source File: RestExecuteAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private AnomalyDetectorExecutionInput getAnomalyDetectorExecutionInput(RestRequest request) throws IOException {
    String detectorId = null;
    if (request.hasParam(DETECTOR_ID)) {
        detectorId = request.param(DETECTOR_ID);
    }

    XContentParser parser = request.contentParser();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
    AnomalyDetectorExecutionInput input = AnomalyDetectorExecutionInput.parse(parser, detectorId);
    if (detectorId != null) {
        input.setDetectorId(detectorId);
    }
    return input;
}
 
Example 11
Source File: RestCreateModelFromSet.java    From elasticsearch-learning-to-rank with Apache License 2.0 4 votes vote down vote up
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    String store = indexName(request);
    Long expectedVersion = null;
    if (request.hasParam("version")) {
        expectedVersion = request.paramAsLong("version", -1);
        if (expectedVersion <= 0) {
            throw new IllegalArgumentException("version must be a strictly positive long value");
        }
    }
    String routing = request.param("routing");
    ParserState state = new ParserState();
    request.withContentOrSourceParamParserOrNull((p) -> ParserState.parse(p, state));
    CreateModelFromSetRequestBuilder builder = new CreateModelFromSetRequestBuilder(client);
    if (expectedVersion != null) {
        builder.withVersion(store, request.param("name"), expectedVersion, state.model.name, state.model.model);
    } else {
        builder.withoutVersion(store, request.param("name"), state.model.name, state.model.model);
    }
    builder.request().setValidation(state.validation);
    builder.routing(routing);
    return (channel) -> builder.execute(ActionListener.wrap(
            response -> new RestStatusToXContentListener<CreateModelFromSetAction.CreateModelFromSetResponse>(channel,
                    (r) -> r.getResponse().getLocation(routing)).onResponse(response),
            (e) -> {
                final Exception exc;
                final RestStatus status;
                if (ExceptionsHelper.unwrap(e, VersionConflictEngineException.class) != null) {
                    exc = new IllegalArgumentException("Element of type [" + StoredLtrModel.TYPE +
                            "] are not updatable, please create a new one instead.");
                    exc.addSuppressed(e);
                    status = RestStatus.METHOD_NOT_ALLOWED;
                } else {
                    exc = e;
                    status = ExceptionsHelper.status(exc);
                }

                try {
                    channel.sendResponse(new BytesRestResponse(channel, status, exc));
                } catch (Exception inner) {
                    inner.addSuppressed(e);
                    logger.error("failed to send failure response", inner);
                }
            }
    ));
}
 
Example 12
Source File: RestActions.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Returns <code>true</code> if either payload or source parameter is present. Otherwise <code>false</code>
 */
public static boolean hasBodyContent(final RestRequest request) {
    return request.hasContent() || request.hasParam("source");
}
 
Example 13
Source File: XmlFilter.java    From elasticsearch-xml with Apache License 2.0 4 votes vote down vote up
private boolean isXml(RestRequest request) {
    return "application/xml".equals(request.header("Accept"))
            || request.hasParam("xml");
}
 
Example 14
Source File: RestUpdateAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
    UpdateRequest updateRequest = new UpdateRequest(request.param("index"), request.param("type"), request.param("id"));
    updateRequest.routing(request.param("routing"));
    updateRequest.parent(request.param("parent"));
    updateRequest.timeout(request.paramAsTime("timeout", updateRequest.timeout()));
    updateRequest.refresh(request.paramAsBoolean("refresh", updateRequest.refresh()));
    String consistencyLevel = request.param("consistency");
    if (consistencyLevel != null) {
        updateRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
    }
    updateRequest.docAsUpsert(request.paramAsBoolean("doc_as_upsert", updateRequest.docAsUpsert()));
    ScriptParameterParser scriptParameterParser = new ScriptParameterParser();
    scriptParameterParser.parseParams(request);
    ScriptParameterValue scriptValue = scriptParameterParser.getDefaultScriptParameterValue();
    if (scriptValue != null) {
        Map<String, Object> scriptParams = new HashMap<>();
        for (Map.Entry<String, String> entry : request.params().entrySet()) {
            if (entry.getKey().startsWith("sp_")) {
                scriptParams.put(entry.getKey().substring(3), entry.getValue());
            }
        }
        updateRequest.script(new Script(scriptValue.script(), scriptValue.scriptType(), scriptParameterParser.lang(), scriptParams));
    }
    String sField = request.param("fields");
    if (sField != null) {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
            updateRequest.fields(sFields);
        }
    }
    updateRequest.retryOnConflict(request.paramAsInt("retry_on_conflict", updateRequest.retryOnConflict()));
    updateRequest.version(RestActions.parseVersion(request));
    updateRequest.versionType(VersionType.fromString(request.param("version_type"), updateRequest.versionType()));


    // see if we have it in the body
    if (request.hasContent()) {
        updateRequest.source(request.content());
        IndexRequest upsertRequest = updateRequest.upsertRequest();
        if (upsertRequest != null) {
            upsertRequest.routing(request.param("routing"));
            upsertRequest.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
            upsertRequest.timestamp(request.param("timestamp"));
            if (request.hasParam("ttl")) {
                upsertRequest.ttl(request.param("ttl"));
            }
            upsertRequest.version(RestActions.parseVersion(request));
            upsertRequest.versionType(VersionType.fromString(request.param("version_type"), upsertRequest.versionType()));
        }
        IndexRequest doc = updateRequest.doc();
        if (doc != null) {
            doc.routing(request.param("routing"));
            doc.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
            doc.timestamp(request.param("timestamp"));
            if (request.hasParam("ttl")) {
                doc.ttl(request.param("ttl"));
            }
            doc.version(RestActions.parseVersion(request));
            doc.versionType(VersionType.fromString(request.param("version_type"), doc.versionType()));
        }
    }

    client.update(updateRequest, new RestBuilderListener<UpdateResponse>(channel) {
        @Override
        public RestResponse buildResponse(UpdateResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            ActionWriteResponse.ShardInfo shardInfo = response.getShardInfo();
            builder.field(Fields._INDEX, response.getIndex())
                    .field(Fields._TYPE, response.getType())
                    .field(Fields._ID, response.getId())
                    .field(Fields._VERSION, response.getVersion());

            shardInfo.toXContent(builder, request);
            if (response.getGetResult() != null) {
                builder.startObject(Fields.GET);
                response.getGetResult().toXContentEmbedded(builder, request);
                builder.endObject();
            }

            builder.endObject();
            RestStatus status = shardInfo.status();
            if (response.isCreated()) {
                status = CREATED;
            }
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example 15
Source File: LoginUserContext.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public LoginUserContext(RestRequest request, ClusterService clusterService) {
    authenticated = false;
    // get username and password
    String auth = request.header("Authorization");
    if (request.param(USERNAME_KEY) != null) {
        loginUsername = request.param(USERNAME_KEY);
        password = request.param(PASSWORD_KEY);
        if (request.hasParam(AUTHENTICATED_KEY)) {
            authenticated = Boolean.parseBoolean(request.param(AUTHENTICATED_KEY));
        }
    } else if ((auth != null) && (auth.length() > BASIC_LENGTH)) {
        auth = auth.substring(BASIC_LENGTH);
        String decodedAuth = new String(Base64.decodeBase64(auth));
        String[] nameAndPass = decodedAuth.split(":");
        if (nameAndPass.length > 0) {
            loginUsername = nameAndPass[0];
        }
        if (nameAndPass.length > 1) {
            password = nameAndPass[1];
        }
    }
    
    if (Strings.isNullOrEmpty(loginUsername)) {
        throw new NoPermissionException(RestStatus.UNAUTHORIZED.getStatus(), "could not parse username from http header or url");
    }
    
    MetaData metaData = clusterService.state().metaData();
    if (UserProperty.getUsernameWithoutTenantFromFullUsername(loginUsername).equalsIgnoreCase(UserProperty.ROOT_NAME)) {
        userProperty = metaData.getUserMetadata().getUserProperties().get(UserProperty.ROOT_NAME);
        UserProperty.Builder userBuilder = new UserProperty.Builder(userProperty);
        userBuilder.changeUsername(UserProperty.ROOT_NAME, UserProperty.getTenantIdFromLoginUserName(loginUsername, metaData.tenantMetadata()));
        userProperty = userBuilder.build();
    } else {
        userProperty = metaData.getUserMetadata().getUserPropertyFromLoginUser(loginUsername, metaData.tenantMetadata());
    }
    if (userProperty == null) {
        throw new NoPermissionException(RestStatus.UNAUTHORIZED.getStatus(), "could not find user " + loginUsername);
    }
    tenantId = userProperty.getTenantId();
    fullUsername = userProperty.getUsernameWithTenant();
    // get sourceAddrs and proxyAddrs
    InetSocketAddress addrs = (InetSocketAddress) request.getRemoteAddress();
    String forwardAddrsList = request.header("X-Forwarded-For");
    if (forwardAddrsList != null && forwardAddrsList.length() > 0) {
        proxyAddrs = addrs.getAddress().getHostAddress();
        sourceAddrs = forwardAddrsList.split(",")[0];
    } else {
        sourceAddrs = addrs.getAddress().getHostAddress();
    }
}
 
Example 16
Source File: CsvContent.java    From elasticsearch-dataformat with Apache License 2.0 4 votes vote down vote up
public CsvContent(final Client client, final RestRequest request, final ContentType contentType) {
    super(client, request, contentType);
    csvConfig = new CsvConfig(
            request.param("csv.separator", ",").charAt(0), request.param(
            "csv.quote", "\"").charAt(0), request.param(
            "csv.escape", "\"").charAt(0));
    csvConfig.setQuoteDisabled(request.paramAsBoolean("csv.quoteDisabled",
            false));
    csvConfig.setEscapeDisabled(request.paramAsBoolean(
            "csv.escapeDisabled", false));
    csvConfig.setNullString(request.param("csv.nullString", ""));
    csvConfig.setIgnoreLeadingWhitespaces(request.paramAsBoolean(
            "csv.ignoreLeadingWhitespaces", true));
    csvConfig.setIgnoreTrailingWhitespaces(request.paramAsBoolean(
            "csv.ignoreTrailingWhitespaces", true));

    appendHeader = request.paramAsBoolean("append.header", true);
    charsetName = request.param("csv.encoding", "UTF-8");

    String fields_name = "fields_name";
    if (request.hasParam("fl")) {
        fields_name = "fl";
    }
    final String[] fields = request.paramAsStringArray(fields_name,
            StringUtils.EMPTY_STRINGS);
    if (fields.length == 0) {
        headerSet = new LinkedHashSet<>();
        modifiableFieldSet = true;
    } else {
        final Set<String> fieldSet = new LinkedHashSet<>();
        for (final String field : fields) {
            fieldSet.add(field.trim());
        }
        headerSet = Collections.unmodifiableSet(fieldSet);
        modifiableFieldSet = false;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("CsvConfig: {}, appendHeader: {}, charsetName: {}, headerSet: {}",
                csvConfig, appendHeader, charsetName, headerSet);
    }
}
 
Example 17
Source File: ClusteringAction.java    From elasticsearch-carrot2 with Apache License 2.0 4 votes vote down vote up
/**
 * Extract and parse HTTP GET parameters for the clustering request.
 */
private void fillFromGetRequest(
    ClusteringActionRequestBuilder actionBuilder,
    RestRequest request) {
   // Use the search query as the query hint, if explicit query hint
   // is not available.
   if (request.hasParam(ClusteringActionRequest.JSON_QUERY_HINT)) {
      actionBuilder.setQueryHint(request.param(ClusteringActionRequest.JSON_QUERY_HINT));
   } else {
      actionBuilder.setQueryHint(request.param("q"));
   }

   if (request.hasParam(ClusteringActionRequest.JSON_ALGORITHM)) {
      actionBuilder.setAlgorithm(request.param(ClusteringActionRequest.JSON_ALGORITHM));
   }

   if (request.hasParam(ClusteringActionRequest.JSON_INCLUDE_HITS)) {
      actionBuilder.setIncludeHits(request.param(ClusteringActionRequest.JSON_INCLUDE_HITS));
   }

   if (request.hasParam(ClusteringActionRequest.JSON_MAX_HITS)) {
      actionBuilder.setMaxHits(request.param(ClusteringActionRequest.JSON_MAX_HITS));
   }

   if (request.hasParam(ClusteringActionRequest.JSON_CREATE_UNGROUPED_CLUSTER)) {
      actionBuilder.setCreateUngroupedDocumentsCluster(
          Boolean.parseBoolean(request.param(ClusteringActionRequest.JSON_CREATE_UNGROUPED_CLUSTER)));
   }

   if (request.hasParam(ClusteringActionRequest.JSON_LANGUAGE)) {
      actionBuilder.setDefaultLanguage(
          request.param(ClusteringActionRequest.JSON_LANGUAGE));
   }

   // Field mappers.
   for (Map.Entry<LogicalField, String> e : GET_REQUEST_FIELDMAPPERS.entrySet()) {
      if (request.hasParam(e.getValue())) {
         for (String spec : Strings.splitStringByCommaToArray(request.param(e.getValue()))) {
            actionBuilder.addFieldMappingSpec(spec, e.getKey());
         }
      }
   }
}