Recycled bytes in http + rest layer refactoring phase 2

Refactor the rest layer handlers to simplify common code paths (like handling) failures, and introduce optional (enabled for netty) rest channel bytes recycling
This commit is contained in:
Shay Banon 2014-04-06 23:39:51 +02:00
parent 94278d81e3
commit 705c7e2469
115 changed files with 1366 additions and 2746 deletions

View File

@ -124,7 +124,6 @@ public class MultiGetResponse extends ActionResponse implements Iterable<MultiGe
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.startArray(Fields.DOCS);
for (MultiGetItemResponse response : responses) {
if (response.isFailed()) {
@ -137,11 +136,12 @@ public class MultiGetResponse extends ActionResponse implements Iterable<MultiGe
builder.endObject();
} else {
GetResponse getResponse = response.getResponse();
builder.startObject();
getResponse.toXContent(builder, params);
builder.endObject();
}
}
builder.endArray();
builder.endObject();
return builder;
}

View File

@ -59,7 +59,6 @@ public class MultiPercolateResponse extends ActionResponse implements Iterable<M
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.startArray(Fields.RESPONSES);
for (MultiPercolateResponse.Item item : items) {
if (item.isFailure()) {
@ -67,11 +66,12 @@ public class MultiPercolateResponse extends ActionResponse implements Iterable<M
builder.field(Fields.ERROR, item.getErrorMessage());
builder.endObject();
} else {
builder.startObject();
item.getResponse().toXContent(builder, params);
builder.endObject();
}
}
builder.endArray();
builder.endObject();
return builder;
}

View File

@ -122,8 +122,6 @@ public class PercolateResponse extends BroadcastOperationResponse implements Ite
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(Fields.TOOK, tookInMillis);
RestActions.buildBroadcastShardsHeader(builder, this);
@ -172,8 +170,6 @@ public class PercolateResponse extends BroadcastOperationResponse implements Ite
if (aggregations != null) {
aggregations.toXContent(builder, params);
}
builder.endObject();
return builder;
}

View File

@ -124,7 +124,6 @@ public class MultiTermVectorsResponse extends ActionResponse implements Iterable
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.startArray(Fields.DOCS);
for (MultiTermVectorsItemResponse response : responses) {
if (response.isFailed()) {
@ -137,11 +136,12 @@ public class MultiTermVectorsResponse extends ActionResponse implements Iterable
builder.endObject();
} else {
TermVectorResponse getResponse = response.getResponse();
builder.startObject();
getResponse.toXContent(builder, params);
builder.endObject();
}
}
builder.endArray();
builder.endObject();
return builder;
}

View File

@ -164,7 +164,6 @@ public class TermVectorResponse extends ActionResponse implements ToXContent {
assert index != null;
assert type != null;
assert id != null;
builder.startObject();
builder.field(FieldStrings._INDEX, index);
builder.field(FieldStrings._TYPE, type);
builder.field(FieldStrings._ID, id);
@ -182,7 +181,6 @@ public class TermVectorResponse extends ActionResponse implements ToXContent {
buildField(builder, spare, theFields, fieldIter);
}
builder.endObject();
builder.endObject();
return builder;
}

View File

