org.elasticsearch.rest.RestResponse Java Examples

The following examples show how to use org.elasticsearch.rest.RestResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RestFeatureStoreCaches.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
private RestChannelConsumer clearCache(RestRequest request, NodeClient client) {
    String storeName = indexName(request);
    ClearCachesAction.ClearCachesNodesRequest cacheRequest = new ClearCachesAction.ClearCachesNodesRequest();
    cacheRequest.clearStore(storeName);
    return (channel) -> client.execute(ClearCachesAction.INSTANCE, cacheRequest,
        new RestBuilderListener<ClearCachesNodesResponse>(channel) {
            @Override
            public RestResponse buildResponse(ClearCachesNodesResponse clearCachesNodesResponse,
                                              XContentBuilder builder) throws Exception {
                builder.startObject()
                        .field("acknowledged", true);
                builder.endObject();
                return new BytesRestResponse(OK, builder);
            }
        }
    );
}
 
Example #2
Source File: RestUpgradeAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
void handlePost(final RestRequest request, RestChannel channel, Client client) {
    UpgradeRequest upgradeReq = new UpgradeRequest(Strings.splitStringByCommaToArray(request.param("index")));
    upgradeReq.upgradeOnlyAncientSegments(request.paramAsBoolean("only_ancient_segments", false));
    client.admin().indices().upgrade(upgradeReq, new RestBuilderListener<UpgradeResponse>(channel) {
        @Override
        public RestResponse buildResponse(UpgradeResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            buildBroadcastShardsHeader(builder, request, response);
            builder.startObject("upgraded_indices");
            for (Map.Entry<String, Tuple<Version, String>> entry : response.versions().entrySet()) {
                builder.startObject(entry.getKey(), XContentBuilder.FieldCaseConversion.NONE);
                builder.field("upgrade_version", entry.getValue().v1());
                builder.field("oldest_lucene_segment_version", entry.getValue().v2());
                builder.endObject();
            }
            builder.endObject();
            builder.endObject();
            return new BytesRestResponse(OK, builder);
        }
    });
}
 
Example #3
Source File: RestSegmentsAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected void doRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));

    final ClusterStateRequest clusterStateRequest = new ClusterStateRequest();
    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 RestActionListener<ClusterStateResponse>(channel) {
        @Override
        public void processResponse(final ClusterStateResponse clusterStateResponse) {
            final IndicesSegmentsRequest indicesSegmentsRequest = new IndicesSegmentsRequest();
            indicesSegmentsRequest.indices(indices);
            client.admin().indices().segments(indicesSegmentsRequest, new RestResponseListener<IndicesSegmentResponse>(channel) {
                @Override
                public RestResponse buildResponse(final IndicesSegmentResponse indicesSegmentResponse) throws Exception {
                    final Map<String, IndexSegments> indicesSegments = indicesSegmentResponse.getIndices();
                    Table tab = buildTable(request, clusterStateResponse, indicesSegments);
                    return RestTable.buildResponse(tab, channel);
                }
            });
        }
    });
}
 
Example #4
Source File: RestSnapshotAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected void doRequest(final RestRequest request, RestChannel channel, Client client) {
    GetSnapshotsRequest getSnapshotsRequest = new GetSnapshotsRequest()
            .repository(request.param("repository"))
            .snapshots(new String[]{GetSnapshotsRequest.ALL_SNAPSHOTS});

    getSnapshotsRequest.ignoreUnavailable(request.paramAsBoolean("ignore_unavailable", getSnapshotsRequest.ignoreUnavailable()));

    getSnapshotsRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getSnapshotsRequest.masterNodeTimeout()));

    client.admin().cluster().getSnapshots(getSnapshotsRequest, new RestResponseListener<GetSnapshotsResponse>(channel) {
        @Override
        public RestResponse buildResponse(GetSnapshotsResponse getSnapshotsResponse) throws Exception {
            return RestTable.buildResponse(buildTable(request, getSnapshotsResponse), channel);
        }
    });
}
 
Example #5
Source File: RestCountAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void doRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    CountRequest countRequest = new CountRequest(indices);
    String source = request.param("source");
    if (source != null) {
        countRequest.source(source);
    } else {
        QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
        if (querySourceBuilder != null) {
            countRequest.source(querySourceBuilder);
        }
    }

    client.search(countRequest.toSearchRequest(), new RestResponseListener<SearchResponse>(channel) {
        @Override
        public RestResponse buildResponse(SearchResponse countResponse) throws Exception {
            return RestTable.buildResponse(buildTable(request, countResponse), channel);
        }
    });
}
 
