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

The following examples show how to use org.elasticsearch.rest.RestRequest#param() . 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: JobRestHandler.java    From elasticsearch-rest-command with The Unlicense 6 votes vote down vote up
private String getCommandStringFromRestRequest(final RestRequest request) throws CommandException{
	String command = "";
	if(request.method() == RestRequest.Method.GET)
		command = request.param("q", "");
	else{
		HashMap<String, String> post = new HashMap<String, String>();
		RestUtils.decodeQueryString(request.content().toUtf8(), 0, post);
		if(post.containsKey("q")){
			command = post.get("q");
		}
	}
	
	if (command.length() == 0) {
		throw new CommandException("命令为空");
		
	}else{
		if( ! command.startsWith(Search.PREFIX_SEARCH_STRING))
			command = Search.PREFIX_SEARCH_STRING+" "+command;				
	}
	
	logger.info(command);
	
	return command;
}
 
Example 2
Source File: RestDataAction.java    From elasticsearch-dataformat with Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request, final RestChannel channel, final String file) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        final String pretty = request.param("pretty");
        if (pretty != null && !"false".equalsIgnoreCase(pretty)) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", true);
        builder.field("file", file);
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final IOException e) {
        throw new ElasticsearchException("Failed to create a resposne.", e);
    }
}
 
Example 3
Source File: RestGetAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 6 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);
    String typesStr = request.param(TYPE);
    String rawPath = request.rawPath();
    if (!Strings.isEmpty(typesStr) || rawPath.endsWith(PROFILE) || rawPath.endsWith(PROFILE + "/")) {
        boolean all = request.paramAsBoolean("_all", false);
        return channel -> profileRunner
            .profile(detectorId, getProfileActionListener(channel, detectorId), getProfilesToCollect(typesStr, all));
    } else {
        boolean returnJob = request.paramAsBoolean("job", false);
        MultiGetRequest.Item adItem = new MultiGetRequest.Item(ANOMALY_DETECTORS_INDEX, detectorId)
            .version(RestActions.parseVersion(request));
        MultiGetRequest multiGetRequest = new MultiGetRequest().add(adItem);
        if (returnJob) {
            MultiGetRequest.Item adJobItem = new MultiGetRequest.Item(ANOMALY_DETECTOR_JOB_INDEX, detectorId)
                .version(RestActions.parseVersion(request));
            multiGetRequest.add(adJobItem);
        }

        return channel -> client.multiGet(multiGetRequest, onMultiGetResponse(channel, returnJob, detectorId));
    }
}
 
Example 4
Source File: AuthService.java    From elasticsearch-auth with Apache License 2.0 6 votes vote down vote up
public String getToken(final RestRequest request) {
    String token = request.param(tokenKey);
    //   cookie
    if (token == null && cookieToken) {
        final String cookieString = request
                .header(HttpHeaders.Names.COOKIE);
        if (cookieString != null) {
            final Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieString);
            for (final Cookie cookie : cookies) {
                if (cookieTokenName.equals(cookie.name())) {
                    token = cookie.value();
                    break;
                }
            }
        }
    }
    return token;
}
 
Example 5
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 6
Source File: RestCancelTasksAction.java    From Elasticsearch 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[] nodesIds = Strings.splitStringByCommaToArray(request.param("nodeId"));
    TaskId taskId = new TaskId(request.param("taskId"));
    String[] actions = Strings.splitStringByCommaToArray(request.param("actions"));
    TaskId parentTaskId = new TaskId(request.param("parent_task_id"));

    CancelTasksRequest cancelTasksRequest = new CancelTasksRequest();
    cancelTasksRequest.setTaskId(taskId);
    cancelTasksRequest.setNodesIds(nodesIds);
    cancelTasksRequest.setActions(actions);
    cancelTasksRequest.setParentTaskId(parentTaskId);
    client.admin().cluster().cancelTasks(cancelTasksRequest, new RestToXContentListener<CancelTasksResponse>(channel));
}
 