@ -20,10 +20,14 @@
package org.elasticsearch.http;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestRequest;
/**
*
*/
public interface HttpChannel extends RestChannel {
public abstract class HttpChannel extends RestChannel {
protected HttpChannel(RestRequest request) {
super(request);
}
}

View File

@ -22,6 +22,8 @@ package org.elasticsearch.http.netty;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.UnicodeUtil;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput;
import org.elasticsearch.common.lease.Releasable;
import org.elasticsearch.common.netty.ReleaseChannelFutureListener;
import org.elasticsearch.http.HttpChannel;
@ -42,7 +44,7 @@ import java.util.Set;
/**
*
*/
public class NettyHttpChannel implements HttpChannel {
public class NettyHttpChannel extends HttpChannel {
private static final ChannelBuffer END_JSONP;
@ -54,16 +56,21 @@ public class NettyHttpChannel implements HttpChannel {
private final NettyHttpServerTransport transport;
private final Channel channel;
private final NettyHttpRequest request;
private final org.jboss.netty.handler.codec.http.HttpRequest nettyRequest;
public NettyHttpChannel(NettyHttpServerTransport transport, Channel channel, NettyHttpRequest request) {
super(request);
this.transport = transport;
this.channel = channel;
this.request = request;
this.nettyRequest = request.request();
}
@Override
public BytesStreamOutput newBytesOutput() {
return new ReleasableBytesStreamOutput(transport.bigArrays);
}
@Override
public void sendResponse(RestResponse response) {
// Decide whether to close the connection or not.

View File

@ -33,6 +33,7 @@ import org.elasticsearch.common.transport.NetworkExceptionHelper;
import org.elasticsearch.common.transport.PortsRange;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.http.*;
import org.elasticsearch.http.HttpRequest;
@ -64,6 +65,7 @@ public class NettyHttpServerTransport extends AbstractLifecycleComponent<HttpSer
}
private final NetworkService networkService;
final BigArrays bigArrays;
final ByteSizeValue maxContentLength;
final ByteSizeValue maxInitialLineLength;
@ -110,9 +112,10 @@ public class NettyHttpServerTransport extends AbstractLifecycleComponent<HttpSer
private volatile HttpServerAdapter httpServerAdapter;
@Inject
public NettyHttpServerTransport(Settings settings, NetworkService networkService) {
public NettyHttpServerTransport(Settings settings, NetworkService networkService, BigArrays bigArrays) {
super(settings);
this.networkService = networkService;
this.bigArrays = bigArrays;
if (settings.getAsBoolean("netty.epollBugWorkaround", false)) {
System.setProperty("org.jboss.netty.epollBugWorkaround", "true");

View File

@ -30,7 +30,6 @@ import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.search.lookup.SourceLookup;
import java.io.IOException;
@ -210,7 +209,7 @@ public class GetResult implements Streamable, Iterable<GetField>, ToXContent {
builder.field(Fields.FOUND, exists);
if (source != null) {
RestXContentBuilder.restDocumentSource(source, builder, params);
XContentHelper.writeRawField("_source", source, builder, params);
}
if (fields != null && !fields.isEmpty()) {
@ -238,14 +237,11 @@ public class GetResult implements Streamable, Iterable<GetField>, ToXContent {
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (!isExists()) {
builder.startObject();
builder.field(Fields._INDEX, index);
builder.field(Fields._TYPE, type);
builder.field(Fields._ID, id);
builder.field(Fields.FOUND, false);
builder.endObject();
} else {
builder.startObject();
builder.field(Fields._INDEX, index);
builder.field(Fields._TYPE, type);
builder.field(Fields._ID, id);
@ -253,8 +249,6 @@ public class GetResult implements Streamable, Iterable<GetField>, ToXContent {
builder.field(Fields._VERSION, version);
}
toXContentEmbedded(builder, params);
builder.endObject();
}
return builder;
}

View File

@ -27,7 +27,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException;
import static org.elasticsearch.ExceptionsHelper.detailedMessage;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
public class BytesRestResponse extends RestResponse {
@ -80,12 +79,21 @@ public class BytesRestResponse extends RestResponse {
this.contentType = contentType;
}
public BytesRestResponse(RestRequest request, Throwable t) throws IOException {
this(request, ((t instanceof ElasticsearchException) ? ((ElasticsearchException) t).status() : RestStatus.INTERNAL_SERVER_ERROR), t);
public BytesRestResponse(RestChannel channel, Throwable t) throws IOException {
this(channel, ((t instanceof ElasticsearchException) ? ((ElasticsearchException) t).status() : RestStatus.INTERNAL_SERVER_ERROR), t);
}
public BytesRestResponse(RestRequest request, RestStatus status, Throwable t) throws IOException {
this(status, convert(request, status, t));
public BytesRestResponse(RestChannel channel, RestStatus status, Throwable t) throws IOException {
this.status = status;
if (channel.request().method() == RestRequest.Method.HEAD) {
this.content = BytesArray.EMPTY;
this.contentType = TEXT_CONTENT_TYPE;
} else {
XContentBuilder builder = convert(channel, status, t);
this.content = builder.bytes();
this.contentType = builder.contentType().restContentType();
}
this.contentThreadSafe = true;
}
@Override
@ -108,11 +116,11 @@ public class BytesRestResponse extends RestResponse {
return this.status;
}
private static XContentBuilder convert(RestRequest request, RestStatus status, Throwable t) throws IOException {
XContentBuilder builder = restContentBuilder(request).startObject()
private static XContentBuilder convert(RestChannel channel, RestStatus status, Throwable t) throws IOException {
XContentBuilder builder = channel.newBuilder().startObject()
.field("error", detailedMessage(t))
.field("status", status.getStatus());
if (t != null && request.paramAsBoolean("error_trace", false)) {
if (t != null && channel.request().paramAsBoolean("error_trace", false)) {
builder.startObject("error_trace");
boolean first = true;
int counter = 0;

View File

@ -19,10 +19,82 @@
package org.elasticsearch.rest;
/**
*
*/
public interface RestChannel {
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
void sendResponse(RestResponse response);
import java.io.IOException;
/**
* A channel used to construct bytes / builder based outputs, and send responses.
*/
public abstract class RestChannel {
protected final RestRequest request;
private BytesStreamOutput bytesOut;
protected RestChannel(RestRequest request) {
this.request = request;
}
public XContentBuilder newBuilder() throws IOException {
return newBuilder(request.hasContent() ? request.content() : null);
}
public XContentBuilder newBuilder(@Nullable BytesReference autoDetectSource) throws IOException {
XContentType contentType = XContentType.fromRestContentType(request.param("format", request.header("Content-Type")));
if (contentType == null) {
// try and guess it from the auto detect source
if (autoDetectSource != null) {
contentType = XContentFactory.xContentType(autoDetectSource);
}
}
if (contentType == null) {
// default to JSON
contentType = XContentType.JSON;
}
XContentBuilder builder = new XContentBuilder(XContentFactory.xContent(contentType), bytesOutput());
if (request.paramAsBoolean("pretty", false)) {
builder.prettyPrint().lfAtEnd();
}
builder.humanReadable(request.paramAsBoolean("human", builder.humanReadable()));
String casing = request.param("case");
if (casing != null && "camelCase".equals(casing)) {
builder.fieldCaseConversion(XContentBuilder.FieldCaseConversion.CAMELCASE);
} else {
// we expect all REST interfaces to write results in underscore casing, so
// no need for double casing
builder.fieldCaseConversion(XContentBuilder.FieldCaseConversion.NONE);
}
return builder;
}
/**
* A channel level bytes output that can be reused. It gets reset on each call to this
* method.
*/
public final BytesStreamOutput bytesOutput() {
if (bytesOut == null) {
bytesOut = newBytesOutput();
} else {
bytesOut.reset();
}
return bytesOut;
}
protected BytesStreamOutput newBytesOutput() {
return new BytesStreamOutput();
}
public RestRequest request() {
return this.request;
}
public abstract void sendResponse(RestResponse response);
}

View File

@ -140,11 +140,11 @@ public class RestController extends AbstractLifecycleComponent<RestController> {
if (filters.length == 0) {
try {
executeHandler(request, channel);
} catch (Exception e) {
} catch (Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response for uri [" + request.uri() + "]", e1);
channel.sendResponse(new BytesRestResponse(channel, e));
} catch (Throwable e1) {
logger.error("failed to send failure response for uri [" + request.uri() + "]", e1);
}
}
} else {
@ -153,7 +153,7 @@ public class RestController extends AbstractLifecycleComponent<RestController> {
}
}
void executeHandler(RestRequest request, RestChannel channel) {
void executeHandler(RestRequest request, RestChannel channel) throws Exception {
final RestHandler handler = getHandler(request);
if (handler != null) {
handler.handleRequest(request, channel);
@ -219,7 +219,7 @@ public class RestController extends AbstractLifecycleComponent<RestController> {
}
} catch (Exception e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
channel.sendResponse(new BytesRestResponse(channel, e));
} catch (IOException e1) {
logger.error("Failed to send failure response for uri [" + request.uri() + "]", e1);
}
@ -230,7 +230,7 @@ public class RestController extends AbstractLifecycleComponent<RestController> {
class RestHandlerFilter extends RestFilter {
@Override
public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) {
public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception {
executeHandler(request, channel);
}
}

View File

@ -44,5 +44,5 @@ public abstract class RestFilter implements CloseableComponent {
* Process the rest request. Using the channel to send a response, or the filter chain to continue
* processing the request.
*/
public abstract void process(RestRequest request, RestChannel channel, RestFilterChain filterChain);
public abstract void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception;
}

View File

@ -24,5 +24,5 @@ package org.elasticsearch.rest;
*/
public interface RestHandler {
void handleRequest(RestRequest request, RestChannel channel);
void handleRequest(RestRequest request, RestChannel channel) throws Exception;
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.cluster.health;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
@ -27,15 +26,15 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import java.io.IOException;
import java.util.Locale;
import static org.elasticsearch.client.Requests.clusterHealthRequest;
import static org.elasticsearch.rest.RestStatus.PRECONDITION_FAILED;
/**
*
@ -55,55 +54,16 @@ public class RestClusterHealthAction extends BaseRestHandler {
ClusterHealthRequest clusterHealthRequest = clusterHealthRequest(Strings.splitStringByCommaToArray(request.param("index")));
clusterHealthRequest.local(request.paramAsBoolean("local", clusterHealthRequest.local()));
clusterHealthRequest.listenerThreaded(false);
try {
clusterHealthRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterHealthRequest.masterNodeTimeout()));
clusterHealthRequest.timeout(request.paramAsTime("timeout", clusterHealthRequest.timeout()));
String waitForStatus = request.param("wait_for_status");
if (waitForStatus != null) {
clusterHealthRequest.waitForStatus(ClusterHealthStatus.valueOf(waitForStatus.toUpperCase(Locale.ROOT)));
}
clusterHealthRequest.waitForRelocatingShards(request.paramAsInt("wait_for_relocating_shards", clusterHealthRequest.waitForRelocatingShards()));
clusterHealthRequest.waitForActiveShards(request.paramAsInt("wait_for_active_shards", clusterHealthRequest.waitForActiveShards()));
clusterHealthRequest.waitForNodes(request.param("wait_for_nodes", clusterHealthRequest.waitForNodes()));
} catch (Exception e) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(PRECONDITION_FAILED, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
clusterHealthRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterHealthRequest.masterNodeTimeout()));
clusterHealthRequest.timeout(request.paramAsTime("timeout", clusterHealthRequest.timeout()));
String waitForStatus = request.param("wait_for_status");
if (waitForStatus != null) {
clusterHealthRequest.waitForStatus(ClusterHealthStatus.valueOf(waitForStatus.toUpperCase(Locale.ROOT)));
}
clusterHealthRequest.waitForRelocatingShards(request.paramAsInt("wait_for_relocating_shards", clusterHealthRequest.waitForRelocatingShards()));
clusterHealthRequest.waitForActiveShards(request.paramAsInt("wait_for_active_shards", clusterHealthRequest.waitForActiveShards()));
clusterHealthRequest.waitForNodes(request.param("wait_for_nodes", clusterHealthRequest.waitForNodes()));
client.admin().cluster().health(clusterHealthRequest, new ActionListener<ClusterHealthResponse>() {
@Override
public void onResponse(ClusterHealthResponse response) {
try {
RestStatus status = RestStatus.OK;
// not sure..., we handle the health API, so we are not unavailable
// in any case, "/" should be used for
//if (response.status() == ClusterHealthStatus.RED) {
// status = RestStatus.SERVICE_UNAVAILABLE;
//}
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(status, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.admin().cluster().health(clusterHealthRequest, new RestToXContentListener<ClusterHealthResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.cluster.node.hotthreads;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodeHotThreads;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodesHotThreadsRequest;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodesHotThreadsResponse;
@ -29,8 +28,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.rest.*;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestResponseListener;
/**
@ -59,29 +57,16 @@ public class RestNodesHotThreadsAction extends BaseRestHandler {
nodesHotThreadsRequest.type(request.param("type", nodesHotThreadsRequest.type()));
nodesHotThreadsRequest.interval(TimeValue.parseTimeValue(request.param("interval"), nodesHotThreadsRequest.interval()));
nodesHotThreadsRequest.snapshots(request.paramAsInt("snapshots", nodesHotThreadsRequest.snapshots()));
client.admin().cluster().nodesHotThreads(nodesHotThreadsRequest, new ActionListener<NodesHotThreadsResponse>() {
client.admin().cluster().nodesHotThreads(nodesHotThreadsRequest, new RestResponseListener<NodesHotThreadsResponse>(channel) {
@Override
public void onResponse(NodesHotThreadsResponse response) {
try {
StringBuilder sb = new StringBuilder();
for (NodeHotThreads node : response) {
sb.append("::: ").append(node.getNode().toString()).append("\n");
Strings.spaceify(3, node.getHotThreads(), sb);
sb.append('\n');
}
channel.sendResponse(new BytesRestResponse(RestStatus.OK, sb.toString()));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
public RestResponse buildResponse(NodesHotThreadsResponse response) throws Exception {
StringBuilder sb = new StringBuilder();
for (NodeHotThreads node : response) {
sb.append("::: ").append(node.getNode().toString()).append("\n");
Strings.spaceify(3, node.getHotThreads(), sb);
sb.append('\n');
}
return new BytesRestResponse(RestStatus.OK, sb.toString());
}
});
}

View File

@ -20,7 +20,6 @@
package org.elasticsearch.rest.action.admin.cluster.node.info;
import com.google.common.collect.Sets;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.elasticsearch.client.Client;
@ -30,9 +29,8 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
import java.util.Set;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -72,7 +70,7 @@ public class RestNodesInfoAction extends BaseRestHandler {
Set<String> metricsOrNodeIds = Strings.splitStringByCommaToSet(request.param("nodeId", "_all"));
boolean isMetricsOnly = ALLOWED_METRICS.containsAll(metricsOrNodeIds);
if (isMetricsOnly) {
nodeIds = new String[] { "_all" };
nodeIds = new String[]{"_all"};
metrics = metricsOrNodeIds;
} else {
nodeIds = metricsOrNodeIds.toArray(new String[]{});
@ -102,28 +100,15 @@ public class RestNodesInfoAction extends BaseRestHandler {
nodesInfoRequest.plugins(metrics.contains("plugins"));
}
client.admin().cluster().nodesInfo(nodesInfoRequest, new ActionListener<NodesInfoResponse>() {
@Override
public void onResponse(NodesInfoResponse response) {
try {
response.settingsFilter(settingsFilter);
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
client.admin().cluster().nodesInfo(nodesInfoRequest, new RestBuilderListener<NodesInfoResponse>(channel) {
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(NodesInfoResponse response, XContentBuilder builder) throws Exception {
response.settingsFilter(settingsFilter);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
return new BytesRestResponse(RestStatus.OK, builder);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.cluster.node.restart;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.node.restart.NodesRestartRequest;
import org.elasticsearch.action.admin.cluster.node.restart.NodesRestartResponse;
import org.elasticsearch.client.Client;
@ -28,10 +27,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import java.io.IOException;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
/**
*
@ -52,36 +48,22 @@ public class RestNodesRestartAction extends BaseRestHandler {
NodesRestartRequest nodesRestartRequest = new NodesRestartRequest(nodesIds);
nodesRestartRequest.listenerThreaded(false);
nodesRestartRequest.delay(request.paramAsTime("delay", nodesRestartRequest.delay()));
client.admin().cluster().nodesRestart(nodesRestartRequest, new ActionListener<NodesRestartResponse>() {
client.admin().cluster().nodesRestart(nodesRestartRequest, new RestBuilderListener<NodesRestartResponse>(channel) {
@Override
public void onResponse(NodesRestartResponse result) {
try {
XContentBuilder builder = restContentBuilder(request);
builder.startObject();
builder.field("cluster_name", result.getClusterName().value());
public RestResponse buildResponse(NodesRestartResponse result, XContentBuilder builder) throws Exception {
builder.startObject();
builder.field("cluster_name", result.getClusterName().value());
builder.startObject("nodes");
for (NodesRestartResponse.NodeRestartResponse nodeInfo : result) {
builder.startObject(nodeInfo.getNode().id());
builder.field("name", nodeInfo.getNode().name());
builder.endObject();
}
builder.startObject("nodes");
for (NodesRestartResponse.NodeRestartResponse nodeInfo : result) {
builder.startObject(nodeInfo.getNode().id());
builder.field("name", nodeInfo.getNode().name());
builder.endObject();
builder.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
builder.endObject();
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
builder.endObject();
return new BytesRestResponse(RestStatus.OK, builder);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.cluster.node.shutdown;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.node.shutdown.NodesShutdownRequest;
import org.elasticsearch.action.admin.cluster.node.shutdown.NodesShutdownResponse;
import org.elasticsearch.client.Client;
@ -29,10 +28,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import java.io.IOException;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
/**
*
@ -55,36 +51,22 @@ public class RestNodesShutdownAction extends BaseRestHandler {
nodesShutdownRequest.listenerThreaded(false);
nodesShutdownRequest.delay(request.paramAsTime("delay", nodesShutdownRequest.delay()));
nodesShutdownRequest.exit(request.paramAsBoolean("exit", nodesShutdownRequest.exit()));
client.admin().cluster().nodesShutdown(nodesShutdownRequest, new ActionListener<NodesShutdownResponse>() {
client.admin().cluster().nodesShutdown(nodesShutdownRequest, new RestBuilderListener<NodesShutdownResponse>(channel) {
@Override
public void onResponse(NodesShutdownResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
builder.startObject();
builder.field("cluster_name", response.getClusterName().value());
public RestResponse buildResponse(NodesShutdownResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.field("cluster_name", response.getClusterName().value());
builder.startObject("nodes");
for (DiscoveryNode node : response.getNodes()) {
builder.startObject(node.id(), XContentBuilder.FieldCaseConversion.NONE);
builder.field("name", node.name(), XContentBuilder.FieldCaseConversion.NONE);
builder.endObject();
}
builder.startObject("nodes");
for (DiscoveryNode node : response.getNodes()) {
builder.startObject(node.id(), XContentBuilder.FieldCaseConversion.NONE);
builder.field("name", node.name(), XContentBuilder.FieldCaseConversion.NONE);
builder.endObject();
builder.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
builder.endObject();
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
builder.endObject();
return new BytesRestResponse(RestStatus.OK, builder);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.cluster.node.stats;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequest;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags;
@ -28,11 +27,12 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import java.io.IOException;
import java.util.Set;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -111,28 +111,6 @@ public class RestNodesStatsAction extends BaseRestHandler {
nodesStatsRequest.indices().types(request.paramAsStringArray("types", null));
}
client.admin().cluster().nodesStats(nodesStatsRequest, new ActionListener<NodesStatsResponse>() {
@Override
public void onResponse(NodesStatsResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.admin().cluster().nodesStats(nodesStatsRequest, new RestToXContentListener<NodesStatsResponse>(channel));
}
}

View File

@ -25,6 +25,7 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import static org.elasticsearch.client.Requests.deleteRepositoryRequest;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
@ -47,6 +48,6 @@ public class RestDeleteRepositoryAction extends BaseRestHandler {
deleteRepositoryRequest.listenerThreaded(false);
deleteRepositoryRequest.timeout(request.paramAsTime("timeout", deleteRepositoryRequest.timeout()));
deleteRepositoryRequest.masterNodeTimeout(request.paramAsTime("master_timeout", deleteRepositoryRequest.masterNodeTimeout()));
client.admin().cluster().deleteRepository(deleteRepositoryRequest, new AcknowledgedRestResponseActionListener<DeleteRepositoryResponse>(request, channel, logger));
client.admin().cluster().deleteRepository(deleteRepositoryRequest, new AcknowledgedRestListener<DeleteRepositoryResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.cluster.repositories.get;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesRequest;
import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesResponse;
import org.elasticsearch.client.Client;
@ -30,7 +29,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
@ -56,30 +55,16 @@ public class RestGetRepositoriesAction extends BaseRestHandler {
GetRepositoriesRequest getRepositoriesRequest = getRepositoryRequest(repositories);
getRepositoriesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRepositoriesRequest.masterNodeTimeout()));
getRepositoriesRequest.local(request.paramAsBoolean("local", getRepositoriesRequest.local()));
client.admin().cluster().getRepositories(getRepositoriesRequest, new ActionListener<GetRepositoriesResponse>() {
client.admin().cluster().getRepositories(getRepositoriesRequest, new RestBuilderListener<GetRepositoriesResponse>(channel) {
@Override
public void onResponse(GetRepositoriesResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
for (RepositoryMetaData repositoryMetaData : response.repositories()) {
RepositoriesMetaData.FACTORY.toXContent(repositoryMetaData, builder, request);
}
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
public RestResponse buildResponse(GetRepositoriesResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
for (RepositoryMetaData repositoryMetaData : response.repositories()) {
RepositoriesMetaData.FACTORY.toXContent(repositoryMetaData, builder, request);
}
}
builder.endObject();
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -25,6 +25,7 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import static org.elasticsearch.client.Requests.putRepositoryRequest;
import static org.elasticsearch.rest.RestRequest.Method.POST;
@ -50,6 +51,6 @@ public class RestPutRepositoryAction extends BaseRestHandler {
putRepositoryRequest.source(request.content().toUtf8());
putRepositoryRequest.masterNodeTimeout(request.paramAsTime("master_timeout", putRepositoryRequest.masterNodeTimeout()));
putRepositoryRequest.timeout(request.paramAsTime("timeout", putRepositoryRequest.timeout()));
client.admin().cluster().putRepository(putRepositoryRequest, new AcknowledgedRestResponseActionListener<PutRepositoryResponse>(request, channel, logger));
client.admin().cluster().putRepository(putRepositoryRequest, new AcknowledgedRestListener<PutRepositoryResponse>(channel));
}
}

View File

@ -29,6 +29,7 @@ import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import java.io.IOException;
@ -47,7 +48,7 @@ public class RestClusterRerouteAction extends BaseRestHandler {
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
public void handleRequest(final RestRequest request, final RestChannel channel) throws Exception {
final ClusterRerouteRequest clusterRerouteRequest = Requests.clusterRerouteRequest();
clusterRerouteRequest.listenerThreaded(false);
clusterRerouteRequest.dryRun(request.paramAsBoolean("dry_run", clusterRerouteRequest.dryRun()));
@ -55,19 +56,10 @@ public class RestClusterRerouteAction extends BaseRestHandler {
clusterRerouteRequest.timeout(request.paramAsTime("timeout", clusterRerouteRequest.timeout()));
clusterRerouteRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterRerouteRequest.masterNodeTimeout()));
if (request.hasContent()) {
try {
clusterRerouteRequest.source(request.content());
} catch (Exception e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.warn("Failed to send response", e1);
}
return;
}
clusterRerouteRequest.source(request.content());
}
client.admin().cluster().reroute(clusterRerouteRequest, new AcknowledgedRestResponseActionListener<ClusterRerouteResponse>(request, channel, logger) {
client.admin().cluster().reroute(clusterRerouteRequest, new AcknowledgedRestListener<ClusterRerouteResponse>(channel) {
@Override
protected void addCustomFields(XContentBuilder builder, ClusterRerouteResponse response) throws IOException {
builder.startObject("state");
@ -82,14 +74,6 @@ public class RestClusterRerouteAction extends BaseRestHandler {
response.getExplanations().toXContent(builder, ToXContent.EMPTY_PARAMS);
}
}
@Override
public void onFailure(Throwable e) {
if (logger.isDebugEnabled()) {
logger.debug("failed to handle cluster reroute", e);
}
super.onFailure(e);
}
});
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.cluster.settings;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.client.Client;
@ -28,7 +27,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
@ -49,36 +48,22 @@ public class RestClusterGetSettingsAction extends BaseRestHandler {
.routingTable(false)
.nodes(false);
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() {
client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(ClusterStateResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.startObject("persistent");
response.getState().metaData().persistentSettings().toXContent(builder, request);
builder.endObject();
builder.startObject("persistent");
response.getState().metaData().persistentSettings().toXContent(builder, request);
builder.endObject();
builder.startObject("transient");
response.getState().metaData().transientSettings().toXContent(builder, request);
builder.endObject();
builder.startObject("transient");
response.getState().metaData().transientSettings().toXContent(builder, request);
builder.endObject();
builder.endObject();
builder.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return new BytesRestResponse(RestStatus.OK, builder);
}
});
}

View File

@ -28,6 +28,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import java.io.IOException;
import java.util.Map;
@ -43,30 +44,20 @@ public class RestClusterUpdateSettingsAction extends BaseRestHandler {
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
public void handleRequest(final RestRequest request, final RestChannel channel) throws Exception {
final ClusterUpdateSettingsRequest clusterUpdateSettingsRequest = Requests.clusterUpdateSettingsRequest();
clusterUpdateSettingsRequest.listenerThreaded(false);
clusterUpdateSettingsRequest.timeout(request.paramAsTime("timeout", clusterUpdateSettingsRequest.timeout()));
clusterUpdateSettingsRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterUpdateSettingsRequest.masterNodeTimeout()));
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 BytesRestResponse(request, e));
} catch (IOException e1) {
logger.warn("Failed to send response", e1);
}
return;
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"));
}
client.admin().cluster().updateSettings(clusterUpdateSettingsRequest, new AcknowledgedRestResponseActionListener<ClusterUpdateSettingsResponse>(request, channel, logger) {
client.admin().cluster().updateSettings(clusterUpdateSettingsRequest, new AcknowledgedRestListener<ClusterUpdateSettingsResponse>(channel) {
@Override
protected void addCustomFields(XContentBuilder builder, ClusterUpdateSettingsResponse response) throws IOException {
builder.startObject("persistent");
@ -77,14 +68,6 @@ public class RestClusterUpdateSettingsAction extends BaseRestHandler {
response.getTransientSettings().toXContent(builder, request);
builder.endObject();
}
@Override
public void onFailure(Throwable e) {
if (logger.isDebugEnabled()) {
logger.debug("failed to handle cluster state", e);
}
super.onFailure(e);
}
});
}
}

View File

@ -30,7 +30,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import java.io.IOException;
@ -64,28 +64,6 @@ public class RestClusterSearchShardsAction extends BaseRestHandler {
clusterSearchShardsRequest.preference(request.param("preference"));
clusterSearchShardsRequest.indicesOptions(IndicesOptions.fromRequest(request, clusterSearchShardsRequest.indicesOptions()));
client.admin().cluster().searchShards(clusterSearchShardsRequest, new ActionListener<ClusterSearchShardsResponse>() {
@Override
public void onResponse(ClusterSearchShardsResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.admin().cluster().searchShards(clusterSearchShardsRequest, new RestToXContentListener<ClusterSearchShardsResponse>(channel));
}
}

View File

@ -19,17 +19,16 @@
package org.elasticsearch.rest.action.admin.cluster.snapshots.create;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import static org.elasticsearch.client.Requests.createSnapshotRequest;
import static org.elasticsearch.rest.RestRequest.Method.POST;
@ -54,29 +53,6 @@ public class RestCreateSnapshotAction extends BaseRestHandler {
createSnapshotRequest.source(request.content().toUtf8());
createSnapshotRequest.masterNodeTimeout(request.paramAsTime("master_timeout", createSnapshotRequest.masterNodeTimeout()));
createSnapshotRequest.waitForCompletion(request.paramAsBoolean("wait_for_completion", false));
client.admin().cluster().createSnapshot(createSnapshotRequest, new ActionListener<CreateSnapshotResponse>() {
@Override
public void onResponse(CreateSnapshotResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(response.status(), builder));
} catch (IOException e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.admin().cluster().createSnapshot(createSnapshotRequest, new RestToXContentListener<CreateSnapshotResponse>(channel));
}
}

View File

@ -19,21 +19,16 @@
package org.elasticsearch.rest.action.admin.cluster.snapshots.delete;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest;
import org.elasticsearch.action.admin.cluster.snapshots.delete.DeleteSnapshotResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import static org.elasticsearch.client.Requests.deleteSnapshotRequest;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
import static org.elasticsearch.rest.RestStatus.OK;
/**
* Deletes a snapshot
@ -50,6 +45,6 @@ public class RestDeleteSnapshotAction extends BaseRestHandler {
public void handleRequest(final RestRequest request, final RestChannel channel) {
DeleteSnapshotRequest deleteSnapshotRequest = deleteSnapshotRequest(request.param("repository"), request.param("snapshot"));
deleteSnapshotRequest.masterNodeTimeout(request.paramAsTime("master_timeout", deleteSnapshotRequest.masterNodeTimeout()));
client.admin().cluster().deleteSnapshot(deleteSnapshotRequest, new AcknowledgedRestResponseActionListener<DeleteSnapshotResponse>(request, channel, logger));
client.admin().cluster().deleteSnapshot(deleteSnapshotRequest, new AcknowledgedRestListener<DeleteSnapshotResponse>(channel));
}
}

View File

@ -19,22 +19,20 @@
package org.elasticsearch.rest.action.admin.cluster.snapshots.get;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest;
import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import static org.elasticsearch.client.Requests.getSnapshotsRequest;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
/**
* Returns information about snapshot
@ -57,28 +55,6 @@ public class RestGetSnapshotsAction extends BaseRestHandler {
}
GetSnapshotsRequest getSnapshotsRequest = getSnapshotsRequest(repository).snapshots(snapshots);
getSnapshotsRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getSnapshotsRequest.masterNodeTimeout()));
client.admin().cluster().getSnapshots(getSnapshotsRequest, new ActionListener<GetSnapshotsResponse>() {
@Override
public void onResponse(GetSnapshotsResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (IOException e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.admin().cluster().getSnapshots(getSnapshotsRequest, new RestToXContentListener<GetSnapshotsResponse>(channel));
}
}

View File

@ -19,21 +19,19 @@
package org.elasticsearch.rest.action.admin.cluster.snapshots.restore;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import static org.elasticsearch.client.Requests.restoreSnapshotRequest;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
/**
* Restores a snapshot
@ -52,28 +50,6 @@ public class RestRestoreSnapshotAction extends BaseRestHandler {
restoreSnapshotRequest.masterNodeTimeout(request.paramAsTime("master_timeout", restoreSnapshotRequest.masterNodeTimeout()));
restoreSnapshotRequest.waitForCompletion(request.paramAsBoolean("wait_for_completion", false));
restoreSnapshotRequest.source(request.content().toUtf8());
client.admin().cluster().restoreSnapshot(restoreSnapshotRequest, new ActionListener<RestoreSnapshotResponse>() {
@Override
public void onResponse(RestoreSnapshotResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (IOException e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.admin().cluster().restoreSnapshot(restoreSnapshotRequest, new RestToXContentListener<RestoreSnapshotResponse>(channel));
}
}

View File

@ -19,22 +19,20 @@
package org.elasticsearch.rest.action.admin.cluster.snapshots.status;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusRequest;
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import static org.elasticsearch.client.Requests.snapshotsStatusRequest;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
/**
* Returns status of currently running snapshot
@ -59,19 +57,6 @@ public class RestSnapshotsStatusAction extends BaseRestHandler {
SnapshotsStatusRequest snapshotsStatusResponse = snapshotsStatusRequest(repository).snapshots(snapshots);
snapshotsStatusResponse.masterNodeTimeout(request.paramAsTime("master_timeout", snapshotsStatusResponse.masterNodeTimeout()));
client.admin().cluster().snapshotsStatus(snapshotsStatusResponse, new AbstractRestResponseActionListener<SnapshotsStatusResponse>(request, channel, logger) {
@Override
public void onResponse(SnapshotsStatusResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (IOException e) {
onFailure(e);
}
}
});
client.admin().cluster().snapshotsStatus(snapshotsStatusResponse, new RestToXContentListener<SnapshotsStatusResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.cluster.state;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.client.Client;
@ -31,7 +30,7 @@ import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
import java.util.Set;
@ -78,31 +77,14 @@ public class RestClusterStateAction extends BaseRestHandler {
clusterStateRequest.indexTemplates(request.paramAsStringArray("index_templates", Strings.EMPTY_ARRAY));
}
client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() {
client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(ClusterStateResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
builder.field(Fields.CLUSTER_NAME, response.getClusterName().value());
response.getState().settingsFilter(settingsFilter).toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} 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 BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.field(Fields.CLUSTER_NAME, response.getClusterName().value());
response.getState().settingsFilter(settingsFilter).toXContent(builder, request);
builder.endObject();
return new BytesRestResponse(RestStatus.OK, builder);
}
});
}

View File

@ -19,17 +19,16 @@
package org.elasticsearch.rest.action.admin.cluster.stats;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsRequest;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
/**
@ -48,28 +47,6 @@ public class RestClusterStatsAction extends BaseRestHandler {
public void handleRequest(final RestRequest request, final RestChannel channel) {
ClusterStatsRequest clusterStatsRequest = new ClusterStatsRequest().nodesIds(request.paramAsStringArray("nodeId", null));
clusterStatsRequest.listenerThreaded(false);
client.admin().cluster().clusterStats(clusterStatsRequest, new ActionListener<ClusterStatsResponse>() {
@Override
public void onResponse(ClusterStatsResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.admin().cluster().clusterStats(clusterStatsRequest, new RestToXContentListener<ClusterStatsResponse>(channel));
}
}

View File

@ -19,17 +19,16 @@
package org.elasticsearch.rest.action.admin.cluster.tasks;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksRequest;
import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
/**
*/
@ -46,32 +45,6 @@ public class RestPendingClusterTasksAction extends BaseRestHandler {
PendingClusterTasksRequest pendingClusterTasksRequest = new PendingClusterTasksRequest();
pendingClusterTasksRequest.masterNodeTimeout(request.paramAsTime("master_timeout", pendingClusterTasksRequest.masterNodeTimeout()));
pendingClusterTasksRequest.local(request.paramAsBoolean("local", pendingClusterTasksRequest.local()));
client.admin().cluster().pendingClusterTasks(pendingClusterTasksRequest, new ActionListener<PendingClusterTasksResponse>() {
@Override
public void onResponse(PendingClusterTasksResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
if (logger.isDebugEnabled()) {
logger.debug("failed to get pending cluster tasks", e);
}
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.admin().cluster().pendingClusterTasks(pendingClusterTasksRequest, new RestToXContentListener<PendingClusterTasksResponse>(channel));
}
}

View File

@ -29,8 +29,8 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import java.io.IOException;
import java.util.Map;
import static org.elasticsearch.cluster.metadata.AliasAction.newAddAliasAction;
@ -48,7 +48,7 @@ public class RestIndicesAliasesAction extends BaseRestHandler {
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
public void handleRequest(final RestRequest request, final RestChannel channel) throws Exception {
IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest();
indicesAliasesRequest.listenerThreaded(false);
indicesAliasesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", indicesAliasesRequest.masterNodeTimeout()));
@ -131,14 +131,7 @@ public class RestIndicesAliasesAction extends BaseRestHandler {
}
}
}
} catch (Exception e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.warn("Failed to send response", e1);
}
return;
}
client.admin().indices().aliases(indicesAliasesRequest, new AcknowledgedRestResponseActionListener<IndicesAliasesResponse>(request, channel, logger));
client.admin().indices().aliases(indicesAliasesRequest, new AcknowledgedRestListener<IndicesAliasesResponse>(channel));
}
}

View File

@ -25,6 +25,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
@ -48,6 +49,6 @@ public class RestIndexDeleteAliasesAction extends BaseRestHandler {
indicesAliasesRequest.removeAlias(indices, aliases);
indicesAliasesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", indicesAliasesRequest.masterNodeTimeout()));
client.admin().indices().aliases(indicesAliasesRequest, new AcknowledgedRestResponseActionListener<IndicesAliasesResponse>(request, channel, logger));
client.admin().indices().aliases(indicesAliasesRequest, new AcknowledgedRestListener<IndicesAliasesResponse>(channel));
}
}

View File

@ -20,7 +20,6 @@
package org.elasticsearch.rest.action.admin.indices.alias.get;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -33,9 +32,8 @@ import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
@ -64,50 +62,33 @@ public class RestGetAliasesAction extends BaseRestHandler {
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
getAliasesRequest.local(request.paramAsBoolean("local", getAliasesRequest.local()));
client.admin().indices().getAliases(getAliasesRequest, new ActionListener<GetAliasesResponse>() {
client.admin().indices().getAliases(getAliasesRequest, new RestBuilderListener<GetAliasesResponse>(channel) {
@Override
public void onResponse(GetAliasesResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
// empty body, if indices were specified but no aliases were
if (indices.length > 0 && response.getAliases().isEmpty()) {
channel.sendResponse(new BytesRestResponse(OK, RestXContentBuilder.emptyBuilder(request)));
return;
} else if (response.getAliases().isEmpty()) {
String message = String.format(Locale.ROOT, "alias [%s] missing", toNamesString(getAliasesRequest.aliases()));
builder.startObject()
.field("error", message)
.field("status", RestStatus.NOT_FOUND.getStatus())
.endObject();
channel.sendResponse(new BytesRestResponse(RestStatus.NOT_FOUND, builder));
return;
}
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
// empty body, if indices were specified but no aliases were
if (indices.length > 0 && response.getAliases().isEmpty()) {
return new BytesRestResponse(OK, builder.startObject().endObject());
} else if (response.getAliases().isEmpty()) {
String message = String.format(Locale.ROOT, "alias [%s] missing", toNamesString(getAliasesRequest.aliases()));
builder.startObject()
.field("error", message)
.field("status", RestStatus.NOT_FOUND.getStatus())
.endObject();
return new BytesRestResponse(RestStatus.NOT_FOUND, builder);
}
builder.startObject();
for (ObjectObjectCursor<String, List<AliasMetaData>> entry : response.getAliases()) {
builder.startObject(entry.key, XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(Fields.ALIASES);
for (AliasMetaData alias : entry.value) {
AliasMetaData.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
builder.endObject();
builder.endObject();
builder.startObject();
for (ObjectObjectCursor<String, List<AliasMetaData>> entry : response.getAliases()) {
builder.startObject(entry.key, XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(Fields.ALIASES);
for (AliasMetaData alias : entry.value) {
AliasMetaData.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
builder.endObject();
}
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.alias.get;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.client.Client;
@ -34,9 +33,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.common.Strings.isAllOrWildcard;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -62,49 +59,35 @@ public class RestGetIndicesAliasesAction extends BaseRestHandler {
final String[] aliases = Strings.splitStringByCommaToArray(request.param("name"));
ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest()
.routingTable(false)
.nodes(false)
.indices(indices);
.routingTable(false)
.nodes(false)
.indices(indices);
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.listenerThreaded(false);
client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() {
client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(ClusterStateResponse response) {
try {
MetaData metaData = response.getState().metaData();
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception {
MetaData metaData = response.getState().metaData();
builder.startObject();
final boolean isAllAliasesRequested = isAllOrWildcard(aliases);
for (IndexMetaData indexMetaData : metaData) {
builder.startObject(indexMetaData.index(), XContentBuilder.FieldCaseConversion.NONE);
builder.startObject("aliases");
final boolean isAllAliasesRequested = isAllOrWildcard(aliases);
for (IndexMetaData indexMetaData : metaData) {
builder.startObject(indexMetaData.index(), XContentBuilder.FieldCaseConversion.NONE);
builder.startObject("aliases");
for (ObjectCursor<AliasMetaData> cursor : indexMetaData.aliases().values()) {
if (isAllAliasesRequested || Regex.simpleMatch(aliases, cursor.value.alias())) {
AliasMetaData.Builder.toXContent(cursor.value, builder, ToXContent.EMPTY_PARAMS);
}
for (ObjectCursor<AliasMetaData> cursor : indexMetaData.aliases().values()) {
if (isAllAliasesRequested || Regex.simpleMatch(aliases, cursor.value.alias())) {
AliasMetaData.Builder.toXContent(cursor.value, builder, ToXContent.EMPTY_PARAMS);
}
builder.endObject();
builder.endObject();
}
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
builder.endObject();
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -30,8 +30,8 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import java.io.IOException;
import java.util.Map;
import static org.elasticsearch.rest.RestRequest.Method.POST;
@ -50,7 +50,7 @@ public class RestIndexPutAliasAction extends BaseRestHandler {
controller.registerHandler(PUT, "/_aliases/{name}", this);
controller.registerHandler(PUT, "/{index}/_alias", this);
controller.registerHandler(PUT, "/_alias", this);
controller.registerHandler(POST, "/{index}/_alias/{name}", this);
controller.registerHandler(POST, "/_alias/{name}", this);
controller.registerHandler(POST, "/{index}/_aliases/{name}", this);
@ -60,7 +60,7 @@ public class RestIndexPutAliasAction extends BaseRestHandler {
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
public void handleRequest(final RestRequest request, final RestChannel channel) throws Exception {
String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
String alias = request.param("name");
Map<String, Object> filter = null;
@ -69,9 +69,7 @@ public class RestIndexPutAliasAction extends BaseRestHandler {
String searchRouting = null;
if (request.hasContent()) {
XContentParser parser = null;
try {
parser = XContentFactory.xContent(request.content()).createParser(request.content());
try (XContentParser parser = XContentFactory.xContent(request.content()).createParser(request.content())) {
XContentParser.Token token = parser.nextToken();
if (token == null) {
throw new ElasticsearchIllegalArgumentException("No index alias is specified");
@ -98,27 +96,16 @@ public class RestIndexPutAliasAction extends BaseRestHandler {
}
}
}
} catch (Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.warn("Failed to send response", e1);
}
return;
} finally {
if (parser != null) {
parser.close();
}
}
}
IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest();
indicesAliasesRequest.timeout(request.paramAsTime("timeout", indicesAliasesRequest.timeout()));
String[] aliases = new String[] {alias};
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);
@ -132,6 +119,6 @@ public class RestIndexPutAliasAction extends BaseRestHandler {
if (filter != null) {
aliasAction.filter(filter);
}
client.admin().indices().aliases(indicesAliasesRequest, new AcknowledgedRestResponseActionListener<IndicesAliasesResponse>(request, channel, logger));
client.admin().indices().aliases(indicesAliasesRequest, new AcknowledgedRestListener<IndicesAliasesResponse>(channel));
}
}

View File

@ -19,21 +19,19 @@
package org.elasticsearch.rest.action.admin.indices.analyze;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeRequest;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import java.io.IOException;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
/**
*
@ -56,12 +54,7 @@ public class RestAnalyzeAction extends BaseRestHandler {
text = request.content().toUtf8();
}
if (text == null) {
try {
channel.sendResponse(new BytesRestResponse(request, new ElasticsearchIllegalArgumentException("text is missing")));
} catch (IOException e1) {
logger.warn("Failed to send response", e1);
}
return;
throw new ElasticsearchIllegalArgumentException("text is missing");
}
AnalyzeRequest analyzeRequest = new AnalyzeRequest(request.param("index"), text);
@ -72,28 +65,6 @@ public class RestAnalyzeAction extends BaseRestHandler {
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 BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.admin().indices().analyze(analyzeRequest, new RestToXContentListener<AnalyzeResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.cache.clear;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest;
import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -30,13 +29,10 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestActions.buildBroadcastShardsHeader;
@ -60,69 +56,44 @@ public class RestClearIndicesCacheAction extends BaseRestHandler {
ClearIndicesCacheRequest clearIndicesCacheRequest = new ClearIndicesCacheRequest(Strings.splitStringByCommaToArray(request.param("index")));
clearIndicesCacheRequest.listenerThreaded(false);
clearIndicesCacheRequest.indicesOptions(IndicesOptions.fromRequest(request, clearIndicesCacheRequest.indicesOptions()));
try {
if (request.hasParam("filter")) {
clearIndicesCacheRequest.filterCache(request.paramAsBoolean("filter", clearIndicesCacheRequest.filterCache()));
}
if (request.hasParam("filter_cache")) {
clearIndicesCacheRequest.filterCache(request.paramAsBoolean("filter_cache", clearIndicesCacheRequest.filterCache()));
}
if (request.hasParam("field_data")) {
clearIndicesCacheRequest.fieldDataCache(request.paramAsBoolean("field_data", clearIndicesCacheRequest.fieldDataCache()));
}
if (request.hasParam("fielddata")) {
clearIndicesCacheRequest.fieldDataCache(request.paramAsBoolean("fielddata", clearIndicesCacheRequest.fieldDataCache()));
}
if (request.hasParam("id")) {
clearIndicesCacheRequest.idCache(request.paramAsBoolean("id", clearIndicesCacheRequest.idCache()));
}
if (request.hasParam("id_cache")) {
clearIndicesCacheRequest.idCache(request.paramAsBoolean("id_cache", clearIndicesCacheRequest.idCache()));
}
if (request.hasParam("recycler")) {
clearIndicesCacheRequest.recycler(request.paramAsBoolean("recycler", clearIndicesCacheRequest.recycler()));
}
clearIndicesCacheRequest.fields(request.paramAsStringArray("fields", clearIndicesCacheRequest.fields()));
clearIndicesCacheRequest.filterKeys(request.paramAsStringArray("filter_keys", clearIndicesCacheRequest.filterKeys()));
BroadcastOperationThreading operationThreading = BroadcastOperationThreading.fromString(request.param("operationThreading"), BroadcastOperationThreading.THREAD_PER_SHARD);
if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
// since we don't spawn, don't allow no_threads, but change it to a single thread
operationThreading = BroadcastOperationThreading.THREAD_PER_SHARD;
}
clearIndicesCacheRequest.operationThreading(operationThreading);
} catch (Exception e) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
if (request.hasParam("filter")) {
clearIndicesCacheRequest.filterCache(request.paramAsBoolean("filter", clearIndicesCacheRequest.filterCache()));
}
client.admin().indices().clearCache(clearIndicesCacheRequest, new ActionListener<ClearIndicesCacheResponse>() {
if (request.hasParam("filter_cache")) {
clearIndicesCacheRequest.filterCache(request.paramAsBoolean("filter_cache", clearIndicesCacheRequest.filterCache()));
}
if (request.hasParam("field_data")) {
clearIndicesCacheRequest.fieldDataCache(request.paramAsBoolean("field_data", clearIndicesCacheRequest.fieldDataCache()));
}
if (request.hasParam("fielddata")) {
clearIndicesCacheRequest.fieldDataCache(request.paramAsBoolean("fielddata", clearIndicesCacheRequest.fieldDataCache()));
}
if (request.hasParam("id")) {
clearIndicesCacheRequest.idCache(request.paramAsBoolean("id", clearIndicesCacheRequest.idCache()));
}
if (request.hasParam("id_cache")) {
clearIndicesCacheRequest.idCache(request.paramAsBoolean("id_cache", clearIndicesCacheRequest.idCache()));
}
if (request.hasParam("recycler")) {
clearIndicesCacheRequest.recycler(request.paramAsBoolean("recycler", clearIndicesCacheRequest.recycler()));
}
clearIndicesCacheRequest.fields(request.paramAsStringArray("fields", clearIndicesCacheRequest.fields()));
clearIndicesCacheRequest.filterKeys(request.paramAsStringArray("filter_keys", clearIndicesCacheRequest.filterKeys()));
BroadcastOperationThreading operationThreading = BroadcastOperationThreading.fromString(request.param("operationThreading"), BroadcastOperationThreading.THREAD_PER_SHARD);
if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
// since we don't spawn, don't allow no_threads, but change it to a single thread
operationThreading = BroadcastOperationThreading.THREAD_PER_SHARD;
}
clearIndicesCacheRequest.operationThreading(operationThreading);
client.admin().indices().clearCache(clearIndicesCacheRequest, new RestBuilderListener<ClearIndicesCacheResponse>(channel) {
@Override
public void onResponse(ClearIndicesCacheResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
buildBroadcastShardsHeader(builder, response);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(ClearIndicesCacheResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
buildBroadcastShardsHeader(builder, response);
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -27,6 +27,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
/**
*
@ -47,6 +48,6 @@ public class RestCloseIndexAction extends BaseRestHandler {
closeIndexRequest.masterNodeTimeout(request.paramAsTime("master_timeout", closeIndexRequest.masterNodeTimeout()));
closeIndexRequest.timeout(request.paramAsTime("timeout", closeIndexRequest.timeout()));
closeIndexRequest.indicesOptions(IndicesOptions.fromRequest(request, closeIndexRequest.indicesOptions()));
client.admin().indices().close(closeIndexRequest, new AcknowledgedRestResponseActionListener<CloseIndexResponse>(request, channel, logger));
client.admin().indices().close(closeIndexRequest, new AcknowledgedRestListener<CloseIndexResponse>(channel));
}
}

View File

@ -24,9 +24,11 @@ import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import java.io.IOException;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
/**
*
@ -46,21 +48,10 @@ public class RestCreateIndexAction extends BaseRestHandler {
CreateIndexRequest createIndexRequest = new CreateIndexRequest(request.param("index"));
createIndexRequest.listenerThreaded(false);
if (request.hasContent()) {
try {
createIndexRequest.source(request.content());
} catch (Exception e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.warn("Failed to send response", e1);
}
return;
}
createIndexRequest.source(request.content());
}
createIndexRequest.timeout(request.paramAsTime("timeout", createIndexRequest.timeout()));
createIndexRequest.masterNodeTimeout(request.paramAsTime("master_timeout", createIndexRequest.masterNodeTimeout()));
client.admin().indices().create(createIndexRequest, new AcknowledgedRestResponseActionListener<CreateIndexResponse>(request, channel, logger));
client.admin().indices().create(createIndexRequest, new AcknowledgedRestListener<CreateIndexResponse>(channel));
}
}

View File

@ -27,6 +27,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
/**
*
@ -47,6 +48,6 @@ public class RestDeleteIndexAction extends BaseRestHandler {
deleteIndexRequest.timeout(request.paramAsTime("timeout", deleteIndexRequest.timeout()));
deleteIndexRequest.masterNodeTimeout(request.paramAsTime("master_timeout", deleteIndexRequest.masterNodeTimeout()));
deleteIndexRequest.indicesOptions(IndicesOptions.fromRequest(request, deleteIndexRequest.indicesOptions()));
client.admin().indices().delete(deleteIndexRequest, new AcknowledgedRestResponseActionListener<DeleteIndexResponse>(request, channel, logger));
client.admin().indices().delete(deleteIndexRequest, new AcknowledgedRestListener<DeleteIndexResponse>(channel));
}
}

View File

@ -19,8 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.exists.indices;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -30,6 +28,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
@ -57,28 +56,16 @@ public class RestIndicesExistsAction extends BaseRestHandler {
indicesExistsRequest.indicesOptions(IndicesOptions.fromRequest(request, indicesExistsRequest.indicesOptions()));
indicesExistsRequest.local(request.paramAsBoolean("local", indicesExistsRequest.local()));
indicesExistsRequest.listenerThreaded(false);
client.admin().indices().exists(indicesExistsRequest, new ActionListener<IndicesExistsResponse>() {
client.admin().indices().exists(indicesExistsRequest, new RestResponseListener<IndicesExistsResponse>(channel) {
@Override
public void onResponse(IndicesExistsResponse response) {
try {
if (response.isExists()) {
channel.sendResponse(new BytesRestResponse(OK));
} else {
channel.sendResponse(new BytesRestResponse(NOT_FOUND));
}
} catch (Throwable e) {
onFailure(e);
public RestResponse buildResponse(IndicesExistsResponse response) {
if (response.isExists()) {
return new BytesRestResponse(OK);
} else {
return new BytesRestResponse(NOT_FOUND);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(ExceptionsHelper.status(e)));
} catch (Exception e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}
}

View File

@ -18,8 +18,6 @@
*/
package org.elasticsearch.rest.action.admin.indices.exists.types;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -28,6 +26,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
@ -52,26 +51,13 @@ public class RestTypesExistsAction extends BaseRestHandler {
typesExistsRequest.listenerThreaded(false);
typesExistsRequest.local(request.paramAsBoolean("local", typesExistsRequest.local()));
typesExistsRequest.indicesOptions(IndicesOptions.fromRequest(request, typesExistsRequest.indicesOptions()));
client.admin().indices().typesExists(typesExistsRequest, new ActionListener<TypesExistsResponse>() {
client.admin().indices().typesExists(typesExistsRequest, new RestResponseListener<TypesExistsResponse>(channel) {
@Override
public void onResponse(TypesExistsResponse response) {
try {
if (response.isExists()) {
channel.sendResponse(new BytesRestResponse(OK));
} else {
channel.sendResponse(new BytesRestResponse(NOT_FOUND));
}
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(ExceptionsHelper.status(e)));
} catch (Exception e1) {
logger.error("Failed to send failure response", e1);
public RestResponse buildResponse(TypesExistsResponse response) throws Exception {
if (response.isExists()) {
return new BytesRestResponse(OK);
} else {
return new BytesRestResponse(NOT_FOUND);
}
}
});

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.flush;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.flush.FlushRequest;
import org.elasticsearch.action.admin.indices.flush.FlushResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -30,9 +29,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
@ -67,29 +64,13 @@ public class RestFlushAction extends BaseRestHandler {
flushRequest.operationThreading(operationThreading);
flushRequest.full(request.paramAsBoolean("full", flushRequest.full()));
flushRequest.force(request.paramAsBoolean("force", flushRequest.force()));
client.admin().indices().flush(flushRequest, new ActionListener<FlushResponse>() {
client.admin().indices().flush(flushRequest, new RestBuilderListener<FlushResponse>(channel) {
@Override
public void onResponse(FlushResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
buildBroadcastShardsHeader(builder, response);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(FlushResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
buildBroadcastShardsHeader(builder, response);
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -27,6 +27,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import static org.elasticsearch.client.Requests.deleteMappingRequest;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
@ -56,6 +57,6 @@ public class RestDeleteMappingAction extends BaseRestHandler {
deleteMappingRequest.timeout(request.paramAsTime("timeout", deleteMappingRequest.timeout()));
deleteMappingRequest.masterNodeTimeout(request.paramAsTime("master_timeout", deleteMappingRequest.masterNodeTimeout()));
deleteMappingRequest.indicesOptions(IndicesOptions.fromRequest(request, deleteMappingRequest.indicesOptions()));
client.admin().indices().deleteMapping(deleteMappingRequest, new AcknowledgedRestResponseActionListener<DeleteMappingResponse>(request, channel, logger));
client.admin().indices().deleteMapping(deleteMappingRequest, new AcknowledgedRestListener<DeleteMappingResponse>(channel));
}
}

View File

@ -20,7 +20,6 @@
package org.elasticsearch.rest.action.admin.indices.mapping.get;
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsRequest;
import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse;
import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetaData;
@ -32,7 +31,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
import java.util.Map;
@ -40,7 +39,6 @@ import java.util.Map;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.emptyBuilder;
/**
*
@ -66,48 +64,31 @@ public class RestGetFieldMappingAction extends BaseRestHandler {
getMappingsRequest.indices(indices).types(types).fields(fields).includeDefaults(request.paramAsBoolean("include_defaults", false));
getMappingsRequest.indicesOptions(IndicesOptions.fromRequest(request, getMappingsRequest.indicesOptions()));
getMappingsRequest.local(request.paramAsBoolean("local", getMappingsRequest.local()));
client.admin().indices().getFieldMappings(getMappingsRequest, new ActionListener<GetFieldMappingsResponse>() {
client.admin().indices().getFieldMappings(getMappingsRequest, new RestBuilderListener<GetFieldMappingsResponse>(channel) {
@SuppressWarnings("unchecked")
@Override
public void onResponse(GetFieldMappingsResponse response) {
try {
ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappingsByIndex = response.mappings();
public RestResponse buildResponse(GetFieldMappingsResponse response, XContentBuilder builder) throws Exception {
ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappingsByIndex = response.mappings();
boolean isPossibleSingleFieldRequest = indices.length == 1 && types.length == 1 && fields.length == 1;
if (isPossibleSingleFieldRequest && isFieldMappingMissingField(mappingsByIndex)) {
channel.sendResponse(new BytesRestResponse(OK, emptyBuilder(request)));
return;
}
RestStatus status = OK;
if (mappingsByIndex.isEmpty() && fields.length > 0) {
status = NOT_FOUND;
}
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
channel.sendResponse(new BytesRestResponse(status, builder));
} catch (Throwable e) {
onFailure(e);
boolean isPossibleSingleFieldRequest = indices.length == 1 && types.length == 1 && fields.length == 1;
if (isPossibleSingleFieldRequest && isFieldMappingMissingField(mappingsByIndex)) {
return new BytesRestResponse(OK, builder.startObject().endObject());
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
RestStatus status = OK;
if (mappingsByIndex.isEmpty() && fields.length > 0) {
status = NOT_FOUND;
}
builder.startObject();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
return new BytesRestResponse(status, builder);
}
});
}
/**
*
* Helper method to find out if the only included fieldmapping metadata is typed NULL, which means
* that type and index exist, but the field did not
*/

View File

@ -20,7 +20,6 @@
package org.elasticsearch.rest.action.admin.indices.mapping.get;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -36,9 +35,7 @@ import org.elasticsearch.index.Index;
import org.elasticsearch.indices.IndexMissingException;
import org.elasticsearch.indices.TypeMissingException;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
@ -67,57 +64,39 @@ public class RestGetMappingAction extends BaseRestHandler {
getMappingsRequest.indices(indices).types(types);
getMappingsRequest.indicesOptions(IndicesOptions.fromRequest(request, getMappingsRequest.indicesOptions()));
getMappingsRequest.local(request.paramAsBoolean("local", getMappingsRequest.local()));
client.admin().indices().getMappings(getMappingsRequest, new ActionListener<GetMappingsResponse>() {
client.admin().indices().getMappings(getMappingsRequest, new RestBuilderListener<GetMappingsResponse>(channel) {
@Override
public void onResponse(GetMappingsResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mappingsByIndex = response.getMappings();
if (mappingsByIndex.isEmpty()) {
if (indices.length != 0 && types.length != 0) {
channel.sendResponse(new BytesRestResponse(OK, RestXContentBuilder.emptyBuilder(request)));
} else if (indices.length != 0) {
channel.sendResponse(new BytesRestResponse(request, new IndexMissingException(new Index(indices[0]))));
} else if (types.length != 0) {
channel.sendResponse(new BytesRestResponse(request, new TypeMissingException(new Index("_all"), types[0])));
} else {
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
}
return;
public RestResponse buildResponse(GetMappingsResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mappingsByIndex = response.getMappings();
if (mappingsByIndex.isEmpty()) {
if (indices.length != 0 && types.length != 0) {
return new BytesRestResponse(OK, builder.endObject());
} else if (indices.length != 0) {
return new BytesRestResponse(channel, new IndexMissingException(new Index(indices[0])));
} else if (types.length != 0) {
return new BytesRestResponse(channel, new TypeMissingException(new Index("_all"), types[0]));
} else {
return new BytesRestResponse(OK, builder.endObject());
}
}
for (ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>> indexEntry : mappingsByIndex) {
if (indexEntry.value.isEmpty()) {
continue;
}
builder.startObject(indexEntry.key, XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(Fields.MAPPINGS);
for (ObjectObjectCursor<String, MappingMetaData> typeEntry : indexEntry.value) {
builder.field(typeEntry.key);
builder.map(typeEntry.value.sourceAsMap());
}
builder.endObject();
builder.endObject();
for (ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>> indexEntry : mappingsByIndex) {
if (indexEntry.value.isEmpty()) {
continue;
}
builder.startObject(indexEntry.key, XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(Fields.MAPPINGS);
for (ObjectObjectCursor<String, MappingMetaData> typeEntry : indexEntry.value) {
builder.field(typeEntry.key);
builder.map(typeEntry.value.sourceAsMap());
}
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
builder.endObject();
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -27,6 +27,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import static org.elasticsearch.client.Requests.putMappingRequest;
import static org.elasticsearch.rest.RestRequest.Method.POST;
@ -73,6 +74,6 @@ public class RestPutMappingAction extends BaseRestHandler {
putMappingRequest.ignoreConflicts(request.paramAsBoolean("ignore_conflicts", putMappingRequest.ignoreConflicts()));
putMappingRequest.masterNodeTimeout(request.paramAsTime("master_timeout", putMappingRequest.masterNodeTimeout()));
putMappingRequest.indicesOptions(IndicesOptions.fromRequest(request, putMappingRequest.indicesOptions()));
client.admin().indices().putMapping(putMappingRequest, new AcknowledgedRestResponseActionListener<PutMappingResponse>(request, channel, logger));
client.admin().indices().putMapping(putMappingRequest, new AcknowledgedRestListener<PutMappingResponse>(channel));
}
}

View File

@ -27,6 +27,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
/**
*
@ -47,6 +48,6 @@ public class RestOpenIndexAction extends BaseRestHandler {
openIndexRequest.timeout(request.paramAsTime("timeout", openIndexRequest.timeout()));
openIndexRequest.masterNodeTimeout(request.paramAsTime("master_timeout", openIndexRequest.masterNodeTimeout()));
openIndexRequest.indicesOptions(IndicesOptions.fromRequest(request, openIndexRequest.indicesOptions()));
client.admin().indices().open(openIndexRequest, new AcknowledgedRestResponseActionListener<OpenIndexResponse>(request, channel, logger));
client.admin().indices().open(openIndexRequest, new AcknowledgedRestListener<OpenIndexResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.optimize;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.optimize.OptimizeRequest;
import org.elasticsearch.action.admin.indices.optimize.OptimizeResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -30,13 +29,10 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestActions.buildBroadcastShardsHeader;
@ -60,51 +56,26 @@ public class RestOptimizeAction extends BaseRestHandler {
OptimizeRequest optimizeRequest = new OptimizeRequest(Strings.splitStringByCommaToArray(request.param("index")));
optimizeRequest.listenerThreaded(false);
optimizeRequest.indicesOptions(IndicesOptions.fromRequest(request, optimizeRequest.indicesOptions()));
try {
optimizeRequest.waitForMerge(request.paramAsBoolean("wait_for_merge", optimizeRequest.waitForMerge()));
optimizeRequest.maxNumSegments(request.paramAsInt("max_num_segments", optimizeRequest.maxNumSegments()));
optimizeRequest.onlyExpungeDeletes(request.paramAsBoolean("only_expunge_deletes", optimizeRequest.onlyExpungeDeletes()));
optimizeRequest.flush(request.paramAsBoolean("flush", optimizeRequest.flush()));
optimizeRequest.force(request.paramAsBoolean("force", optimizeRequest.force()));
optimizeRequest.waitForMerge(request.paramAsBoolean("wait_for_merge", optimizeRequest.waitForMerge()));
optimizeRequest.maxNumSegments(request.paramAsInt("max_num_segments", optimizeRequest.maxNumSegments()));
optimizeRequest.onlyExpungeDeletes(request.paramAsBoolean("only_expunge_deletes", optimizeRequest.onlyExpungeDeletes()));
optimizeRequest.flush(request.paramAsBoolean("flush", optimizeRequest.flush()));
optimizeRequest.force(request.paramAsBoolean("force", optimizeRequest.force()));
BroadcastOperationThreading operationThreading = BroadcastOperationThreading.fromString(request.param("operation_threading"), BroadcastOperationThreading.THREAD_PER_SHARD);
if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
// since we don't spawn, don't allow no_threads, but change it to a single thread
operationThreading = BroadcastOperationThreading.THREAD_PER_SHARD;
}
optimizeRequest.operationThreading(operationThreading);
} catch (Exception e) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
BroadcastOperationThreading operationThreading = BroadcastOperationThreading.fromString(request.param("operation_threading"), BroadcastOperationThreading.THREAD_PER_SHARD);
if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
// since we don't spawn, don't allow no_threads, but change it to a single thread
operationThreading = BroadcastOperationThreading.THREAD_PER_SHARD;
}
client.admin().indices().optimize(optimizeRequest, new ActionListener<OptimizeResponse>() {
optimizeRequest.operationThreading(operationThreading);
client.admin().indices().optimize(optimizeRequest, new RestBuilderListener<OptimizeResponse>(channel) {
@Override
public void onResponse(OptimizeResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
buildBroadcastShardsHeader(builder, response);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(OptimizeResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
buildBroadcastShardsHeader(builder, response);
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -19,9 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.recovery;
import java.io.IOException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.recovery.RecoveryRequest;
import org.elasticsearch.action.admin.indices.recovery.RecoveryResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -31,16 +28,15 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestActions.buildBroadcastShardsHeader;
/**
* REST handler to report on index recoveries.
*/
public class RestRecoveryAction extends BaseRestHandler {
public class RestRecoveryAction extends BaseRestHandler {
@Inject
public RestRecoveryAction(Settings settings, Client client, RestController controller) {
@ -58,32 +54,16 @@ public class RestRecoveryAction extends BaseRestHandler {
recoveryRequest.listenerThreaded(false);
recoveryRequest.indicesOptions(IndicesOptions.fromRequest(request, recoveryRequest.indicesOptions()));
client.admin().indices().recoveries(recoveryRequest, new ActionListener<RecoveryResponse>() {
client.admin().indices().recoveries(recoveryRequest, new RestBuilderListener<RecoveryResponse>(channel) {
@Override
public void onResponse(RecoveryResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
if (response.hasRecoveries()) {
response.detailed(recoveryRequest.detailed());
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
}
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException ioe) {
logger.error("Failed to send failure response", ioe);
public RestResponse buildResponse(RecoveryResponse response, XContentBuilder builder) throws Exception {
if (response.hasRecoveries()) {
response.detailed(recoveryRequest.detailed());
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
}
return new BytesRestResponse(OK, builder);
}
});

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.refresh;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -30,7 +29,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
@ -66,29 +65,13 @@ public class RestRefreshAction extends BaseRestHandler {
operationThreading = BroadcastOperationThreading.THREAD_PER_SHARD;
}
refreshRequest.operationThreading(operationThreading);
client.admin().indices().refresh(refreshRequest, new ActionListener<RefreshResponse>() {
client.admin().indices().refresh(refreshRequest, new RestBuilderListener<RefreshResponse>(channel) {
@Override
public void onResponse(RefreshResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
buildBroadcastShardsHeader(builder, response);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(RefreshResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
buildBroadcastShardsHeader(builder, response);
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.segments;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.segments.IndicesSegmentResponse;
import org.elasticsearch.action.admin.indices.segments.IndicesSegmentsRequest;
import org.elasticsearch.action.support.IndicesOptions;
@ -30,9 +29,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
@ -60,28 +57,14 @@ public class RestIndicesSegmentsAction extends BaseRestHandler {
operationThreading = BroadcastOperationThreading.SINGLE_THREAD;
}
indicesSegmentsRequest.operationThreading(operationThreading);
client.admin().indices().segments(indicesSegmentsRequest, new ActionListener<IndicesSegmentResponse>() {
client.admin().indices().segments(indicesSegmentsRequest, new RestBuilderListener<IndicesSegmentResponse>(channel) {
@Override
public void onResponse(IndicesSegmentResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
buildBroadcastShardsHeader(builder, response);
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(IndicesSegmentResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
buildBroadcastShardsHeader(builder, response);
response.toXContent(builder, request);
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -20,7 +20,6 @@
package org.elasticsearch.rest.action.admin.indices.settings;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -31,9 +30,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
@ -59,38 +56,24 @@ public class RestGetSettingsAction extends BaseRestHandler {
.names(names);
getSettingsRequest.local(request.paramAsBoolean("local", getSettingsRequest.local()));
client.admin().indices().getSettings(getSettingsRequest, new ActionListener<GetSettingsResponse>() {
client.admin().indices().getSettings(getSettingsRequest, new RestBuilderListener<GetSettingsResponse>(channel) {
@Override
public void onResponse(GetSettingsResponse getSettingsResponse) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
for (ObjectObjectCursor<String, Settings> cursor : getSettingsResponse.getIndexToSettings()) {
// no settings, jump over it to shorten the response data
if (cursor.value.getAsMap().isEmpty()) {
continue;
}
builder.startObject(cursor.key, XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(Fields.SETTINGS);
cursor.value.toXContent(builder, request);
builder.endObject();
builder.endObject();
public RestResponse buildResponse(GetSettingsResponse getSettingsResponse, XContentBuilder builder) throws Exception {
builder.startObject();
for (ObjectObjectCursor<String, Settings> cursor : getSettingsResponse.getIndexToSettings()) {
// no settings, jump over it to shorten the response data
if (cursor.value.getAsMap().isEmpty()) {
continue;
}
builder.startObject(cursor.key, XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(Fields.SETTINGS);
cursor.value.toXContent(builder, request);
builder.endObject();
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (IOException e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -27,14 +27,12 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsException;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import java.io.IOException;
import java.util.Map;
import static org.elasticsearch.client.Requests.updateSettingsRequest;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
/**
*
@ -59,24 +57,15 @@ public class RestUpdateSettingsAction extends BaseRestHandler {
ImmutableSettings.Builder updateSettings = ImmutableSettings.settingsBuilder();
String bodySettingsStr = request.content().toUtf8();
if (Strings.hasText(bodySettingsStr)) {
try {
Settings buildSettings = ImmutableSettings.settingsBuilder().loadFromSource(bodySettingsStr).build();
for (Map.Entry<String, String> entry : buildSettings.getAsMap().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// clean up in case the body is wrapped with "settings" : { ... }
if (key.startsWith("settings.")) {
key = key.substring("settings.".length());
}
updateSettings.put(key, value);
Settings buildSettings = ImmutableSettings.settingsBuilder().loadFromSource(bodySettingsStr).build();
for (Map.Entry<String, String> entry : buildSettings.getAsMap().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// clean up in case the body is wrapped with "settings" : { ... }
if (key.startsWith("settings.")) {
key = key.substring("settings.".length());
}
} catch (Exception e) {
try {
channel.sendResponse(new BytesRestResponse(request, BAD_REQUEST, new SettingsException("Failed to parse index settings", e)));
} catch (IOException e1) {
logger.warn("Failed to send response", e1);
}
return;
updateSettings.put(key, value);
}
}
for (Map.Entry<String, String> entry : request.params().entrySet()) {
@ -87,6 +76,6 @@ public class RestUpdateSettingsAction extends BaseRestHandler {
}
updateSettingsRequest.settings(updateSettings);
client.admin().indices().updateSettings(updateSettingsRequest, new AcknowledgedRestResponseActionListener<UpdateSettingsResponse>(request, channel, logger));
client.admin().indices().updateSettings(updateSettingsRequest, new AcknowledgedRestListener<UpdateSettingsResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.stats;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -29,7 +28,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
import java.util.Set;
@ -100,28 +99,14 @@ public class RestIndicesStatsAction extends BaseRestHandler {
indicesStatsRequest.fieldDataFields(request.paramAsStringArray("fielddata_fields", request.paramAsStringArray("fields", Strings.EMPTY_ARRAY)));
}
client.admin().indices().stats(indicesStatsRequest, new ActionListener<IndicesStatsResponse>() {
client.admin().indices().stats(indicesStatsRequest, new RestBuilderListener<IndicesStatsResponse>(channel) {
@Override
public void onResponse(IndicesStatsResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
buildBroadcastShardsHeader(builder, response);
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(IndicesStatsResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
buildBroadcastShardsHeader(builder, response);
response.toXContent(builder, request);
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.status;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.status.IndicesStatusRequest;
import org.elasticsearch.action.admin.indices.status.IndicesStatusResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -31,7 +30,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
@ -69,28 +68,14 @@ public class RestIndicesStatusAction extends BaseRestHandler {
operationThreading = BroadcastOperationThreading.SINGLE_THREAD;
}
indicesStatusRequest.operationThreading(operationThreading);
client.admin().indices().status(indicesStatusRequest, new ActionListener<IndicesStatusResponse>() {
client.admin().indices().status(indicesStatusRequest, new RestBuilderListener<IndicesStatusResponse>(channel) {
@Override
public void onResponse(IndicesStatusResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
buildBroadcastShardsHeader(builder, response);
response.toXContent(builder, request, settingsFilter);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(IndicesStatusResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
buildBroadcastShardsHeader(builder, response);
response.toXContent(builder, request, settingsFilter);
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -24,6 +24,7 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
/**
*
@ -41,6 +42,6 @@ public class RestDeleteIndexTemplateAction extends BaseRestHandler {
DeleteIndexTemplateRequest deleteIndexTemplateRequest = new DeleteIndexTemplateRequest(request.param("name"));
deleteIndexTemplateRequest.listenerThreaded(false);
deleteIndexTemplateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", deleteIndexTemplateRequest.masterNodeTimeout()));
client.admin().indices().deleteTemplate(deleteIndexTemplateRequest, new AcknowledgedRestResponseActionListener<DeleteIndexTemplateResponse>(request, channel, logger));
client.admin().indices().deleteTemplate(deleteIndexTemplateRequest, new AcknowledgedRestListener<DeleteIndexTemplateResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.template.get;
import com.google.common.collect.Maps;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest;
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse;
import org.elasticsearch.client.Client;
@ -30,7 +29,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.util.Map;
@ -61,38 +60,24 @@ public class RestGetIndexTemplateAction extends BaseRestHandler {
final boolean implicitAll = getIndexTemplatesRequest.names().length == 0;
client.admin().indices().getTemplates(getIndexTemplatesRequest, new ActionListener<GetIndexTemplatesResponse>() {
client.admin().indices().getTemplates(getIndexTemplatesRequest, new RestBuilderListener<GetIndexTemplatesResponse>(channel) {
@Override
public void onResponse(GetIndexTemplatesResponse getIndexTemplatesResponse) {
try {
boolean templateExists = getIndexTemplatesResponse.getIndexTemplates().size() > 0;
public RestResponse buildResponse(GetIndexTemplatesResponse getIndexTemplatesResponse, XContentBuilder builder) throws Exception {
boolean templateExists = getIndexTemplatesResponse.getIndexTemplates().size() > 0;
Map<String, String> paramsMap = Maps.newHashMap();
paramsMap.put("reduce_mappings", "true");
ToXContent.Params params = new ToXContent.DelegatingMapParams(paramsMap, request);
Map<String, String> paramsMap = Maps.newHashMap();
paramsMap.put("reduce_mappings", "true");
ToXContent.Params params = new ToXContent.DelegatingMapParams(paramsMap, request);
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
for (IndexTemplateMetaData indexTemplateMetaData : getIndexTemplatesResponse.getIndexTemplates()) {
IndexTemplateMetaData.Builder.toXContent(indexTemplateMetaData, builder, params);
}
builder.endObject();
RestStatus restStatus = (templateExists || implicitAll) ? OK : NOT_FOUND;
channel.sendResponse(new BytesRestResponse(restStatus, builder));
} catch (Throwable e) {
onFailure(e);
builder.startObject();
for (IndexTemplateMetaData indexTemplateMetaData : getIndexTemplatesResponse.getIndexTemplates()) {
IndexTemplateMetaData.Builder.toXContent(indexTemplateMetaData, builder, params);
}
}
builder.endObject();
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (Exception e1) {
logger.error("Failed to send failure response", e1);
}
RestStatus restStatus = (templateExists || implicitAll) ? OK : NOT_FOUND;
return new BytesRestResponse(restStatus, builder);
}
});
}

View File

@ -18,14 +18,13 @@
*/
package org.elasticsearch.rest.action.admin.indices.template.head;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest;
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
@ -47,28 +46,14 @@ public class RestHeadIndexTemplateAction extends BaseRestHandler {
public void handleRequest(final RestRequest request, final RestChannel channel) {
GetIndexTemplatesRequest getIndexTemplatesRequest = new GetIndexTemplatesRequest(request.param("name"));
getIndexTemplatesRequest.local(request.paramAsBoolean("local", getIndexTemplatesRequest.local()));
client.admin().indices().getTemplates(getIndexTemplatesRequest, new ActionListener<GetIndexTemplatesResponse>() {
client.admin().indices().getTemplates(getIndexTemplatesRequest, new RestResponseListener<GetIndexTemplatesResponse>(channel) {
@Override
public void onResponse(GetIndexTemplatesResponse getIndexTemplatesResponse) {
try {
boolean templateExists = getIndexTemplatesResponse.getIndexTemplates().size() > 0;
if (templateExists) {
channel.sendResponse(new BytesRestResponse(OK));
} else {
channel.sendResponse(new BytesRestResponse(NOT_FOUND));
}
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(ExceptionsHelper.status(e)));
} catch (Exception e1) {
logger.error("Failed to send failure response", e1);
public RestResponse buildResponse(GetIndexTemplatesResponse getIndexTemplatesResponse) {
boolean templateExists = getIndexTemplatesResponse.getIndexTemplates().size() > 0;
if (templateExists) {
return new BytesRestResponse(OK);
} else {
return new BytesRestResponse(NOT_FOUND);
}
}
});

View File

@ -24,6 +24,7 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import java.io.IOException;
@ -55,20 +56,9 @@ public class RestPutIndexTemplateAction extends BaseRestHandler {
putRequest.template(request.param("template", putRequest.template()));
putRequest.order(request.paramAsInt("order", putRequest.order()));
putRequest.masterNodeTimeout(request.paramAsTime("master_timeout", putRequest.masterNodeTimeout()));
try {
putRequest.create(request.paramAsBoolean("create", false));
putRequest.cause(request.param("cause", ""));
putRequest.source(request.content());
} catch (Exception e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.warn("Failed to send response", e1);
}
return;
}
client.admin().indices().putTemplate(putRequest, new AcknowledgedRestResponseActionListener<PutIndexTemplateResponse>(request, channel, logger));
putRequest.create(request.paramAsBoolean("create", false));
putRequest.cause(request.param("cause", ""));
putRequest.source(request.content());
client.admin().indices().putTemplate(putRequest, new AcknowledgedRestListener<PutIndexTemplateResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.indices.validate.query;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.validate.query.QueryExplanation;
import org.elasticsearch.action.admin.indices.validate.query.ValidateQueryRequest;
import org.elasticsearch.action.admin.indices.validate.query.ValidateQueryResponse;
@ -33,13 +32,10 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestActions.buildBroadcastShardsHeader;
@ -64,84 +60,60 @@ public class RestValidateQueryAction extends BaseRestHandler {
ValidateQueryRequest validateQueryRequest = new ValidateQueryRequest(Strings.splitStringByCommaToArray(request.param("index")));
validateQueryRequest.listenerThreaded(false);
validateQueryRequest.indicesOptions(IndicesOptions.fromRequest(request, validateQueryRequest.indicesOptions()));
try {
BroadcastOperationThreading operationThreading = BroadcastOperationThreading.fromString(request.param("operation_threading"), BroadcastOperationThreading.SINGLE_THREAD);
if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
// since we don't spawn, don't allow no_threads, but change it to a single thread
operationThreading = BroadcastOperationThreading.SINGLE_THREAD;
}
validateQueryRequest.operationThreading(operationThreading);
if (request.hasContent()) {
validateQueryRequest.source(request.content(), request.contentUnsafe());
BroadcastOperationThreading operationThreading = BroadcastOperationThreading.fromString(request.param("operation_threading"), BroadcastOperationThreading.SINGLE_THREAD);
if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
// since we don't spawn, don't allow no_threads, but change it to a single thread
operationThreading = BroadcastOperationThreading.SINGLE_THREAD;
}
validateQueryRequest.operationThreading(operationThreading);
if (request.hasContent()) {
validateQueryRequest.source(request.content(), request.contentUnsafe());
} else {
String source = request.param("source");
if (source != null) {
validateQueryRequest.source(source);
} else {
String source = request.param("source");
if (source != null) {
validateQueryRequest.source(source);
} else {
QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
if (querySourceBuilder != null) {
validateQueryRequest.source(querySourceBuilder);
}
QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
if (querySourceBuilder != null) {
validateQueryRequest.source(querySourceBuilder);
}
}
validateQueryRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
if (request.paramAsBoolean("explain", false)) {
validateQueryRequest.explain(true);
} else {
validateQueryRequest.explain(false);
}
} catch (Exception e) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
}
validateQueryRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
if (request.paramAsBoolean("explain", false)) {
validateQueryRequest.explain(true);
} else {
validateQueryRequest.explain(false);
}
client.admin().indices().validateQuery(validateQueryRequest, new ActionListener<ValidateQueryResponse>() {
client.admin().indices().validateQuery(validateQueryRequest, new RestBuilderListener<ValidateQueryResponse>(channel) {
@Override
public void onResponse(ValidateQueryResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
builder.field("valid", response.isValid());
public RestResponse buildResponse(ValidateQueryResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.field("valid", response.isValid());
buildBroadcastShardsHeader(builder, response);
buildBroadcastShardsHeader(builder, response);
if (response.getQueryExplanation() != null && !response.getQueryExplanation().isEmpty()) {
builder.startArray("explanations");
for (QueryExplanation explanation : response.getQueryExplanation()) {
builder.startObject();
if (explanation.getIndex() != null) {
builder.field("index", explanation.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
}
builder.field("valid", explanation.isValid());
if (explanation.getError() != null) {
builder.field("error", explanation.getError());
}
if (explanation.getExplanation() != null) {
builder.field("explanation", explanation.getExplanation());
}
builder.endObject();
if (response.getQueryExplanation() != null && !response.getQueryExplanation().isEmpty()) {
builder.startArray("explanations");
for (QueryExplanation explanation : response.getQueryExplanation()) {
builder.startObject();
if (explanation.getIndex() != null) {
builder.field("index", explanation.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
}
builder.endArray();
builder.field("valid", explanation.isValid());
if (explanation.getError() != null) {
builder.field("error", explanation.getError());
}
if (explanation.getExplanation() != null) {
builder.field("explanation", explanation.getExplanation());
}
builder.endObject();
}
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
builder.endArray();
}
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -19,12 +19,17 @@
package org.elasticsearch.rest.action.admin.indices.warmer.delete;
import org.elasticsearch.action.admin.indices.warmer.delete.DeleteWarmerRequest;
import org.elasticsearch.action.admin.indices.warmer.delete.DeleteWarmerResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
@ -49,6 +54,6 @@ public class RestDeleteWarmerAction extends BaseRestHandler {
deleteWarmerRequest.timeout(request.paramAsTime("timeout", deleteWarmerRequest.timeout()));
deleteWarmerRequest.masterNodeTimeout(request.paramAsTime("master_timeout", deleteWarmerRequest.masterNodeTimeout()));
deleteWarmerRequest.indicesOptions(IndicesOptions.fromRequest(request, deleteWarmerRequest.indicesOptions()));
client.admin().indices().deleteWarmer(deleteWarmerRequest, new AcknowledgedRestResponseActionListener(request, channel, logger));
client.admin().indices().deleteWarmer(deleteWarmerRequest, new AcknowledgedRestListener<DeleteWarmerResponse>(channel));
}
}

View File

@ -20,7 +20,6 @@ package org.elasticsearch.rest.action.admin.indices.warmer.get;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import com.google.common.collect.ImmutableList;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.warmer.get.GetWarmersRequest;
import org.elasticsearch.action.admin.indices.warmer.get.GetWarmersResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -30,11 +29,9 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import org.elasticsearch.search.warmer.IndexWarmersMetaData;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
@ -64,42 +61,27 @@ public class RestGetWarmerAction extends BaseRestHandler {
getWarmersRequest.indices(indices).types(types).warmers(names);
getWarmersRequest.local(request.paramAsBoolean("local", getWarmersRequest.local()));
getWarmersRequest.indicesOptions(IndicesOptions.fromRequest(request, getWarmersRequest.indicesOptions()));
client.admin().indices().getWarmers(getWarmersRequest, new ActionListener<GetWarmersResponse>() {
client.admin().indices().getWarmers(getWarmersRequest, new RestBuilderListener<GetWarmersResponse>(channel) {
@Override
public void onResponse(GetWarmersResponse response) {
try {
if (indices.length > 0 && response.warmers().isEmpty()) {
channel.sendResponse(new BytesRestResponse(OK, RestXContentBuilder.emptyBuilder(request)));
return;
}
public RestResponse buildResponse(GetWarmersResponse response, XContentBuilder builder) throws Exception {
if (indices.length > 0 && response.warmers().isEmpty()) {
return new BytesRestResponse(OK, builder.startObject().endObject());
}
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
for (ObjectObjectCursor<String, ImmutableList<IndexWarmersMetaData.Entry>> entry : response.warmers()) {
builder.startObject(entry.key, XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(IndexWarmersMetaData.TYPE, XContentBuilder.FieldCaseConversion.NONE);
for (IndexWarmersMetaData.Entry warmerEntry : entry.value) {
IndexWarmersMetaData.FACTORY.toXContent(warmerEntry, builder, request);
}
builder.endObject();
builder.endObject();
builder.startObject();
for (ObjectObjectCursor<String, ImmutableList<IndexWarmersMetaData.Entry>> entry : response.warmers()) {
builder.startObject(entry.key, XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(IndexWarmersMetaData.TYPE, XContentBuilder.FieldCaseConversion.NONE);
for (IndexWarmersMetaData.Entry warmerEntry : entry.value) {
IndexWarmersMetaData.FACTORY.toXContent(warmerEntry, builder, request);
}
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
builder.endObject();
}
}
builder.endObject();
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -19,13 +19,18 @@
package org.elasticsearch.rest.action.admin.indices.warmer.put;
import org.elasticsearch.action.admin.indices.warmer.put.PutWarmerRequest;
import org.elasticsearch.action.admin.indices.warmer.put.PutWarmerResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.support.AcknowledgedRestListener;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestRequest.Method.PUT;
@ -40,15 +45,15 @@ public class RestPutWarmerAction extends BaseRestHandler {
controller.registerHandler(PUT, "/_warmer/{name}", this);
controller.registerHandler(PUT, "/{index}/_warmer/{name}", this);
controller.registerHandler(PUT, "/{index}/{type}/_warmer/{name}", this);
controller.registerHandler(PUT, "/_warmers/{name}", this);
controller.registerHandler(PUT, "/{index}/_warmers/{name}", this);
controller.registerHandler(PUT, "/{index}/{type}/_warmers/{name}", this);
controller.registerHandler(POST, "/_warmer/{name}", this);
controller.registerHandler(POST, "/{index}/_warmer/{name}", this);
controller.registerHandler(POST, "/{index}/{type}/_warmer/{name}", this);
controller.registerHandler(POST, "/_warmers/{name}", this);
controller.registerHandler(POST, "/{index}/_warmers/{name}", this);
controller.registerHandler(POST, "/{index}/{type}/_warmers/{name}", this);
@ -65,6 +70,6 @@ public class RestPutWarmerAction extends BaseRestHandler {
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));
client.admin().indices().putWarmer(putWarmerRequest, new AcknowledgedRestListener<PutWarmerResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.bulk;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.WriteConsistencyLevel;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
@ -36,14 +35,11 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.rest.*;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestRequest.Method.PUT;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
/**
* <pre>
@ -73,7 +69,7 @@ public class RestBulkAction extends BaseRestHandler {
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
public void handleRequest(final RestRequest request, final RestChannel channel) throws Exception {
BulkRequest bulkRequest = Requests.bulkRequest();
bulkRequest.listenerThreaded(false);
String defaultIndex = request.param("index");
@ -90,84 +86,60 @@ public class RestBulkAction extends BaseRestHandler {
}
bulkRequest.timeout(request.paramAsTime("timeout", BulkShardRequest.DEFAULT_TIMEOUT));
bulkRequest.refresh(request.paramAsBoolean("refresh", bulkRequest.refresh()));
try {
bulkRequest.add(request.content(), request.contentUnsafe(), defaultIndex, defaultType, defaultRouting, null, allowExplicitIndex);
} catch (Exception e) {
try {
XContentBuilder builder = restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
}
bulkRequest.add(request.content(), request.contentUnsafe(), defaultIndex, defaultType, defaultRouting, null, allowExplicitIndex);
client.bulk(bulkRequest, new ActionListener<BulkResponse>() {
client.bulk(bulkRequest, new RestBuilderListener<BulkResponse>(channel) {
@Override
public void onResponse(BulkResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
public RestResponse buildResponse(BulkResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.field(Fields.TOOK, response.getTookInMillis());
builder.field(Fields.ERRORS, response.hasFailures());
builder.startArray(Fields.ITEMS);
for (BulkItemResponse itemResponse : response) {
builder.startObject();
builder.field(Fields.TOOK, response.getTookInMillis());
builder.field(Fields.ERRORS, response.hasFailures());
builder.startArray(Fields.ITEMS);
for (BulkItemResponse itemResponse : response) {
builder.startObject();
builder.startObject(itemResponse.getOpType());
builder.field(Fields._INDEX, itemResponse.getIndex());
builder.field(Fields._TYPE, itemResponse.getType());
builder.field(Fields._ID, itemResponse.getId());
long version = itemResponse.getVersion();
if (version != -1) {
builder.field(Fields._VERSION, itemResponse.getVersion());
}
if (itemResponse.isFailed()) {
builder.field(Fields.STATUS, itemResponse.getFailure().getStatus().getStatus());
builder.field(Fields.ERROR, itemResponse.getFailure().getMessage());
} else {
if (itemResponse.getResponse() instanceof DeleteResponse) {
DeleteResponse deleteResponse = itemResponse.getResponse();
if (deleteResponse.isFound()) {
builder.field(Fields.STATUS, RestStatus.OK.getStatus());
} else {
builder.field(Fields.STATUS, RestStatus.NOT_FOUND.getStatus());
}
builder.field(Fields.FOUND, deleteResponse.isFound());
} else if (itemResponse.getResponse() instanceof IndexResponse) {
IndexResponse indexResponse = itemResponse.getResponse();
if (indexResponse.isCreated()) {
builder.field(Fields.STATUS, RestStatus.CREATED.getStatus());
} else {
builder.field(Fields.STATUS, RestStatus.OK.getStatus());
}
} else if (itemResponse.getResponse() instanceof UpdateResponse) {
UpdateResponse updateResponse = itemResponse.getResponse();
if (updateResponse.isCreated()) {
builder.field(Fields.STATUS, RestStatus.CREATED.getStatus());
} else {
builder.field(Fields.STATUS, RestStatus.OK.getStatus());
}
builder.startObject(itemResponse.getOpType());
builder.field(Fields._INDEX, itemResponse.getIndex());
builder.field(Fields._TYPE, itemResponse.getType());
builder.field(Fields._ID, itemResponse.getId());
long version = itemResponse.getVersion();
if (version != -1) {
builder.field(Fields._VERSION, itemResponse.getVersion());
}
if (itemResponse.isFailed()) {
builder.field(Fields.STATUS, itemResponse.getFailure().getStatus().getStatus());
builder.field(Fields.ERROR, itemResponse.getFailure().getMessage());
} else {
if (itemResponse.getResponse() instanceof DeleteResponse) {
DeleteResponse deleteResponse = itemResponse.getResponse();
if (deleteResponse.isFound()) {
builder.field(Fields.STATUS, RestStatus.OK.getStatus());
} else {
builder.field(Fields.STATUS, RestStatus.NOT_FOUND.getStatus());
}
builder.field(Fields.FOUND, deleteResponse.isFound());
} else if (itemResponse.getResponse() instanceof IndexResponse) {
IndexResponse indexResponse = itemResponse.getResponse();
if (indexResponse.isCreated()) {
builder.field(Fields.STATUS, RestStatus.CREATED.getStatus());
} else {
builder.field(Fields.STATUS, RestStatus.OK.getStatus());
}
} else if (itemResponse.getResponse() instanceof UpdateResponse) {
UpdateResponse updateResponse = itemResponse.getResponse();
if (updateResponse.isCreated()) {
builder.field(Fields.STATUS, RestStatus.CREATED.getStatus());
} else {
builder.field(Fields.STATUS, RestStatus.OK.getStatus());
}
}
builder.endObject();
builder.endObject();
}
builder.endArray();
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
builder.endObject();
}
}
builder.endArray();
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -20,6 +20,8 @@ package org.elasticsearch.rest.action.cat;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.io.UTF8StreamWriter;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
@ -42,12 +44,13 @@ public abstract class AbstractCatAction extends BaseRestHandler {
abstract Table getTableWithHeader(final RestRequest request);
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
public void handleRequest(final RestRequest request, final RestChannel channel) throws Exception {
boolean helpWanted = request.paramAsBoolean("help", false);
if (helpWanted) {
Table table = getTableWithHeader(request);
int[] width = buildHelpWidths(table, request, false);
StringBuilder out = new StringBuilder();
int[] width = buildHelpWidths(table, request);
BytesStreamOutput bytesOutput = channel.bytesOutput();
UTF8StreamWriter out = new UTF8StreamWriter().setOutput(bytesOutput);
for (Table.Cell cell : table.getHeaders()) {
// need to do left-align always, so create new cells
pad(new Table.Cell(cell.value), width[0], request, out);
@ -57,11 +60,10 @@ public abstract class AbstractCatAction extends BaseRestHandler {
pad(new Table.Cell(cell.attr.containsKey("desc") ? cell.attr.get("desc") : "not available"), width[2], request, out);
out.append("\n");
}
channel.sendResponse(new BytesRestResponse(RestStatus.OK, out.toString()));
out.close();
channel.sendResponse(new BytesRestResponse(RestStatus.OK, BytesRestResponse.TEXT_CONTENT_TYPE, bytesOutput.bytes(), true));
} else {
doRequest(request, channel);
}
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.cat;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.client.Client;
@ -28,13 +27,13 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import java.io.IOException;
import java.util.List;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -59,24 +58,11 @@ public class RestAliasAction extends AbstractCatAction {
new GetAliasesRequest();
getAliasesRequest.local(request.paramAsBoolean("local", getAliasesRequest.local()));
client.admin().indices().getAliases(getAliasesRequest, new ActionListener<GetAliasesResponse>() {
client.admin().indices().getAliases(getAliasesRequest, new RestResponseListener<GetAliasesResponse>(channel) {
@Override
public void onResponse(GetAliasesResponse response) {
try {
Table tab = buildTable(request, response);
channel.sendResponse(RestTable.buildResponse(tab, request, channel));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(GetAliasesResponse response) throws Exception {
Table tab = buildTable(request, response);
return RestTable.buildResponse(tab, channel);
}
});
}

View File

@ -20,7 +20,6 @@
package org.elasticsearch.rest.action.cat;
import com.carrotsearch.hppc.ObjectIntOpenHashMap;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequest;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
@ -34,14 +33,14 @@ import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestActionListener;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -67,42 +66,20 @@ public class RestAllocationAction extends AbstractCatAction {
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() {
client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(final ClusterStateResponse state) {
public void processResponse(final ClusterStateResponse state) {
NodesStatsRequest statsRequest = new NodesStatsRequest(nodes);
statsRequest.clear().fs(true);
client.admin().cluster().nodesStats(statsRequest, new ActionListener<NodesStatsResponse>() {
client.admin().cluster().nodesStats(statsRequest, new RestResponseListener<NodesStatsResponse>(channel) {
@Override
public void onResponse(NodesStatsResponse stats) {
try {
Table tab = buildTable(request, state, stats);
channel.sendResponse(RestTable.buildResponse(tab, request, channel));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(NodesStatsResponse stats) throws Exception {
Table tab = buildTable(request, state, stats);
return RestTable.buildResponse(tab, channel);
}
});
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}

View File

@ -49,14 +49,6 @@ public class RestCatAction extends BaseRestHandler {
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
try {
channel.sendResponse(new BytesRestResponse(RestStatus.OK, HELP));
} catch (Throwable t) {
try {
channel.sendResponse(new BytesRestResponse(request, t));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
channel.sendResponse(new BytesRestResponse(RestStatus.OK, HELP));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.cat;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.count.CountRequest;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.support.QuerySourceBuilder;
@ -29,16 +28,16 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -74,23 +73,10 @@ public class RestCountAction extends AbstractCatAction {
}
}
client.count(countRequest, new ActionListener<CountResponse>() {
client.count(countRequest, new RestResponseListener<CountResponse>(channel) {
@Override
public void onResponse(CountResponse countResponse) {
try {
channel.sendResponse(RestTable.buildResponse(buildTable(request, countResponse), request, channel));
} catch (Throwable t) {
onFailure(t);
}
}
@Override
public void onFailure(Throwable t) {
try {
channel.sendResponse(new BytesRestResponse(request, t));
} catch (IOException e) {
logger.error("Failed to send failure response", e);
}
public RestResponse buildResponse(CountResponse countResponse) throws Exception {
return RestTable.buildResponse(buildTable(request, countResponse), channel);
}
});
}

View File

@ -19,22 +19,21 @@
package org.elasticsearch.rest.action.cat;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
@ -57,23 +56,10 @@ public class RestHealthAction extends AbstractCatAction {
public void doRequest(final RestRequest request, final RestChannel channel) {
ClusterHealthRequest clusterHealthRequest = new ClusterHealthRequest();
client.admin().cluster().health(clusterHealthRequest, new ActionListener<ClusterHealthResponse>() {
client.admin().cluster().health(clusterHealthRequest, new RestResponseListener<ClusterHealthResponse>(channel) {
@Override
public void onResponse(final ClusterHealthResponse health) {
try {
channel.sendResponse(RestTable.buildResponse(buildTable(health, request), request, channel));
} catch (Throwable t) {
onFailure(t);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(final ClusterHealthResponse health) throws Exception {
return RestTable.buildResponse(buildTable(health, request), channel);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.cat;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterIndexHealth;
@ -30,15 +29,18 @@ import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestActionListener;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import java.io.IOException;
import java.util.Locale;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -66,59 +68,28 @@ public class RestIndicesAction extends AbstractCatAction {
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() {
client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(final ClusterStateResponse clusterStateResponse) {
public void processResponse(final ClusterStateResponse clusterStateResponse) {
final String[] concreteIndices = clusterStateResponse.getState().metaData().concreteIndicesIgnoreMissing(indices);
ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest(concreteIndices);
clusterHealthRequest.local(request.paramAsBoolean("local", clusterHealthRequest.local()));
client.admin().cluster().health(clusterHealthRequest, new ActionListener<ClusterHealthResponse>() {
client.admin().cluster().health(clusterHealthRequest, new RestActionListener<ClusterHealthResponse>(channel) {
@Override
public void onResponse(final ClusterHealthResponse clusterHealthResponse) {
public void processResponse(final ClusterHealthResponse clusterHealthResponse) {
IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest();
indicesStatsRequest.all();
client.admin().indices().stats(indicesStatsRequest, new ActionListener<IndicesStatsResponse>() {
client.admin().indices().stats(indicesStatsRequest, new RestResponseListener<IndicesStatsResponse>(channel) {
@Override
public void onResponse(IndicesStatsResponse indicesStatsResponse) {
try {
Table tab = buildTable(request, concreteIndices, clusterHealthResponse, indicesStatsResponse);
channel.sendResponse(RestTable.buildResponse(tab, request, channel));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(IndicesStatsResponse indicesStatsResponse) throws Exception {
Table tab = buildTable(request, concreteIndices, clusterHealthResponse, indicesStatsResponse);
return RestTable.buildResponse(tab, channel);
}
});
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.cat;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.client.Client;
@ -28,14 +27,13 @@ import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.GET;
public class RestMasterAction extends AbstractCatAction {
@ -58,23 +56,10 @@ public class RestMasterAction extends AbstractCatAction {
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() {
client.admin().cluster().state(clusterStateRequest, new RestResponseListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(final ClusterStateResponse clusterStateResponse) {
try {
channel.sendResponse(RestTable.buildResponse(buildTable(request, clusterStateResponse), request, channel));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(final ClusterStateResponse clusterStateResponse) throws Exception {
return RestTable.buildResponse(buildTable(request, clusterStateResponse), channel);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.cat;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
@ -36,13 +35,14 @@ import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestActionListener;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import java.io.IOException;
import java.util.Locale;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -67,56 +67,25 @@ public class RestNodesAction extends AbstractCatAction {
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() {
client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(final ClusterStateResponse clusterStateResponse) {
public void processResponse(final ClusterStateResponse clusterStateResponse) {
NodesInfoRequest nodesInfoRequest = new NodesInfoRequest();
nodesInfoRequest.clear().jvm(true).os(true).process(true);
client.admin().cluster().nodesInfo(nodesInfoRequest, new ActionListener<NodesInfoResponse>() {
client.admin().cluster().nodesInfo(nodesInfoRequest, new RestActionListener<NodesInfoResponse>(channel) {
@Override
public void onResponse(final NodesInfoResponse nodesInfoResponse) {
public void processResponse(final NodesInfoResponse nodesInfoResponse) {
NodesStatsRequest nodesStatsRequest = new NodesStatsRequest();
nodesStatsRequest.clear().jvm(true).os(true).fs(true).indices(true);
client.admin().cluster().nodesStats(nodesStatsRequest, new ActionListener<NodesStatsResponse>() {
client.admin().cluster().nodesStats(nodesStatsRequest, new RestResponseListener<NodesStatsResponse>(channel) {
@Override
public void onResponse(NodesStatsResponse nodesStatsResponse) {
try {
channel.sendResponse(RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse, nodesStatsResponse), request, channel));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(NodesStatsResponse nodesStatsResponse) throws Exception {
return RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse, nodesStatsResponse), channel);
}
});
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.cat;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksRequest;
import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksResponse;
import org.elasticsearch.client.Client;
@ -27,11 +26,13 @@ import org.elasticsearch.cluster.service.PendingClusterTask;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.GET;
public class RestPendingClusterTasksAction extends AbstractCatAction {
@ -51,24 +52,11 @@ public class RestPendingClusterTasksAction extends AbstractCatAction {
PendingClusterTasksRequest pendingClusterTasksRequest = new PendingClusterTasksRequest();
pendingClusterTasksRequest.masterNodeTimeout(request.paramAsTime("master_timeout", pendingClusterTasksRequest.masterNodeTimeout()));
pendingClusterTasksRequest.local(request.paramAsBoolean("local", pendingClusterTasksRequest.local()));
client.admin().cluster().pendingClusterTasks(pendingClusterTasksRequest, new ActionListener<PendingClusterTasksResponse>() {
client.admin().cluster().pendingClusterTasks(pendingClusterTasksRequest, new RestResponseListener<PendingClusterTasksResponse>(channel) {
@Override
public void onResponse(PendingClusterTasksResponse pendingClusterTasks) {
try {
Table tab = buildTable(request, pendingClusterTasks);
channel.sendResponse(RestTable.buildResponse(tab, request, channel));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(PendingClusterTasksResponse pendingClusterTasks) throws Exception {
Table tab = buildTable(request, pendingClusterTasks);
return RestTable.buildResponse(tab, channel);
}
});
}

View File

@ -31,10 +31,12 @@ import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.AbstractRestResponseActionListener;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestActionListener;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -59,19 +61,15 @@ public class RestPluginsAction extends AbstractCatAction {
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
client.admin().cluster().state(clusterStateRequest, new AbstractRestResponseActionListener<ClusterStateResponse>(request, channel, logger) {
client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(final ClusterStateResponse clusterStateResponse) {
public void processResponse(final ClusterStateResponse clusterStateResponse) throws Exception {
NodesInfoRequest nodesInfoRequest = new NodesInfoRequest();
nodesInfoRequest.clear().plugins(true);
client.admin().cluster().nodesInfo(nodesInfoRequest, new AbstractRestResponseActionListener<NodesInfoResponse>(request, channel, logger) {
client.admin().cluster().nodesInfo(nodesInfoRequest, new RestResponseListener<NodesInfoResponse>(channel) {
@Override
public void onResponse(final NodesInfoResponse nodesInfoResponse) {
try {
channel.sendResponse(RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse), request, channel));
} catch (Throwable e) {
onFailure(e);
}
public RestResponse buildResponse(final NodesInfoResponse nodesInfoResponse) throws Exception {
return RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse), channel);
}
});
}

View File

@ -19,8 +19,7 @@
package org.elasticsearch.rest.action.cat;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.indices.recovery.RecoveryState;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.action.admin.indices.recovery.RecoveryRequest;
import org.elasticsearch.action.admin.indices.recovery.RecoveryResponse;
import org.elasticsearch.action.admin.indices.recovery.ShardRecoveryResponse;
@ -30,16 +29,17 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.indices.recovery.RecoveryState;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import org.apache.lucene.util.CollectionUtil;
import java.io.IOException;
import java.util.*;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -71,28 +71,10 @@ public class RestRecoveryAction extends AbstractCatAction {
recoveryRequest.listenerThreaded(false);
recoveryRequest.indicesOptions(IndicesOptions.fromRequest(request, recoveryRequest.indicesOptions()));
client.admin().indices().recoveries(recoveryRequest, new ActionListener<RecoveryResponse>() {
client.admin().indices().recoveries(recoveryRequest, new RestResponseListener<RecoveryResponse>(channel) {
@Override
public void onResponse(final RecoveryResponse response) {
try {
channel.sendResponse(RestTable.buildResponse(buildRecoveryTable(request, response), request, channel));
} catch (Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e2) {
logger.error("Unable to send recovery status response", e2);
}
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(final RecoveryResponse response) throws Exception {
return RestTable.buildResponse(buildRecoveryTable(request, response), channel);
}
});
}
@ -122,8 +104,8 @@ public class RestRecoveryAction extends AbstractCatAction {
* buildRecoveryTable will build a table of recovery information suitable
* for displaying at the command line.
*
* @param request A Rest request
* @param response A recovery status response
* @param request A Rest request
* @param response A recovery status response
* @return A table containing index, shardId, node, target size, recovered size and percentage for each recovering replica
*/
public Table buildRecoveryTable(RestRequest request, RecoveryResponse response) {

View File

@ -31,6 +31,8 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.engine.Segment;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActionListener;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import java.io.IOException;
@ -57,43 +59,19 @@ public class RestSegmentsAction extends AbstractCatAction {
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
clusterStateRequest.clear().nodes(true).routingTable(true).indices(indices);
client.admin().cluster().state(clusterStateRequest, new AbstractRestResponseActionListener<ClusterStateResponse>(request, channel, logger) {
client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(final ClusterStateResponse clusterStateResponse) {
public void processResponse(final ClusterStateResponse clusterStateResponse) {
final IndicesSegmentsRequest indicesSegmentsRequest = new IndicesSegmentsRequest();
indicesSegmentsRequest.indices(indices);
client.admin().indices().segments(indicesSegmentsRequest, new ActionListener<IndicesSegmentResponse>() {
client.admin().indices().segments(indicesSegmentsRequest, new RestResponseListener<IndicesSegmentResponse>(channel) {
@Override
public void onResponse(final IndicesSegmentResponse indicesSegmentResponse) {
public RestResponse buildResponse(final IndicesSegmentResponse indicesSegmentResponse) throws Exception {
final Map<String, IndexSegments> indicesSegments = indicesSegmentResponse.getIndices();
try {
Table tab = buildTable(request, clusterStateResponse, indicesSegments);
channel.sendResponse(RestTable.buildResponse(tab, request, channel));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
Table tab = buildTable(request, clusterStateResponse, indicesSegments);
return RestTable.buildResponse(tab, channel);
}
});
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}

View File

@ -30,7 +30,12 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestActionListener;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import static org.elasticsearch.rest.RestRequest.Method.GET;
@ -57,19 +62,15 @@ public class RestShardsAction extends AbstractCatAction {
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
clusterStateRequest.clear().nodes(true).routingTable(true).indices(indices);
client.admin().cluster().state(clusterStateRequest, new AbstractRestResponseActionListener<ClusterStateResponse>(request, channel, logger) {
client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(final ClusterStateResponse clusterStateResponse) {
public void processResponse(final ClusterStateResponse clusterStateResponse) {
IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest();
indicesStatsRequest.all();
client.admin().indices().stats(indicesStatsRequest, new AbstractRestResponseActionListener<IndicesStatsResponse>(request, channel, logger) {
client.admin().indices().stats(indicesStatsRequest, new RestResponseListener<IndicesStatsResponse>(channel) {
@Override
public void onResponse(IndicesStatsResponse indicesStatsResponse) {
try {
channel.sendResponse(RestTable.buildResponse(buildTable(request, clusterStateResponse, indicesStatsResponse), request, channel));
} catch (Throwable e) {
onFailure(e);
}
public RestResponse buildResponse(IndicesStatsResponse indicesStatsResponse) throws Exception {
return RestTable.buildResponse(buildTable(request, clusterStateResponse, indicesStatsResponse), channel);
}
});
}

View File

@ -36,10 +36,12 @@ import org.elasticsearch.common.Table;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.rest.AbstractRestResponseActionListener;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestActionListener;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.rest.action.support.RestTable;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.ThreadPoolStats;
@ -50,7 +52,7 @@ import static org.elasticsearch.rest.RestRequest.Method.GET;
public class RestThreadPoolAction extends AbstractCatAction {
private final static String[] SUPPORTED_NAMES = new String[] {
private final static String[] SUPPORTED_NAMES = new String[]{
ThreadPool.Names.BULK,
ThreadPool.Names.FLUSH,
ThreadPool.Names.GENERIC,
@ -67,7 +69,7 @@ public class RestThreadPoolAction extends AbstractCatAction {
ThreadPool.Names.WARMER
};
private final static String[] SUPPORTED_ALIASES = new String[] {
private final static String[] SUPPORTED_ALIASES = new String[]{
"b",
"f",
"ge",
@ -84,7 +86,7 @@ public class RestThreadPoolAction extends AbstractCatAction {
"w"
};
private final static String[] DEFAULT_THREAD_POOLS = new String[] {
private final static String[] DEFAULT_THREAD_POOLS = new String[]{
ThreadPool.Names.BULK,
ThreadPool.Names.INDEX,
ThreadPool.Names.SEARCH,
@ -123,24 +125,20 @@ public class RestThreadPoolAction extends AbstractCatAction {
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
final String[] pools = fetchSortedPools(request, DEFAULT_THREAD_POOLS);
client.admin().cluster().state(clusterStateRequest, new AbstractRestResponseActionListener<ClusterStateResponse>(request, channel, logger) {
client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(final ClusterStateResponse clusterStateResponse) {
public void processResponse(final ClusterStateResponse clusterStateResponse) {
NodesInfoRequest nodesInfoRequest = new NodesInfoRequest();
nodesInfoRequest.clear().process(true);
client.admin().cluster().nodesInfo(nodesInfoRequest, new AbstractRestResponseActionListener<NodesInfoResponse>(request, channel, logger) {
client.admin().cluster().nodesInfo(nodesInfoRequest, new RestActionListener<NodesInfoResponse>(channel) {
@Override
public void onResponse(final NodesInfoResponse nodesInfoResponse) {
public void processResponse(final NodesInfoResponse nodesInfoResponse) {
NodesStatsRequest nodesStatsRequest = new NodesStatsRequest();
nodesStatsRequest.clear().threadPool(true);
client.admin().cluster().nodesStats(nodesStatsRequest, new AbstractRestResponseActionListener<NodesStatsResponse>(request, channel, logger) {
client.admin().cluster().nodesStats(nodesStatsRequest, new RestResponseListener<NodesStatsResponse>(channel) {
@Override
public void onResponse(NodesStatsResponse nodesStatsResponse) {
try {
channel.sendResponse(RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse, nodesStatsResponse, pools), request, channel));
} catch (Throwable e) {
onFailure(e);
}
public RestResponse buildResponse(NodesStatsResponse nodesStatsResponse) throws Exception {
return RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse, nodesStatsResponse, pools), channel);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.count;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.count.CountRequest;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.support.IndicesOptions;
@ -32,14 +31,11 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.action.count.CountRequest.DEFAULT_MIN_SCORE;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
import static org.elasticsearch.rest.action.support.RestActions.buildBroadcastShardsHeader;
/**
@ -63,64 +59,40 @@ public class RestCountAction extends BaseRestHandler {
CountRequest countRequest = new CountRequest(Strings.splitStringByCommaToArray(request.param("index")));
countRequest.indicesOptions(IndicesOptions.fromRequest(request, countRequest.indicesOptions()));
countRequest.listenerThreaded(false);
try {
BroadcastOperationThreading operationThreading = BroadcastOperationThreading.fromString(request.param("operation_threading"), BroadcastOperationThreading.THREAD_PER_SHARD);
if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
// since we don't spawn, don't allow no_threads, but change it to a single thread
operationThreading = BroadcastOperationThreading.SINGLE_THREAD;
}
countRequest.operationThreading(operationThreading);
if (request.hasContent()) {
countRequest.source(request.content(), request.contentUnsafe());
} else {
String source = request.param("source");
if (source != null) {
countRequest.source(source);
} else {
QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
if (querySourceBuilder != null) {
countRequest.source(querySourceBuilder);
}
}
}
countRequest.routing(request.param("routing"));
countRequest.minScore(request.paramAsFloat("min_score", DEFAULT_MIN_SCORE));
countRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
countRequest.preference(request.param("preference"));
} catch (Exception e) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
BroadcastOperationThreading operationThreading = BroadcastOperationThreading.fromString(request.param("operation_threading"), BroadcastOperationThreading.THREAD_PER_SHARD);
if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
// since we don't spawn, don't allow no_threads, but change it to a single thread
operationThreading = BroadcastOperationThreading.SINGLE_THREAD;
}
client.count(countRequest, new ActionListener<CountResponse>() {
@Override
public void onResponse(CountResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
builder.field("count", response.getCount());
buildBroadcastShardsHeader(builder, response);
builder.endObject();
channel.sendResponse(new BytesRestResponse(response.status(), builder));
} catch (Throwable e) {
onFailure(e);
countRequest.operationThreading(operationThreading);
if (request.hasContent()) {
countRequest.source(request.content(), request.contentUnsafe());
} else {
String source = request.param("source");
if (source != null) {
countRequest.source(source);
} else {
QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
if (querySourceBuilder != null) {
countRequest.source(querySourceBuilder);
}
}
}
countRequest.routing(request.param("routing"));
countRequest.minScore(request.paramAsFloat("min_score", DEFAULT_MIN_SCORE));
countRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
countRequest.preference(request.param("preference"));
client.count(countRequest, new RestBuilderListener<CountResponse>(channel) {
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(CountResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.field("count", response.getCount());
buildBroadcastShardsHeader(builder, response);
builder.endObject();
return new BytesRestResponse(response.status(), builder);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.delete;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.WriteConsistencyLevel;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
@ -32,9 +31,7 @@ import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
@ -74,35 +71,21 @@ public class RestDeleteAction extends BaseRestHandler {
deleteRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
}
client.delete(deleteRequest, new ActionListener<DeleteResponse>() {
client.delete(deleteRequest, new RestBuilderListener<DeleteResponse>(channel) {
@Override
public void onResponse(DeleteResponse result) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject()
.field(Fields.FOUND, result.isFound())
.field(Fields._INDEX, result.getIndex())
.field(Fields._TYPE, result.getType())
.field(Fields._ID, result.getId())
.field(Fields._VERSION, result.getVersion())
.endObject();
RestStatus status = OK;
if (!result.isFound()) {
status = NOT_FOUND;
}
channel.sendResponse(new BytesRestResponse(status, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
public RestResponse buildResponse(DeleteResponse result, XContentBuilder builder) throws Exception {
builder.startObject()
.field(Fields.FOUND, result.isFound())
.field(Fields._INDEX, result.getIndex())
.field(Fields._TYPE, result.getType())
.field(Fields._ID, result.getId())
.field(Fields._VERSION, result.getVersion())
.endObject();
RestStatus status = OK;
if (!result.isFound()) {
status = NOT_FOUND;
}
return new BytesRestResponse(status, builder);
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.deletebyquery;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.WriteConsistencyLevel;
import org.elasticsearch.action.deletebyquery.DeleteByQueryRequest;
@ -37,12 +36,9 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
import static org.elasticsearch.rest.RestStatus.PRECONDITION_FAILED;
/**
*
@ -60,88 +56,64 @@ public class RestDeleteByQueryAction extends BaseRestHandler {
public void handleRequest(final RestRequest request, final RestChannel channel) {
DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(Strings.splitStringByCommaToArray(request.param("index")));
deleteByQueryRequest.listenerThreaded(false);
try {
if (request.hasContent()) {
deleteByQueryRequest.source(request.content(), request.contentUnsafe());
if (request.hasContent()) {
deleteByQueryRequest.source(request.content(), request.contentUnsafe());
} else {
String source = request.param("source");
if (source != null) {
deleteByQueryRequest.source(source);
} else {
String source = request.param("source");
if (source != null) {
deleteByQueryRequest.source(source);
} else {
QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
if (querySourceBuilder != null) {
deleteByQueryRequest.source(querySourceBuilder);
}
QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
if (querySourceBuilder != null) {
deleteByQueryRequest.source(querySourceBuilder);
}
}
deleteByQueryRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
deleteByQueryRequest.timeout(request.paramAsTime("timeout", ShardDeleteByQueryRequest.DEFAULT_TIMEOUT));
deleteByQueryRequest.routing(request.param("routing"));
String replicationType = request.param("replication");
if (replicationType != null) {
deleteByQueryRequest.replicationType(ReplicationType.fromString(replicationType));
}
String consistencyLevel = request.param("consistency");
if (consistencyLevel != null) {
deleteByQueryRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
}
deleteByQueryRequest.indicesOptions(IndicesOptions.fromRequest(request, deleteByQueryRequest.indicesOptions()));
} catch (Exception e) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(PRECONDITION_FAILED, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
}
client.deleteByQuery(deleteByQueryRequest, new ActionListener<DeleteByQueryResponse>() {
deleteByQueryRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
deleteByQueryRequest.timeout(request.paramAsTime("timeout", ShardDeleteByQueryRequest.DEFAULT_TIMEOUT));
deleteByQueryRequest.routing(request.param("routing"));
String replicationType = request.param("replication");
if (replicationType != null) {
deleteByQueryRequest.replicationType(ReplicationType.fromString(replicationType));
}
String consistencyLevel = request.param("consistency");
if (consistencyLevel != null) {
deleteByQueryRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
}
deleteByQueryRequest.indicesOptions(IndicesOptions.fromRequest(request, deleteByQueryRequest.indicesOptions()));
client.deleteByQuery(deleteByQueryRequest, new RestBuilderListener<DeleteByQueryResponse>(channel) {
@Override
public void onResponse(DeleteByQueryResponse result) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
RestStatus restStatus = result.status();
builder.startObject();
builder.startObject(Fields._INDICES);
for (IndexDeleteByQueryResponse indexDeleteByQueryResponse : result.getIndices().values()) {
builder.startObject(indexDeleteByQueryResponse.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
public RestResponse buildResponse(DeleteByQueryResponse result, XContentBuilder builder) throws Exception {
RestStatus restStatus = result.status();
builder.startObject();
builder.startObject(Fields._INDICES);
for (IndexDeleteByQueryResponse indexDeleteByQueryResponse : result.getIndices().values()) {
builder.startObject(indexDeleteByQueryResponse.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
builder.startObject(Fields._SHARDS);
builder.field(Fields.TOTAL, indexDeleteByQueryResponse.getTotalShards());
builder.field(Fields.SUCCESSFUL, indexDeleteByQueryResponse.getSuccessfulShards());
builder.field(Fields.FAILED, indexDeleteByQueryResponse.getFailedShards());
ShardOperationFailedException[] failures = indexDeleteByQueryResponse.getFailures();
if (failures != null && failures.length > 0) {
builder.startArray(Fields.FAILURES);
for (ShardOperationFailedException shardFailure : failures) {
builder.startObject();
builder.field(Fields.INDEX, shardFailure.index());
builder.field(Fields.SHARD, shardFailure.shardId());
builder.field(Fields.REASON, shardFailure.reason());
builder.endObject();
}
builder.endArray();
builder.startObject(Fields._SHARDS);
builder.field(Fields.TOTAL, indexDeleteByQueryResponse.getTotalShards());
builder.field(Fields.SUCCESSFUL, indexDeleteByQueryResponse.getSuccessfulShards());
builder.field(Fields.FAILED, indexDeleteByQueryResponse.getFailedShards());
ShardOperationFailedException[] failures = indexDeleteByQueryResponse.getFailures();
if (failures != null && failures.length > 0) {
builder.startArray(Fields.FAILURES);
for (ShardOperationFailedException shardFailure : failures) {
builder.startObject();
builder.field(Fields.INDEX, shardFailure.index());
builder.field(Fields.SHARD, shardFailure.shardId());
builder.field(Fields.REASON, shardFailure.reason());
builder.endObject();
}
builder.endObject();
builder.endObject();
builder.endArray();
}
builder.endObject();
builder.endObject();
channel.sendResponse(new BytesRestResponse(restStatus, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
builder.endObject();
}
builder.endObject();
builder.endObject();
return new BytesRestResponse(restStatus, builder);
}
});
}

View File

@ -21,7 +21,6 @@ package org.elasticsearch.rest.action.explain;
import org.apache.lucene.search.Explanation;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.explain.ExplainRequest;
import org.elasticsearch.action.explain.ExplainResponse;
import org.elasticsearch.action.support.QuerySourceBuilder;
@ -36,6 +35,7 @@ import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import org.elasticsearch.search.fetch.source.FetchSourceContext;
import java.io.IOException;
@ -44,7 +44,6 @@ import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
/**
* Rest action for computing a score explanation for specific documents.
@ -103,34 +102,28 @@ public class RestExplainAction extends BaseRestHandler {
explainRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));
client.explain(explainRequest, new ActionListener<ExplainResponse>() {
client.explain(explainRequest, new RestBuilderListener<ExplainResponse>(channel) {
@Override
public void onResponse(ExplainResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
builder.startObject();
builder.field(Fields._INDEX, explainRequest.index())
.field(Fields._TYPE, explainRequest.type())
.field(Fields._ID, explainRequest.id())
.field(Fields.MATCHED, response.isMatch());
public RestResponse buildResponse(ExplainResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.field(Fields._INDEX, explainRequest.index())
.field(Fields._TYPE, explainRequest.type())
.field(Fields._ID, explainRequest.id())
.field(Fields.MATCHED, response.isMatch());
if (response.hasExplanation()) {
builder.startObject(Fields.EXPLANATION);
buildExplanation(builder, response.getExplanation());
builder.endObject();
}
GetResult getResult = response.getGetResult();
if (getResult != null) {
builder.startObject(Fields.GET);
response.getGetResult().toXContentEmbedded(builder, request);
builder.endObject();
}
if (response.hasExplanation()) {
builder.startObject(Fields.EXPLANATION);
buildExplanation(builder, response.getExplanation());
builder.endObject();
channel.sendResponse(new BytesRestResponse(response.isExists() ? OK : NOT_FOUND, builder));
} catch (Throwable e) {
onFailure(e);
}
GetResult getResult = response.getGetResult();
if (getResult != null) {
builder.startObject(Fields.GET);
response.getGetResult().toXContentEmbedded(builder, request);
builder.endObject();
}
builder.endObject();
return new BytesRestResponse(response.isExists() ? OK : NOT_FOUND, builder);
}
private void buildExplanation(XContentBuilder builder, Explanation explanation) throws IOException {
@ -147,15 +140,6 @@ public class RestExplainAction extends BaseRestHandler {
builder.endArray();
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.get;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;
@ -30,14 +29,12 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import org.elasticsearch.search.fetch.source.FetchSourceContext;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
/**
*
@ -74,29 +71,16 @@ public class RestGetAction extends BaseRestHandler {
getRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));
client.get(getRequest, new ActionListener<GetResponse>() {
client.get(getRequest, new RestBuilderListener<GetResponse>(channel) {
@Override
public void onResponse(GetResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
response.toXContent(builder, request);
if (!response.isExists()) {
channel.sendResponse(new BytesRestResponse(NOT_FOUND, builder));
} else {
channel.sendResponse(new BytesRestResponse(OK, builder));
}
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
public RestResponse buildResponse(GetResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
if (!response.isExists()) {
return new BytesRestResponse(NOT_FOUND, builder);
} else {
return new BytesRestResponse(OK, builder);
}
}
});

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.get;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
@ -27,8 +26,9 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.elasticsearch.search.fetch.source.FetchSourceContext;
import java.io.IOException;
@ -36,7 +36,6 @@ import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
/**
*
@ -66,35 +65,21 @@ public class RestGetSourceAction extends BaseRestHandler {
try {
ActionRequestValidationException validationError = new ActionRequestValidationException();
validationError.addValidationError("fetching source can not be disabled");
channel.sendResponse(new BytesRestResponse(request, validationError));
channel.sendResponse(new BytesRestResponse(channel, validationError));
} catch (IOException e) {
logger.error("Failed to send failure response", e);
}
}
client.get(getRequest, new ActionListener<GetResponse>() {
client.get(getRequest, new RestResponseListener<GetResponse>(channel) {
@Override
public void onResponse(GetResponse response) {
try {
XContentBuilder builder = restContentBuilder(request, response.getSourceInternal());
if (!response.isExists()) {
channel.sendResponse(new BytesRestResponse(NOT_FOUND, builder));
} else {
RestXContentBuilder.directSource(response.getSourceInternal(), builder, request);
channel.sendResponse(new BytesRestResponse(OK, builder));
}
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
public RestResponse buildResponse(GetResponse response) throws Exception {
XContentBuilder builder = channel.newBuilder(response.getSourceInternal());
if (!response.isExists()) {
return new BytesRestResponse(NOT_FOUND, builder);
} else {
XContentHelper.writeDirect(response.getSourceInternal(), builder, request);
return new BytesRestResponse(OK, builder);
}
}
});

View File

@ -19,8 +19,6 @@
package org.elasticsearch.rest.action.get;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;
@ -28,6 +26,7 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
@ -59,26 +58,13 @@ public class RestHeadAction extends BaseRestHandler {
getRequest.fields(Strings.EMPTY_ARRAY);
// TODO we can also just return the document size as Content-Length
client.get(getRequest, new ActionListener<GetResponse>() {
client.get(getRequest, new RestResponseListener<GetResponse>(channel) {
@Override
public void onResponse(GetResponse response) {
try {
if (!response.isExists()) {
channel.sendResponse(new BytesRestResponse(NOT_FOUND));
} else {
channel.sendResponse(new BytesRestResponse(OK));
}
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(ExceptionsHelper.status(e)));
} catch (Exception e1) {
logger.error("Failed to send failure response", e1);
public RestResponse buildResponse(GetResponse response) {
if (!response.isExists()) {
return new BytesRestResponse(NOT_FOUND);
} else {
return new BytesRestResponse(OK);
}
}
});

View File

@ -29,6 +29,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import org.elasticsearch.search.fetch.source.FetchSourceContext;
import java.io.IOException;
@ -37,7 +38,6 @@ import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
public class RestMultiGetAction extends BaseRestHandler {
@ -57,7 +57,7 @@ public class RestMultiGetAction extends BaseRestHandler {
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
public void handleRequest(final RestRequest request, final RestChannel channel) throws Exception {
MultiGetRequest multiGetRequest = new MultiGetRequest();
multiGetRequest.listenerThreaded(false);
multiGetRequest.refresh(request.paramAsBoolean("refresh", multiGetRequest.refresh()));
@ -71,39 +71,8 @@ public class RestMultiGetAction extends BaseRestHandler {
}
FetchSourceContext defaultFetchSource = FetchSourceContext.parseFromRestRequest(request);
multiGetRequest.add(request.param("index"), request.param("type"), sFields, defaultFetchSource, request.param("routing"), RestActions.getRestContent(request), allowExplicitIndex);
try {
multiGetRequest.add(request.param("index"), request.param("type"), sFields, defaultFetchSource, request.param("routing"), RestActions.getRestContent(request), allowExplicitIndex);
} catch (Exception e) {
try {
XContentBuilder builder = restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
}
client.multiGet(multiGetRequest, new ActionListener<MultiGetResponse>() {
@Override
public void onResponse(MultiGetResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
response.toXContent(builder, request);
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.multiGet(multiGetRequest, new RestToXContentListener<MultiGetResponse>(channel));
}
}

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.index;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.WriteConsistencyLevel;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
@ -32,7 +31,7 @@ import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
@ -87,7 +86,7 @@ public class RestIndexAction extends BaseRestHandler {
indexRequest.opType(IndexRequest.OpType.CREATE);
} else {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
XContentBuilder builder = channel.newBuilder();
channel.sendResponse(new BytesRestResponse(BAD_REQUEST, builder.startObject().field("error", "opType [" + sOpType + "] not allowed, either [index] or [create] are allowed").endObject()));
} catch (IOException e1) {
logger.warn("Failed to send response", e1);
@ -103,35 +102,21 @@ public class RestIndexAction extends BaseRestHandler {
if (consistencyLevel != null) {
indexRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
}
client.index(indexRequest, new ActionListener<IndexResponse>() {
client.index(indexRequest, new RestBuilderListener<IndexResponse>(channel) {
@Override
public void onResponse(IndexResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject()
.field(Fields._INDEX, response.getIndex())
.field(Fields._TYPE, response.getType())
.field(Fields._ID, response.getId())
.field(Fields._VERSION, response.getVersion())
.field(Fields.CREATED, response.isCreated());
builder.endObject();
RestStatus status = OK;
if (response.isCreated()) {
status = CREATED;
}
channel.sendResponse(new BytesRestResponse(status, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
public RestResponse buildResponse(IndexResponse response, XContentBuilder builder) throws Exception {
builder.startObject()
.field(Fields._INDEX, response.getIndex())
.field(Fields._TYPE, response.getType())
.field(Fields._ID, response.getId())
.field(Fields._VERSION, response.getVersion())
.field(Fields.CREATED, response.isCreated());
builder.endObject();
RestStatus status = OK;
if (response.isCreated()) {
status = CREATED;
}
return new BytesRestResponse(status, builder);
}
});
}

View File

@ -23,7 +23,6 @@ import org.apache.lucene.util.Constants;
import org.elasticsearch.Build;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.client.Client;
@ -32,7 +31,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestResponseListener;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
@ -59,61 +58,43 @@ public class RestMainAction extends BaseRestHandler {
clusterStateRequest.masterNodeTimeout(TimeValue.timeValueMillis(0));
clusterStateRequest.local(true);
clusterStateRequest.clear().blocks(true);
client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() {
client.admin().cluster().state(clusterStateRequest, new RestResponseListener<ClusterStateResponse>(channel) {
@Override
public void onResponse(ClusterStateResponse response) {
public RestResponse buildResponse(ClusterStateResponse response) throws Exception {
RestStatus status = RestStatus.OK;
if (response.getState().blocks().hasGlobalBlock(RestStatus.SERVICE_UNAVAILABLE)) {
status = RestStatus.SERVICE_UNAVAILABLE;
}
if (request.method() == RestRequest.Method.HEAD) {
channel.sendResponse(new BytesRestResponse(status));
return;
return new BytesRestResponse(status);
}
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
XContentBuilder builder = channel.newBuilder();
// Default to pretty printing, but allow ?pretty=false to disable
if (!request.hasParam("pretty")) {
builder.prettyPrint().lfAtEnd();
}
builder.startObject();
builder.field("status", status.getStatus());
if (settings.get("name") != null) {
builder.field("name", settings.get("name"));
}
builder.startObject("version")
.field("number", version.number())
.field("build_hash", Build.CURRENT.hash())
.field("build_timestamp", Build.CURRENT.timestamp())
.field("build_snapshot", version.snapshot)
// We use the lucene version from lucene constants since
// this includes bugfix release version as well and is already in
// the right format. We can also be sure that the format is maitained
// since this is also recorded in lucene segments and has BW compat
.field("lucene_version", Constants.LUCENE_MAIN_VERSION)
.endObject();
builder.field("tagline", "You Know, for Search");
builder.endObject();
channel.sendResponse(new BytesRestResponse(status, builder));
} catch (Throwable e) {
onFailure(e);
// Default to pretty printing, but allow ?pretty=false to disable
if (!request.hasParam("pretty")) {
builder.prettyPrint().lfAtEnd();
}
}
@Override
public void onFailure(Throwable e) {
try {
if (request.method() == HEAD) {
channel.sendResponse(new BytesRestResponse(ExceptionsHelper.status(e)));
} else {
channel.sendResponse(new BytesRestResponse(request, e));
}
} catch (Exception e1) {
logger.warn("Failed to send response", e);
builder.startObject();
builder.field("status", status.getStatus());
if (settings.get("name") != null) {
builder.field("name", settings.get("name"));
}
builder.startObject("version")
.field("number", version.number())
.field("build_hash", Build.CURRENT.hash())
.field("build_timestamp", Build.CURRENT.timestamp())
.field("build_snapshot", version.snapshot)
// We use the lucene version from lucene constants since
// this includes bugfix release version as well and is already in
// the right format. We can also be sure that the format is maitained
// since this is also recorded in lucene segments and has BW compat
.field("lucene_version", Constants.LUCENE_MAIN_VERSION)
.endObject();
builder.field("tagline", "You Know, for Search");
builder.endObject();
return new BytesRestResponse(status, builder);
}
});
}

View File

@ -28,6 +28,7 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import org.elasticsearch.search.Scroll;
import java.io.IOException;
@ -36,9 +37,7 @@ import static org.elasticsearch.client.Requests.moreLikeThisRequest;
import static org.elasticsearch.common.unit.TimeValue.parseTimeValue;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
/**
*
@ -58,71 +57,39 @@ public class RestMoreLikeThisAction extends BaseRestHandler {
mltRequest.routing(request.param("routing"));
mltRequest.listenerThreaded(false);
try {
//TODO the ParseField class that encapsulates the supported names used for an attribute
//needs some work if it is to be used in a REST context like this too
// See the MoreLikeThisQueryParser constants that hold the valid syntax
mltRequest.fields(request.paramAsStringArray("mlt_fields", null));
mltRequest.percentTermsToMatch(request.paramAsFloat("percent_terms_to_match", -1));
mltRequest.minTermFreq(request.paramAsInt("min_term_freq", -1));
mltRequest.maxQueryTerms(request.paramAsInt("max_query_terms", -1));
mltRequest.stopWords(request.paramAsStringArray("stop_words", null));
mltRequest.minDocFreq(request.paramAsInt("min_doc_freq", -1));
mltRequest.maxDocFreq(request.paramAsInt("max_doc_freq", -1));
mltRequest.minWordLength(request.paramAsInt("min_word_len", request.paramAsInt("min_word_length",-1)));
mltRequest.maxWordLength(request.paramAsInt("max_word_len", request.paramAsInt("max_word_length",-1)));
mltRequest.boostTerms(request.paramAsFloat("boost_terms", -1));
//TODO the ParseField class that encapsulates the supported names used for an attribute
//needs some work if it is to be used in a REST context like this too
// See the MoreLikeThisQueryParser constants that hold the valid syntax
mltRequest.fields(request.paramAsStringArray("mlt_fields", null));
mltRequest.percentTermsToMatch(request.paramAsFloat("percent_terms_to_match", -1));
mltRequest.minTermFreq(request.paramAsInt("min_term_freq", -1));
mltRequest.maxQueryTerms(request.paramAsInt("max_query_terms", -1));
mltRequest.stopWords(request.paramAsStringArray("stop_words", null));
mltRequest.minDocFreq(request.paramAsInt("min_doc_freq", -1));
mltRequest.maxDocFreq(request.paramAsInt("max_doc_freq", -1));
mltRequest.minWordLength(request.paramAsInt("min_word_len", request.paramAsInt("min_word_length", -1)));
mltRequest.maxWordLength(request.paramAsInt("max_word_len", request.paramAsInt("max_word_length", -1)));
mltRequest.boostTerms(request.paramAsFloat("boost_terms", -1));
mltRequest.searchType(SearchType.fromString(request.param("search_type")));
mltRequest.searchIndices(request.paramAsStringArray("search_indices", null));
mltRequest.searchTypes(request.paramAsStringArray("search_types", null));
mltRequest.searchQueryHint(request.param("search_query_hint"));
mltRequest.searchSize(request.paramAsInt("search_size", mltRequest.searchSize()));
mltRequest.searchFrom(request.paramAsInt("search_from", mltRequest.searchFrom()));
String searchScroll = request.param("search_scroll");
if (searchScroll != null) {
mltRequest.searchScroll(new Scroll(parseTimeValue(searchScroll, null)));
mltRequest.searchType(SearchType.fromString(request.param("search_type")));
mltRequest.searchIndices(request.paramAsStringArray("search_indices", null));
mltRequest.searchTypes(request.paramAsStringArray("search_types", null));
mltRequest.searchQueryHint(request.param("search_query_hint"));
mltRequest.searchSize(request.paramAsInt("search_size", mltRequest.searchSize()));
mltRequest.searchFrom(request.paramAsInt("search_from", mltRequest.searchFrom()));
String searchScroll = request.param("search_scroll");
if (searchScroll != null) {
mltRequest.searchScroll(new Scroll(parseTimeValue(searchScroll, null)));
}
if (request.hasContent()) {
mltRequest.searchSource(request.content(), request.contentUnsafe());
} else {
String searchSource = request.param("search_source");
if (searchSource != null) {
mltRequest.searchSource(searchSource);
}
if (request.hasContent()) {
mltRequest.searchSource(request.content(), request.contentUnsafe());
} else {
String searchSource = request.param("search_source");
if (searchSource != null) {
mltRequest.searchSource(searchSource);
}
}
} catch (Exception e) {
try {
XContentBuilder builder = restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
}
client.moreLikeThis(mltRequest, new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
builder.startObject();
response.toXContent(builder, request);
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.moreLikeThis(mltRequest, new RestToXContentListener<SearchResponse>(channel));
}
}

View File

@ -29,13 +29,13 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import java.io.IOException;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
/**
*
@ -59,45 +59,14 @@ public class RestMultiPercolateAction extends BaseRestHandler {
}
@Override
public void handleRequest(final RestRequest restRequest, final RestChannel restChannel) {
public void handleRequest(final RestRequest restRequest, final RestChannel restChannel) throws Exception {
MultiPercolateRequest multiPercolateRequest = new MultiPercolateRequest();
multiPercolateRequest.indicesOptions(IndicesOptions.fromRequest(restRequest, multiPercolateRequest.indicesOptions()));
multiPercolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
multiPercolateRequest.documentType(restRequest.param("type"));
multiPercolateRequest.add(RestActions.getRestContent(restRequest), restRequest.contentUnsafe(), allowExplicitIndex);
try {
multiPercolateRequest.add(RestActions.getRestContent(restRequest), restRequest.contentUnsafe(), allowExplicitIndex);
} catch (Exception e) {
try {
restChannel.sendResponse(new BytesRestResponse(restRequest, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
}
client.multiPercolate(multiPercolateRequest, new ActionListener<MultiPercolateResponse>() {
@Override
public void onResponse(MultiPercolateResponse response) {
try {
XContentBuilder builder = restContentBuilder(restRequest);
response.toXContent(builder, restRequest);
restChannel.sendResponse(new BytesRestResponse(OK, builder));
} catch (IOException e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
restChannel.sendResponse(new BytesRestResponse(restRequest, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.multiPercolate(multiPercolateRequest, new RestToXContentListener<MultiPercolateResponse>(restChannel));
}
}

View File

@ -32,7 +32,7 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestXContentBuilder;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import java.io.IOException;
@ -112,27 +112,7 @@ public class RestPercolateAction extends BaseRestHandler {
percolateRequest.operationThreading(operationThreading);
}
client.percolate(percolateRequest, new ActionListener<PercolateResponse>() {
@Override
public void onResponse(PercolateResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(restRequest);
response.toXContent(builder, restRequest);
restChannel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
restChannel.sendResponse(new BytesRestResponse(restRequest, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.percolate(percolateRequest, new RestToXContentListener<PercolateResponse>(restChannel));
}
@Override

View File

@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.search;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.ClearScrollResponse;
import org.elasticsearch.client.Client;
@ -27,15 +26,13 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import java.io.IOException;
import java.util.Arrays;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
/**
*/
@ -55,26 +52,12 @@ public class RestClearScrollAction extends BaseRestHandler {
ClearScrollRequest clearRequest = new ClearScrollRequest();
clearRequest.setScrollIds(Arrays.asList(splitScrollIds(scrollIds)));
client.clearScroll(clearRequest, new ActionListener<ClearScrollResponse>() {
client.clearScroll(clearRequest, new RestBuilderListener<ClearScrollResponse>(channel) {
@Override
public void onResponse(ClearScrollResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
builder.startObject();
builder.endObject();
channel.sendResponse(new BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
public RestResponse buildResponse(ClearScrollResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}

View File

@ -30,6 +30,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestToXContentListener;
import java.io.IOException;
@ -37,7 +38,6 @@ import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder;
/**
*/
@ -60,48 +60,15 @@ public class RestMultiSearchAction extends BaseRestHandler {
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
public void handleRequest(final RestRequest request, final RestChannel channel) throws Exception {
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());
multiSearchRequest.add(RestActions.getRestContent(request), request.contentUnsafe(), indices, types, request.param("search_type"), request.param("routing"), indicesOptions, allowExplicitIndex);
try {
multiSearchRequest.add(RestActions.getRestContent(request), request.contentUnsafe(), indices, types, request.param("search_type"), request.param("routing"), indicesOptions, allowExplicitIndex);
} catch (Exception e) {
try {
XContentBuilder builder = restContentBuilder(request);
channel.sendResponse(new BytesRestResponse(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 BytesRestResponse(OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new BytesRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
client.multiSearch(multiSearchRequest, new RestToXContentListener<MultiSearchResponse>(channel));
}
}

Some files were not shown because too many files have changed in this diff Show More