Example #6
Source File: IndexAnomalyDetectorActionHandler.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private ActionListener<IndexResponse> indexAnomalyDetectorResponse() {
    return new RestResponseListener<IndexResponse>(channel) {
        @Override
        public RestResponse buildResponse(IndexResponse response) throws Exception {
            if (response.getShardInfo().getSuccessful() < 1) {
                return new BytesRestResponse(response.status(), response.toXContent(channel.newErrorBuilder(), EMPTY_PARAMS));
            }

            XContentBuilder builder = channel
                .newBuilder()
                .startObject()
                .field(RestHandlerUtils._ID, response.getId())
                .field(RestHandlerUtils._VERSION, response.getVersion())
                .field(RestHandlerUtils._SEQ_NO, response.getSeqNo())
                .field(RestHandlerUtils._PRIMARY_TERM, response.getPrimaryTerm())
                .field("anomaly_detector", anomalyDetector)
                .endObject();

            BytesRestResponse restResponse = new BytesRestResponse(response.status(), builder);
            if (response.status() == RestStatus.CREATED) {
                String location = String.format(Locale.ROOT, "%s/%s", AnomalyDetectorPlugin.AD_BASE_URI, response.getId());
                restResponse.addHeader("Location", location);
            }
            return restResponse;
        }
    };
}
 
Example #7
Source File: JobRestHandler.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
@Override
public RestResponse buildResponse(SearchResponse result, XContentBuilder builder) throws Exception {
	
	Response resp = new Response();
	resp.type = ResponseType.SearchResponse;
	resp.search = result;
	resp.fieldNames = search.tableFieldNames;
	
	queryResultCache.put(retId, resp);								
	Search.buildQuery(from, builder, result, logger, search.tableFieldNames, showMeta);
	return new BytesRestResponse(RestStatus.OK, builder);
}
 
Example #8
Source File: GetIndexRequestRestListener.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
@Override
public RestResponse buildResponse(GetIndexResponse getIndexResponse, XContentBuilder builder) throws Exception {
    GetIndexRequest.Feature[] features = getIndexRequest.features();
    String[] indices = getIndexResponse.indices();

    builder.startObject();
    for (String index : indices) {
        builder.startObject(index);
        for (GetIndexRequest.Feature feature : features) {
            switch (feature) {
                case ALIASES:
                    writeAliases(getIndexResponse.aliases().get(index), builder, channel.request());
                    break;
                case MAPPINGS:
                    writeMappings(getIndexResponse.mappings().get(index), builder, channel.request());
                    break;
                case SETTINGS:
                    writeSettings(getIndexResponse.settings().get(index), builder, channel.request());
                    break;
                default:
                    throw new IllegalStateException("feature [" + feature + "] is not valid");
            }
        }
        builder.endObject();

    }
    builder.endObject();

    return new BytesRestResponse(RestStatus.OK, builder);
}
 
Example #9
Source File: XmlFilter.java    From elasticsearch-xml with Apache License 2.0 5 votes vote down vote up
@Override
public void sendResponse(RestResponse response) {
    if (!response.status().equals(RestStatus.OK)) {
        channel.sendResponse(response);
    }
    if (isXml(request)) {
        XContentParser parser = null;
        try {
            String string = response.content().toUtf8(); // takes some space ... :(
            XContentType xContentType = XContentFactory.xContentType(string);
            parser = XContentFactory.xContent(xContentType).createParser(string);
            parser.nextToken();
            XmlXContentBuilder builder = XmlXContentFactory.xmlBuilder(params);
            if (request.paramAsBoolean("pretty", false)) {
                builder.prettyPrint();
            }
            builder.copyCurrentStructure(parser);
            BytesRestResponse restResponse = new BytesRestResponse(RestStatus.OK, "text/xml; charset=UTF-8", builder.bytes());
            channel.sendResponse(restResponse);
            return;
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, e.getMessage()));
            return;
        } finally {
            if (parser != null) {
                parser.close();
            }
        }
    }
    channel.sendResponse(response);
}
 
Example #10
Source File: RestSimpleFeatureStore.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
RestChannelConsumer getStore(NodeClient client, String indexName) {
    return (channel) -> client.admin().indices().prepareExists(indexName)
            .execute(new RestBuilderListener<IndicesExistsResponse>(channel) {
                @Override
                public RestResponse buildResponse(IndicesExistsResponse indicesExistsResponse,
                                                  XContentBuilder builder) throws Exception {
                    builder.startObject()
                            .field("exists", indicesExistsResponse.isExists())
                            .endObject()
                            .close();
                    return new BytesRestResponse(indicesExistsResponse.isExists() ? RestStatus.OK : RestStatus.NOT_FOUND,
                            builder);
                }
            });
}
 