Example 7
Source File: TasteSearchRestAction.java    From elasticsearch-taste with Apache License 2.0 5 votes vote down vote up
Info(final RestRequest request) {
    size = request.paramAsInt("size", 10);
    from = request.paramAsInt("from", 0);
    targetIndex = request.param("index");
    targetType = request.param("type");
    userIndex = request.param(TasteConstants.REQUEST_PARAM_USER_INDEX,
            targetIndex);
    userType = request.param(TasteConstants.REQUEST_PARAM_USER_TYPE,
            TasteConstants.USER_TYPE);
    itemIndex = request.param(TasteConstants.REQUEST_PARAM_ITEM_INDEX,
            targetIndex);
    itemType = request.param(TasteConstants.REQUEST_PARAM_ITEM_TYPE,
            TasteConstants.ITEM_TYPE);
    userIdField = request.param(
            TasteConstants.REQUEST_PARAM_USER_ID_FIELD,
            TasteConstants.USER_ID_FIELD);
    itemIdField = request.param(
            TasteConstants.REQUEST_PARAM_ITEM_ID_FIELD,
            TasteConstants.ITEM_ID_FIELD);
    timestampField = request.param(
            TasteConstants.REQUEST_PARAM_TIMESTAMP_FIELD,
            TasteConstants.TIMESTAMP_FIELD);
    objectType = request.param("objectType");
    if (USER.equals(objectType)) {
        idIndex = userIndex;
        idType = userType;
        idField = request.param(TasteConstants.REQUEST_PARAM_ID_FIELD,
                userIdField);
    } else if (ITEM.equals(objectType)) {
        idIndex = itemIndex;
        idType = itemType;
        idField = request.param(TasteConstants.REQUEST_PARAM_ID_FIELD,
                itemIdField);
    }
    targetIdField = request.param(
            TasteConstants.REQUEST_PARAM_TARGET_ID_FIELD, idField);
}
 
Example 8
Source File: RestTermVectorsAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
    TermVectorsRequest termVectorsRequest = new TermVectorsRequest(request.param("index"), request.param("type"), request.param("id"));
    if (RestActions.hasBodyContent(request)) {
        try (XContentParser parser = XContentFactory.xContent(RestActions.guessBodyContentType(request)).createParser(RestActions.getRestContent(request))){
            TermVectorsRequest.parseRequest(termVectorsRequest, parser);
        }
    }
    readURIParameters(termVectorsRequest, request);

    client.termVectors(termVectorsRequest, new RestToXContentListener<TermVectorsResponse>(channel));
}
 
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: 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 11
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 12
Source File: RequestUtil.java    From elasticsearch-dataformat with Apache License 2.0 5 votes vote down vote up
public static TimeValue getScroll(final RestRequest request) {
    final String scroll = request.param("scroll");
    if (scroll != null) {
        return parseTimeValue(scroll, DEFAULT_SCROLL, "");
    } else {
        return DEFAULT_SCROLL;
    }
}
 
Example 13
Source File: AbstractApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
protected void handleDelete(final RestChannel channel, final RestRequest request, final Client client, final JsonNode content) throws IOException {
	final String name = request.param("name");

	if (name == null || name.length() == 0) {
		badRequestResponse(channel, "No " + getResourceName() + " specified.");
		return;
	}

	final SecurityDynamicConfiguration<?> existingConfiguration = load(getConfigName(), false);

	if (isHidden(existingConfiguration, name)) {
		notFound(channel, getResourceName() + " " + name + " not found.");
		return;
	}

	if (isReserved(existingConfiguration, name)) {
		forbidden(channel, "Resource '"+ name +"' is read-only.");
		return;
	}

	boolean existed = existingConfiguration.exists(name);
	existingConfiguration.remove(name);

	if (existed) {
		saveAnUpdateConfigs(client, request, getConfigName(), existingConfiguration, new OnSucessActionListener<IndexResponse>(channel) {

			@Override
			public void onResponse(IndexResponse response) {
				successResponse(channel, "'" + name + "' deleted.");
			}
		});

	} else {
		notFound(channel, getResourceName() + " " + name + " not found.");
	}
}
 
