@Override public void handleRequest(final RestRequest request, final RestChannel channel) { final ClusterUpdateSettingsRequest clusterUpdateSettingsRequest = Requests.clusterUpdateSettingsRequest(); clusterUpdateSettingsRequest.listenerThreaded(false); try { Map<String, Object> source = XContentFactory.xContent(request.content()).createParser(request.content()).mapAndClose(); if (source.containsKey("transient")) { clusterUpdateSettingsRequest.transientSettings((Map) source.get("transient")); } if (source.containsKey("persistent")) { clusterUpdateSettingsRequest.persistentSettings((Map) source.get("persistent")); } } catch (Exception e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.warn("Failed to send response", e1); } return; } client .admin() .cluster() .updateSettings( clusterUpdateSettingsRequest, new ActionListener<ClusterUpdateSettingsResponse>() { @Override public void onResponse(ClusterUpdateSettingsResponse response) { try { channel.sendResponse(new StringRestResponse(RestStatus.OK)); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { if (logger.isDebugEnabled()) { logger.debug("failed to handle cluster state", e); } try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); }
@Override public void login(final RestRequest request, final ActionListener<String[]> listener) { String username = request.param(usernameKey); String password = request.param(passwordKey); final BytesReference content = request.content(); final XContentType xContentType = XContentFactory.xContentType(content); XContentParser parser = null; try { parser = XContentFactory.xContent(xContentType).createParser(content); final XContentParser.Token t = parser.nextToken(); if (t != null) { final Map<String, Object> contentMap = parser.map(); username = MapUtil.getAsString(contentMap, usernameKey, username); password = MapUtil.getAsString(contentMap, passwordKey, password); } } catch (final Exception e) { listener.onFailure(e); return; } finally { if (parser != null) { parser.close(); } } if (username == null) { listener.onResponse(new String[0]); return; } processLogin(username, password, listener); }
@Override public void handleRequest(final RestRequest request, final RestChannel channel) { MultiSearchRequest multiSearchRequest = new MultiSearchRequest(); multiSearchRequest.listenerThreaded(false); String[] indices = Strings.splitStringByCommaToArray(request.param("index")); String[] types = Strings.splitStringByCommaToArray(request.param("type")); IndicesOptions indicesOptions = IndicesOptions.fromRequest(request, multiSearchRequest.indicesOptions()); try { multiSearchRequest.add( request.content(), request.contentUnsafe(), indices, types, request.param("search_type"), request.param("routing"), indicesOptions, allowExplicitIndex); } catch (Exception e) { try { XContentBuilder builder = restContentBuilder(request); channel.sendResponse( new XContentRestResponse( request, BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject())); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } return; } client.multiSearch( multiSearchRequest, new ActionListener<MultiSearchResponse>() { @Override public void onResponse(MultiSearchResponse response) { try { XContentBuilder builder = restContentBuilder(request); builder.startObject(); response.toXContent(builder, request); builder.endObject(); channel.sendResponse(new XContentRestResponse(request, OK, builder)); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); }
@Override public void handleRequest( final RestRequest request, final RestChannel channel, NodeClient client) { PutStoredScriptRequest putRequest = new PutStoredScriptRequest(getScriptLang(request), request.param("id")); putRequest.script(request.content()); client.admin().cluster().putStoredScript(putRequest, new AcknowledgedRestListener<>(channel)); }
@Override public void handleRequest(final RestRequest request, final RestChannel channel) { String text = request.param("text"); if (text == null && request.hasContent()) { text = request.content().toUtf8(); } if (text == null) { try { channel.sendResponse( new XContentThrowableRestResponse( request, new ElasticsearchIllegalArgumentException("text is missing"))); } catch (IOException e1) { logger.warn("Failed to send response", e1); } return; } AnalyzeRequest analyzeRequest = new AnalyzeRequest(request.param("index"), text); analyzeRequest.listenerThreaded(false); analyzeRequest.preferLocal( request.paramAsBoolean("prefer_local", analyzeRequest.preferLocalShard())); 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())); client .admin() .indices() .analyze( analyzeRequest, new ActionListener<AnalyzeResponse>() { @Override public void onResponse(AnalyzeResponse response) { try { XContentBuilder builder = restContentBuilder(request, null); builder.startObject(); response.toXContent(builder, request); builder.endObject(); channel.sendResponse(new XContentRestResponse(request, OK, builder)); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); }
@Override public void handleRequest( final RestRequest request, final RestChannel channel, final Client client) throws IOException { DeleteByQueryRequest delete = new DeleteByQueryRequest(Strings.splitStringByCommaToArray(request.param("index"))); delete.indicesOptions(IndicesOptions.fromRequest(request, delete.indicesOptions())); delete.routing(request.param("routing")); if (request.hasParam("timeout")) { delete.timeout(request.paramAsTime("timeout", null)); } if (request.hasContent()) { XContentParser requestParser = XContentFactory.xContent(request.content()).createParser(request.content()); QueryParseContext context = new QueryParseContext(indicesQueriesRegistry); context.reset(requestParser); context.parseFieldMatcher(parseFieldMatcher); final QueryBuilder<?> builder = context.parseInnerQueryBuilder(); delete.query(builder); } else { String source = request.param("source"); if (source != null) { XContentParser requestParser = XContentFactory.xContent(source).createParser(source); QueryParseContext context = new QueryParseContext(indicesQueriesRegistry); context.reset(requestParser); final QueryBuilder<?> builder = context.parseInnerQueryBuilder(); delete.query(builder); } else { QueryBuilder<?> queryBuilder = RestActions.urlParamsToQueryBuilder(request); if (queryBuilder != null) { delete.query(queryBuilder); } } } delete.types(Strings.splitStringByCommaToArray(request.param("type"))); client.execute(INSTANCE, delete, new RestToXContentListener<DeleteByQueryResponse>(channel)); }
@Override public void handleRequest( final RestRequest request, final RestChannel channel, final Client client) { PutRepositoryRequest putRepositoryRequest = putRepositoryRequest(request.param("repository")); putRepositoryRequest.source(request.content().toUtf8()); putRepositoryRequest.verify(request.paramAsBoolean("verify", true)); putRepositoryRequest.masterNodeTimeout( request.paramAsTime("master_timeout", putRepositoryRequest.masterNodeTimeout())); putRepositoryRequest.timeout(request.paramAsTime("timeout", putRepositoryRequest.timeout())); client .admin() .cluster() .putRepository( putRepositoryRequest, new AcknowledgedRestListener<PutRepositoryResponse>(channel)); }
@Override public void handleRequest( final RestRequest request, final RestChannel channel, final NodeClient client) { RestoreSnapshotRequest restoreSnapshotRequest = restoreSnapshotRequest(request.param("repository"), request.param("snapshot")); restoreSnapshotRequest.masterNodeTimeout( request.paramAsTime("master_timeout", restoreSnapshotRequest.masterNodeTimeout())); restoreSnapshotRequest.waitForCompletion(request.paramAsBoolean("wait_for_completion", false)); restoreSnapshotRequest.source(request.content().utf8ToString()); client .admin() .cluster() .restoreSnapshot( restoreSnapshotRequest, new RestToXContentListener<RestoreSnapshotResponse>(channel)); }
public ACLRequest(RestRequest request, RestChannel channel) { this( request.uri(), getAddress(channel), request.header("X-Api-Key"), request.header("Auth"), request.content().length(), request.method(), getXForwardedForHeader(request)); ESLogger logger = ESLoggerFactory.getLogger(ACLRequest.class.getName()); logger.debug("Headers:\n"); for (Map.Entry<String, String> header : request.headers()) { logger.debug(header.getKey() + "=" + header.getValue()); } }
@Override public void handleRequest(final RestRequest request, final RestChannel channel) { PutWarmerRequest putWarmerRequest = new PutWarmerRequest(request.param("name")); putWarmerRequest.listenerThreaded(false); SearchRequest searchRequest = new SearchRequest(Strings.splitStringByCommaToArray(request.param("index"))) .types(Strings.splitStringByCommaToArray(request.param("type"))) .source(request.content(), request.contentUnsafe()); searchRequest.indicesOptions( IndicesOptions.fromRequest(request, searchRequest.indicesOptions())); putWarmerRequest.searchRequest(searchRequest); putWarmerRequest.timeout(request.paramAsTime("timeout", putWarmerRequest.timeout())); putWarmerRequest.masterNodeTimeout( request.paramAsTime("master_timeout", putWarmerRequest.masterNodeTimeout())); client .admin() .indices() .putWarmer( putWarmerRequest, new AcknowledgedRestResponseActionListener(request, channel, logger)); }
@Override public void handleRequest(final RestRequest request, final RestChannel channel) { PutWarmerRequest putWarmerRequest = new PutWarmerRequest(request.param("name")); putWarmerRequest.listenerThreaded(false); SearchRequest searchRequest = new SearchRequest(RestActions.splitIndices(request.param("index"))) .types(RestActions.splitTypes(request.param("type"))) .source(request.content(), request.contentUnsafe()); putWarmerRequest.searchRequest(searchRequest); client .admin() .indices() .putWarmer( putWarmerRequest, new ActionListener<PutWarmerResponse>() { @Override public void onResponse(PutWarmerResponse response) { try { XContentBuilder builder = RestXContentBuilder.restContentBuilder(request); builder .startObject() .field("ok", true) .field("acknowledged", response.isAcknowledged()); builder.endObject(); channel.sendResponse(new XContentRestResponse(request, OK, builder)); } catch (IOException e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); }
@Override public void handleRequest(final RestRequest request, final RestChannel channel) { final ExplainRequest explainRequest = new ExplainRequest(request.param("index"), request.param("type"), request.param("id")); explainRequest.parent(request.param("parent")); explainRequest.routing(request.param("routing")); explainRequest.preference(request.param("preference")); String sourceString = request.param("source"); String queryString = request.param("q"); if (request.hasContent()) { explainRequest.source(request.content(), request.contentUnsafe()); } else if (sourceString != null) { explainRequest.source(new BytesArray(request.param("source")), false); } else if (queryString != null) { QueryStringQueryBuilder queryStringBuilder = QueryBuilders.queryString(queryString); queryStringBuilder.defaultField(request.param("df")); queryStringBuilder.analyzer(request.param("analyzer")); queryStringBuilder.analyzeWildcard(request.paramAsBoolean("analyze_wildcard", false)); queryStringBuilder.lowercaseExpandedTerms( request.paramAsBoolean("lowercase_expanded_terms", true)); queryStringBuilder.lenient(request.paramAsBooleanOptional("lenient", null)); String defaultOperator = request.param("default_operator"); if (defaultOperator != null) { if ("OR".equals(defaultOperator)) { queryStringBuilder.defaultOperator(QueryStringQueryBuilder.Operator.OR); } else if ("AND".equals(defaultOperator)) { queryStringBuilder.defaultOperator(QueryStringQueryBuilder.Operator.AND); } else { throw new ElasticSearchIllegalArgumentException( "Unsupported defaultOperator [" + defaultOperator + "], can either be [OR] or [AND]"); } } ExplainSourceBuilder explainSourceBuilder = new ExplainSourceBuilder(); explainSourceBuilder.query(queryStringBuilder); explainRequest.source(explainSourceBuilder); } client.explain( explainRequest, new ActionListener<ExplainResponse>() { @Override public void onResponse(ExplainResponse response) { try { XContentBuilder builder = restContentBuilder(request); builder.startObject(); builder.field(Fields.OK, response.exists()); builder.field(Fields.MATCHES, response.match()); if (response.hasExplanation()) { builder.startObject(Fields.EXPLANATION); buildExplanation(builder, response.explanation()); builder.endObject(); } builder.endObject(); channel.sendResponse( new XContentRestResponse(request, response.exists() ? OK : NOT_FOUND, builder)); } catch (Exception e) { onFailure(e); } } private void buildExplanation(XContentBuilder builder, Explanation explanation) throws IOException { builder.field(Fields.VALUE, explanation.getValue()); builder.field(Fields.DESCRIPTION, explanation.getDescription()); Explanation[] innerExps = explanation.getDetails(); if (innerExps != null) { builder.startArray(Fields.DETAILS); for (Explanation exp : innerExps) { builder.startObject(); buildExplanation(builder, exp); builder.endObject(); } builder.endArray(); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); }
@Override public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException { 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.setRefreshPolicy(request.param("refresh")); String waitForActiveShards = request.param("wait_for_active_shards"); if (waitForActiveShards != null) { updateRequest.waitForActiveShards(ActiveShardCount.parseString(waitForActiveShards)); } updateRequest.docAsUpsert(request.paramAsBoolean("doc_as_upsert", updateRequest.docAsUpsert())); FetchSourceContext fetchSourceContext = FetchSourceContext.parseFromRestRequest(request); String sField = request.param("fields"); if (sField != null && fetchSourceContext != null) { throw new IllegalArgumentException( "[fields] and [_source] cannot be used in the same request"); } if (sField != null) { DEPRECATION_LOGGER.deprecated("Deprecated field [fields] used, expected [_source] instead"); String[] sFields = Strings.splitStringByCommaToArray(sField); updateRequest.fields(sFields); } else if (fetchSourceContext != null) { updateRequest.fetchSource(fetchSourceContext); } 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.fromXContent(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())); } } return channel -> client.update( updateRequest, new RestStatusToXContentListener<>( channel, r -> r.getLocation(updateRequest.routing()))); }
@Override public void handleRequest( final RestRequest request, final RestChannel channel, final NodeClient 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())); indicesAliasesRequest.masterNodeTimeout( request.paramAsTime("master_timeout", indicesAliasesRequest.masterNodeTimeout())); IndicesAliasesRequest.AliasActions aliasAction = AliasActions.add().indices(indices).alias(alias); if (routing != null) { aliasAction.routing(routing); } if (searchRouting != null) { aliasAction.searchRouting(searchRouting); } if (indexRouting != null) { aliasAction.indexRouting(indexRouting); } if (filter != null) { aliasAction.filter(filter); } indicesAliasesRequest.addAliasAction(aliasAction); client .admin() .indices() .aliases(indicesAliasesRequest, new AcknowledgedRestListener<>(channel)); }
@Override public void handleRequest(final RestRequest request, final RestChannel channel) { IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest(); indicesAliasesRequest.listenerThreaded(false); indicesAliasesRequest.masterNodeTimeout( request.paramAsTime("master_timeout", indicesAliasesRequest.masterNodeTimeout())); XContentParser parser = null; try { // { // actions : [ // { add : { index : "test1", alias : "alias1", filter : {"user" : "kimchy"} } } // { remove : { index : "test1", alias : "alias1" } } // ] // } indicesAliasesRequest.timeout( request.paramAsTime("timeout", indicesAliasesRequest.timeout())); parser = XContentFactory.xContent(request.content()).createParser(request.content()); XContentParser.Token token = parser.nextToken(); if (token == null) { throw new ElasticsearchIllegalArgumentException("No action is specified"); } while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.START_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.FIELD_NAME) { String action = parser.currentName(); AliasAction.Type type; if ("add".equals(action)) { type = AliasAction.Type.ADD; } else if ("remove".equals(action)) { type = AliasAction.Type.REMOVE; } else { throw new ElasticsearchIllegalArgumentException( "Alias action [" + action + "] not supported"); } String index = null; String alias = null; Map<String, Object> filter = null; String routing = null; boolean routingSet = false; String indexRouting = null; boolean indexRoutingSet = false; String searchRouting = null; boolean searchRoutingSet = false; 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 ("index".equals(currentFieldName)) { index = parser.text(); } else if ("alias".equals(currentFieldName)) { alias = parser.text(); } else if ("routing".equals(currentFieldName)) { routing = parser.textOrNull(); routingSet = true; } else if ("indexRouting".equals(currentFieldName) || "index-routing".equals(currentFieldName) || "index_routing".equals(currentFieldName)) { indexRouting = parser.textOrNull(); indexRoutingSet = true; } else if ("searchRouting".equals(currentFieldName) || "search-routing".equals(currentFieldName) || "search_routing".equals(currentFieldName)) { searchRouting = parser.textOrNull(); searchRoutingSet = true; } } else if (token == XContentParser.Token.START_OBJECT) { if ("filter".equals(currentFieldName)) { filter = parser.mapOrdered(); } } } if (type == AliasAction.Type.ADD) { AliasAction aliasAction = newAddAliasAction(index, alias).filter(filter); if (routingSet) { aliasAction.routing(routing); } if (indexRoutingSet) { aliasAction.indexRouting(indexRouting); } if (searchRoutingSet) { aliasAction.searchRouting(searchRouting); } indicesAliasesRequest.addAliasAction(aliasAction); } else if (type == AliasAction.Type.REMOVE) { indicesAliasesRequest.removeAlias(index, alias); } } } } } } catch (Exception e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.warn("Failed to send response", e1); } return; } finally { parser.close(); } client .admin() .indices() .aliases( indicesAliasesRequest, new AcknowledgedRestResponseActionListener<IndicesAliasesResponse>( request, channel, logger)); }
@Override public XContentBuilder newErrorBuilder() throws IOException { // Disable filtering when building error responses return newBuilder(request.hasContent() ? request.content() : null, false); }
@Override public XContentBuilder newBuilder() throws IOException { return newBuilder(request.hasContent() ? request.content() : null, true); }