Example #11
Source File: RestRepositoriesAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected void doRequest(final RestRequest request, RestChannel channel, Client client) {
    GetRepositoriesRequest getRepositoriesRequest = new GetRepositoriesRequest();
    getRepositoriesRequest.local(request.paramAsBoolean("local", getRepositoriesRequest.local()));
    getRepositoriesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRepositoriesRequest.masterNodeTimeout()));

    client.admin().cluster().getRepositories(getRepositoriesRequest, new RestResponseListener<GetRepositoriesResponse>(channel) {
        @Override
        public RestResponse buildResponse(GetRepositoriesResponse getRepositoriesResponse) throws Exception {
            return RestTable.buildResponse(buildTable(request, getRepositoriesResponse), channel);
        }
    });
}
 
Example #12
Source File: RestRecoveryAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void doRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final RecoveryRequest recoveryRequest = new RecoveryRequest(Strings.splitStringByCommaToArray(request.param("index")));
    recoveryRequest.detailed(request.paramAsBoolean("detailed", false));
    recoveryRequest.activeOnly(request.paramAsBoolean("active_only", false));
    recoveryRequest.indicesOptions(IndicesOptions.fromRequest(request, recoveryRequest.indicesOptions()));

    client.admin().indices().recoveries(recoveryRequest, new RestResponseListener<RecoveryResponse>(channel) {
        @Override
        public RestResponse buildResponse(final RecoveryResponse response) throws Exception {
            return RestTable.buildResponse(buildRecoveryTable(request, response), channel);
        }
    });
}
 
Example #13
Source File: AbstractSearchAction.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private RestResponseListener<SearchResponse> search(RestChannel channel, Class<T> clazz) {
    return new RestResponseListener<SearchResponse>(channel) {
        @Override
        public RestResponse buildResponse(SearchResponse response) throws Exception {
            if (response.isTimedOut()) {
                return new BytesRestResponse(RestStatus.REQUEST_TIMEOUT, response.toString());
            }

            if (clazz == AnomalyDetector.class) {
                for (SearchHit hit : response.getHits()) {
                    XContentParser parser = XContentType.JSON
                        .xContent()
                        .createParser(
                            channel.request().getXContentRegistry(),
                            LoggingDeprecationHandler.INSTANCE,
                            hit.getSourceAsString()
                        );
                    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);

                    // write back id and version to anomaly detector object
                    ToXContentObject xContentObject = AnomalyDetector.parse(parser, hit.getId(), hit.getVersion());
                    XContentBuilder builder = xContentObject.toXContent(jsonBuilder(), EMPTY_PARAMS);
                    hit.sourceRef(BytesReference.bytes(builder));
                }
            }

            return new BytesRestResponse(RestStatus.OK, response.toXContent(channel.newBuilder(), EMPTY_PARAMS));
        }
    };
}
 
Example #14
Source File: AcknowledgedRestListener.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public RestResponse buildResponse(T response, XContentBuilder builder) throws Exception {
    builder.startObject()
            .field(Fields.ACKNOWLEDGED, response.isAcknowledged());
    addCustomFields(builder, response);
    builder.endObject();
    return new BytesRestResponse(OK, builder);
}
 
Example #15
Source File: RestUpgradeAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
void handleGet(final RestRequest request, RestChannel channel, Client client) {
    client.admin().indices().prepareUpgradeStatus(Strings.splitStringByCommaToArray(request.param("index")))
            .execute(new RestBuilderListener<UpgradeStatusResponse>(channel) {
                @Override
                public RestResponse buildResponse(UpgradeStatusResponse response, XContentBuilder builder) throws Exception {
                    builder.startObject();
                    response.toXContent(builder, request);
                    builder.endObject();
                    return new BytesRestResponse(OK, builder);
                }
            });
}
 