Example 14
Source File: PatchableResourceApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private void handlePatch(RestChannel channel, final RestRequest request, final Client client)
        throws IOException  {
    if (request.getXContentType() != XContentType.JSON) {
        badRequestResponse(channel, "PATCH accepts only application/json");
        return;
    }

    String name = request.param("name");
    SecurityDynamicConfiguration<?> existingConfiguration = load(getConfigName(), false);

    JsonNode jsonPatch;

    try {
        jsonPatch = DefaultObjectMapper.readTree(request.content().utf8ToString());
    } catch (IOException e) {
        log.debug("Error while parsing JSON patch", e);
        badRequestResponse(channel, "Error in JSON patch: " + e.getMessage());
        return;
    }

    JsonNode existingAsJsonNode = Utils.convertJsonToJackson(existingConfiguration, true);

    if (!(existingAsJsonNode instanceof ObjectNode)) {
        internalErrorResponse(channel, "Config " + getConfigName() + " is malformed");
        return;
    }

    ObjectNode existingAsObjectNode = (ObjectNode) existingAsJsonNode;

    if (Strings.isNullOrEmpty(name)) {
        handleBulkPatch(channel, request, client, existingConfiguration, existingAsObjectNode, jsonPatch);
    } else {
        handleSinglePatch(channel, request, client, name, existingConfiguration, existingAsObjectNode, jsonPatch);
    }
}
 
Example 15
Source File: RestDataAction.java    From elasticsearch-dataformat with Apache License 2.0 5 votes vote down vote up
public RestChannelConsumer prepareRequest(final RestRequest request,
        final NodeClient client) throws IOException {
    SearchRequest searchRequest = new SearchRequest();
    request.withContentOrSourceParamParserOrNull(
            parser -> RestSearchAction.parseSearchRequest(searchRequest,
                    request, parser,
                    size -> searchRequest.source().size(size)));

    if (request.paramAsInt("size", -1) == -1) {
        searchRequest.source().size(100);
    }

    final String file = request.param("file");

    final long limitBytes;
    String limitParamStr = request.param("limit");
    if (Strings.isNullOrEmpty(limitParamStr)) {
        limitBytes = defaultLimit;
    } else {
        if (limitParamStr.endsWith("%")) {
            limitParamStr = limitParamStr.substring(0,
                    limitParamStr.length() - 1);
        }
        limitBytes = (long) (maxMemory
                * (Float.parseFloat(limitParamStr) / 100F));
    }

    final ContentType contentType = getContentType(request);
    if (contentType == null) {
        final String msg = "Unknown content type:"
                + request.header("Content-Type");
        throw new IllegalArgumentException(msg);
    }
    final DataContent dataContent = contentType.dataContent(client,
            request);

    return channel -> client.search(searchRequest, new SearchResponseListener(
            channel, file, limitBytes, dataContent));
}
 
Example 16
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 17
Source File: RestStatsAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a ADStatsRequest from a RestRequest
 *
 * @param request RestRequest
 * @return ADStatsRequest Request containing stats to be retrieved
 */