Example #16
Source File: RestRenderSearchTemplateAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception {
    RenderSearchTemplateRequest renderSearchTemplateRequest;
    BytesReference source = RestActions.getRestContent(request);
    XContentParser parser = XContentFactory.xContent(source).createParser(source);
    String templateId = request.param("id");
    final Template template;
    if (templateId == null) {
        template = Template.parse(parser, parseFieldMatcher);
    } else {
        Map<String, Object> params = null;
        String currentFieldName = null;
        XContentParser.Token token = parser.nextToken();
        if (token != XContentParser.Token.START_OBJECT) {
            throw new ElasticsearchParseException("failed to parse request. request body must be an object but found [{}] instead", token);
        }
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (parseFieldMatcher.match(currentFieldName, ScriptField.PARAMS)) {
                if (token == XContentParser.Token.START_OBJECT) {
                    params = parser.map();
                } else {
                    throw new ElasticsearchParseException("failed to parse request. field [{}] is expected to be an object, but found [{}] instead", currentFieldName, token);
                }
            } else {
                throw new ElasticsearchParseException("failed to parse request. unknown field [{}] of type [{}]", currentFieldName, token);
            }
        }
        template = new Template(templateId, ScriptType.INDEXED, MustacheScriptEngineService.NAME, null, params);
    }
    renderSearchTemplateRequest = new RenderSearchTemplateRequest();
    renderSearchTemplateRequest.template(template);
    client.admin().cluster().renderSearchTemplate(renderSearchTemplateRequest, new RestBuilderListener<RenderSearchTemplateResponse>(channel) {

        @Override
        public RestResponse buildResponse(RenderSearchTemplateResponse response, XContentBuilder builder) throws Exception {
            builder.prettyPrint();
            response.toXContent(builder, ToXContent.EMPTY_PARAMS);
            return new BytesRestResponse(OK, builder);
        }});
}
 
Example #17
Source File: HTTPSamlAuthenticatorTest.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@Override
public void sendResponse(RestResponse response) {
    this.response = response;

}
 
Example #18
Source File: RestGetAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
private RestResponse buildInternalServerErrorResponse(Exception e, String errorMsg) {
    logger.error(errorMsg, e);
    return new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, errorMsg);
}
 
Example #19
Source File: OpenShiftRestResponseTest.java    From openshift-elasticsearch-plugin with Apache License 2.0 4 votes vote down vote up
private OpenShiftRestResponse whenCreatingResponseResponse(ToXContent content) throws Exception {
    RestResponse response = new BytesRestResponse(RestStatus.CREATED, content.toXContent(XContentBuilder.builder(XCONTENT), ToXContent.EMPTY_PARAMS));
    return new OpenShiftRestResponse(response, CONTEXT, DEFAULT_USER_PROFILE_PREFIX);
}
 
Example #20
Source File: RestChannelInterceptor.java    From openshift-elasticsearch-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void sendResponse(RestResponse response) {
    OpenshiftRequestContext context = threadContext.getTransient(ConfigurationSettings.OPENSHIFT_REQUEST_CONTEXT);
    channel.sendResponse(new OpenShiftRestResponse(response, context, defaultKibanaIndex));
}
 
Example #21
Source File: OpenShiftRestResponse.java    From openshift-elasticsearch-plugin with Apache License 2.0 4 votes vote down vote up
OpenShiftRestResponse(final RestResponse response, final OpenshiftRequestContext context, final String defaultKibanaIndex){
    this.response = response;
    this.content = evaluateContentForKibanaIndex(response.content(), context, defaultKibanaIndex);
}
 
Example #22
Source File: NettyHttpChannel.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void doSendResponse(RestResponse response) {
    // if the response object was created upstream, then use it;
    // otherwise, create a new one
    HttpResponse resp = newResponse();
    resp.setStatus(getStatus(response.status()));

    CorsHandler.setCorsResponseHeaders(nettyRequest, resp, transport.getCorsConfig());

    String opaque = nettyRequest.headers().get("X-Opaque-Id");
    if (opaque != null) {
        resp.headers().add("X-Opaque-Id", opaque);
    }

    // Add all custom headers
    Map<String, List<String>> customHeaders = response.getHeaders();
    if (customHeaders != null) {
        for (Map.Entry<String, List<String>> headerEntry : customHeaders.entrySet()) {
            for (String headerValue : headerEntry.getValue()) {
                resp.headers().add(headerEntry.getKey(), headerValue);
            }
        }
    }

    BytesReference content = response.content();
    ChannelBuffer buffer;
    boolean addedReleaseListener = false;
    try {
        buffer = content.toChannelBuffer();
        resp.setContent(buffer);

        // If our response doesn't specify a content-type header, set one
        if (!resp.headers().contains(HttpHeaders.Names.CONTENT_TYPE)) {
            resp.headers().add(HttpHeaders.Names.CONTENT_TYPE, response.contentType());
        }

        // If our response has no content-length, calculate and set one
        if (!resp.headers().contains(HttpHeaders.Names.CONTENT_LENGTH)) {
            resp.headers().add(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buffer.readableBytes()));
        }

        if (transport.resetCookies) {
            String cookieString = nettyRequest.headers().get(HttpHeaders.Names.COOKIE);
            if (cookieString != null) {
                CookieDecoder cookieDecoder = new CookieDecoder();
                Set<Cookie> cookies = cookieDecoder.decode(cookieString);
                if (!cookies.isEmpty()) {
                    // Reset the cookies if necessary.
                    CookieEncoder cookieEncoder = new CookieEncoder(true);
                    for (Cookie cookie : cookies) {
                        cookieEncoder.addCookie(cookie);
                    }
                    resp.headers().add(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode());
                }
            }
        }

        ChannelFuture future;

        if (orderedUpstreamMessageEvent != null) {
            OrderedDownstreamChannelEvent downstreamChannelEvent = new OrderedDownstreamChannelEvent(orderedUpstreamMessageEvent, 0, true, resp);
            future = downstreamChannelEvent.getFuture();
            channel.getPipeline().sendDownstream(downstreamChannelEvent);
        } else {
            future = channel.write(resp);
        }

        if (content instanceof Releasable) {
            future.addListener(new ReleaseChannelFutureListener((Releasable) content));
            addedReleaseListener = true;
        }

        if (isCloseConnection()) {
            future.addListener(ChannelFutureListener.CLOSE);
        }

    } finally {
        if (!addedReleaseListener && content instanceof Releasable) {
            ((Releasable) content).close();
        }
    }
}
 
Example #23
Source File: RestUpdateAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
    UpdateRequest updateRequest = new UpdateRequest(request.param("index"), request.param("type"), request.param("id"));
    updateRequest.routing(request.param("routing"));
    updateRequest.parent(request.param("parent"));
    updateRequest.timeout(request.paramAsTime("timeout", updateRequest.timeout()));
    updateRequest.refresh(request.paramAsBoolean("refresh", updateRequest.refresh()));
    String consistencyLevel = request.param("consistency");
    if (consistencyLevel != null) {
        updateRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
    }
    updateRequest.docAsUpsert(request.paramAsBoolean("doc_as_upsert", updateRequest.docAsUpsert()));
    ScriptParameterParser scriptParameterParser = new ScriptParameterParser();
    scriptParameterParser.parseParams(request);
    ScriptParameterValue scriptValue = scriptParameterParser.getDefaultScriptParameterValue();
    if (scriptValue != null) {
        Map<String, Object> scriptParams = new HashMap<>();
        for (Map.Entry<String, String> entry : request.params().entrySet()) {
            if (entry.getKey().startsWith("sp_")) {
                scriptParams.put(entry.getKey().substring(3), entry.getValue());
            }
        }
        updateRequest.script(new Script(scriptValue.script(), scriptValue.scriptType(), scriptParameterParser.lang(), scriptParams));
    }
    String sField = request.param("fields");
    if (sField != null) {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
            updateRequest.fields(sFields);
        }
    }
    updateRequest.retryOnConflict(request.paramAsInt("retry_on_conflict", updateRequest.retryOnConflict()));
    updateRequest.version(RestActions.parseVersion(request));
    updateRequest.versionType(VersionType.fromString(request.param("version_type"), updateRequest.versionType()));


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

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

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

            builder.endObject();
            RestStatus status = shardInfo.status();
            if (response.isCreated()) {
                status = CREATED;
            }
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example #24
Source File: RestStatusToXContentListener.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public final RestResponse buildResponse(Response response) throws Exception {
    return buildResponse(response, channel.newBuilder());
}
 
Example #25
Source File: RestStatusToXContentListener.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public final RestResponse buildResponse(Response response, XContentBuilder builder) throws Exception {
    builder.startObject();
    response.toXContent(builder, channel.request());
    builder.endObject();
    return new BytesRestResponse(response.status(), builder);
}
 
Example #26
Source File: RestToXContentListener.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public final RestResponse buildResponse(Response response, XContentBuilder builder) throws Exception {
    builder.startObject();
    response.toXContent(builder, channel.request());
    builder.endObject();
    return new BytesRestResponse(getStatus(response), builder);
}
 
Example #27
Source File: RestToXContentListener.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public final RestResponse buildResponse(Response response) throws Exception {
    return buildResponse(response, channel.newBuilder());
}
 
Example #28
Source File: RestBuilderListener.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public final RestResponse buildResponse(Response response) throws Exception {
    return buildResponse(response, channel.newBuilder());
}
 
Example #29
Source File: RestResponseListener.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * Builds the response to send back through the channel.
 */
public abstract RestResponse buildResponse(Response response) throws Exception;
 
Example #30
Source File: RestBuilderListener.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * Builds a response to send back over the channel.
 */
public abstract RestResponse buildResponse(Response response, XContentBuilder builder) throws Exception;