private ADStatsRequest getRequest(RestRequest request) {
    // parse the nodes the user wants to query the stats for
    String nodesIdsStr = request.param("nodeId");
    Set<String> validStats = adStats.getStats().keySet();

    ADStatsRequest adStatsRequest = null;
    if (!Strings.isEmpty(nodesIdsStr)) {
        String[] nodeIdsArr = nodesIdsStr.split(",");
        adStatsRequest = new ADStatsRequest(nodeIdsArr);
    } else {
        DiscoveryNode[] dataNodes = nodeFilter.getEligibleDataNodes();
        adStatsRequest = new ADStatsRequest(dataNodes);
    }

    adStatsRequest.timeout(request.param("timeout"));

    // parse the stats the user wants to see
    HashSet<String> statsSet = null;
    String statsStr = request.param("stat");
    if (!Strings.isEmpty(statsStr)) {
        statsSet = new HashSet<>(Arrays.asList(statsStr.split(",")));
    }

    if (statsSet == null) {
        adStatsRequest.addAll(validStats); // retrieve all stats if none are specified
    } else if (statsSet.size() == 1 && statsSet.contains(ADStatsRequest.ALL_STATS_KEY)) {
        adStatsRequest.addAll(validStats);
    } else if (statsSet.contains(ADStatsRequest.ALL_STATS_KEY)) {
        throw new IllegalArgumentException(
            "Request " + request.path() + " contains " + ADStatsRequest.ALL_STATS_KEY + " and individual stats"
        );
    } else {
        Set<String> invalidStats = new TreeSet<>();
        for (String stat : statsSet) {
            if (validStats.contains(stat)) {
                adStatsRequest.addStat(stat);
            } else {
                invalidStats.add(stat);
            }
        }

        if (!invalidStats.isEmpty()) {
            throw new IllegalArgumentException(unrecognized(request, invalidStats, adStatsRequest.getStatsToBeRetrieved(), "stat"));
        }
    }
    return adStatsRequest;
}
 
Example 18
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 19
Source File: RestIndexPutAliasAction.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 {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    String alias = request.param("name");
    Map<String, Object> filter = null;
    String routing = null;
    String indexRouting = null;
    String searchRouting = null;

    if (request.hasContent()) {
        try (XContentParser parser = XContentFactory.xContent(request.content()).createParser(request.content())) {
            XContentParser.Token token = parser.nextToken();
            if (token == null) {
                throw new IllegalArgumentException("No index alias is specified");
            }
            String currentFieldName = null;
            while ((token = parser.nextToken()) != null) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (token.isValue()) {
                    if ("index".equals(currentFieldName)) {
                        indices = Strings.splitStringByCommaToArray(parser.text());
                    } else if ("alias".equals(currentFieldName)) {
                        alias = parser.text();
                    } else if ("routing".equals(currentFieldName)) {
                        routing = parser.textOrNull();
                    } else if ("indexRouting".equals(currentFieldName) || "index-routing".equals(currentFieldName) || "index_routing".equals(currentFieldName)) {
                        indexRouting = parser.textOrNull();
                    } else if ("searchRouting".equals(currentFieldName) || "search-routing".equals(currentFieldName) || "search_routing".equals(currentFieldName)) {
                        searchRouting = parser.textOrNull();
                    }
                } else if (token == XContentParser.Token.START_OBJECT) {
                    if ("filter".equals(currentFieldName)) {
                        filter = parser.mapOrdered();
                    }
                }
            }
        }
    }

    IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest();
    indicesAliasesRequest.timeout(request.paramAsTime("timeout", indicesAliasesRequest.timeout()));
    String[] aliases = new String[]{alias};
    IndicesAliasesRequest.AliasActions aliasAction = new AliasActions(AliasAction.Type.ADD, indices, aliases);
    indicesAliasesRequest.addAliasAction(aliasAction);
    indicesAliasesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", indicesAliasesRequest.masterNodeTimeout()));


    if (routing != null) {
        aliasAction.routing(routing);
    }
    if (searchRouting != null) {
        aliasAction.searchRouting(searchRouting);
    }
    if (indexRouting != null) {
        aliasAction.indexRouting(indexRouting);
    }
    if (filter != null) {
        aliasAction.filter(filter);
    }
    client.admin().indices().aliases(indicesAliasesRequest, new AcknowledgedRestListener<IndicesAliasesResponse>(channel));
}
 
Example 20
Source File: ActionGroupsApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@Override
protected void consumeParameters(final RestRequest request) {
	request.param("name");
}