Java Code Examples for org.elasticsearch.rest.RestChannel

The following examples show how to use org.elasticsearch.rest.RestChannel. These examples are extracted from open source projects. 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 Project: elasticsearch-taste   Source File: TasteActionRestAction.java    License: Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request,
        final RestChannel channel, final Map<String, Object> params,
        final boolean acknowledged) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        if (request.hasParam("pretty")) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", acknowledged);
        if (params != null) {
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                builder.field(entry.getKey(), entry.getValue());
            }
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final Exception e) {
        sendErrorResponse(channel, e);
    }
}
 
Example 2
boolean handle(RestRequest restRequest, RestChannel restChannel) throws Exception {
    try {
        final SecurityManager sm = System.getSecurityManager();

        if (sm != null) {
            sm.checkPermission(new SpecialPermission());
        }

        return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws XPathExpressionException, SamlConfigException, IOException,
                    ParserConfigurationException, SAXException, SettingsException {
                return handleLowLevel(restRequest, restChannel);
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof Exception) {
            throw (Exception) e.getCause();
        } else {
            throw new RuntimeException(e);
        }
    }
}
 
Example 3
protected void handleGet(final RestChannel channel, RestRequest request, Client client, final JsonNode content)
		throws IOException{

	final String resourcename = request.param("name");

	final SecurityDynamicConfiguration<?> configuration = load(getConfigName(), true);
	filter(configuration);


	// no specific resource requested, return complete config
	if (resourcename == null || resourcename.length() == 0) {

		successResponse(channel, configuration);
		return;
	}

	if (!configuration.exists(resourcename)) {
		notFound(channel, "Resource '" + resourcename + "' not found.");
		return;
	}

	configuration.removeOthers(resourcename);
	successResponse(channel, configuration);

	return;
}
 
Example 4
Source Project: elasticsearch-dataformat   Source File: RestDataAction.java    License: Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request, final RestChannel channel, final String file) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        final String pretty = request.param("pretty");
        if (pretty != null && !"false".equalsIgnoreCase(pretty)) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", true);
        builder.field("file", file);
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final IOException e) {
        throw new ElasticsearchException("Failed to create a resposne.", e);
    }
}
 
Example 5
private void deleteAnomalyDetectorJobDoc(NodeClient client, String detectorId, RestChannel channel) {
    logger.info("Delete anomaly detector job {}", detectorId);
    DeleteRequest deleteRequest = new DeleteRequest(AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX, detectorId)
        .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
    client.delete(deleteRequest, ActionListener.wrap(response -> {
        if (response.getResult() == DocWriteResponse.Result.DELETED || response.getResult() == DocWriteResponse.Result.NOT_FOUND) {
            deleteAnomalyDetectorDoc(client, detectorId, channel);
        } else {
            logger.error("Fail to delete anomaly detector job {}", detectorId);
        }
    }, exception -> {
        if (exception instanceof IndexNotFoundException) {
            deleteAnomalyDetectorDoc(client, detectorId, channel);
        } else {
            logger.error("Failed to delete anomaly detector job", exception);
            try {
                channel.sendResponse(new BytesRestResponse(channel, exception));
            } catch (IOException e) {
                logger.error("Failed to send response of delete anomaly detector job exception", e);
            }
        }
    }));
}
 
Example 6
/**
 * Get detector job for update/delete AD job.
 * If AD job exist, will return error message; otherwise, execute function.
 *
 * @param clusterService ES cluster service
 * @param client ES node client
 * @param detectorId detector identifier
 * @param channel ES rest channel
 * @param function AD function
 */
public void getDetectorJob(
    ClusterService clusterService,
    NodeClient client,
    String detectorId,
    RestChannel channel,
    AnomalyDetectorFunction function
) {
    if (clusterService.state().metadata().indices().containsKey(ANOMALY_DETECTOR_JOB_INDEX)) {
        GetRequest request = new GetRequest(ANOMALY_DETECTOR_JOB_INDEX).id(detectorId);
        client.get(request, ActionListener.wrap(response -> onGetAdJobResponseForWrite(response, channel, function), exception -> {
            logger.error("Fail to get anomaly detector job: " + detectorId, exception);
            try {
                channel.sendResponse(new BytesRestResponse(channel, exception));
            } catch (IOException e) {
                logger.error("Fail to send exception" + detectorId, e);
            }
        }));
    } else {
        function.execute();
    }
}
 
Example 7
private void onGetAdJobResponseForWrite(GetResponse response, RestChannel channel, AnomalyDetectorFunction function) {
    if (response.isExists()) {
        String adJobId = response.getId();
        if (adJobId != null) {
            // check if AD job is running on the detector, if yes, we can't delete the detector
            try (XContentParser parser = RestHandlerUtils.createXContentParser(channel, response.getSourceAsBytesRef())) {
                ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
                AnomalyDetectorJob adJob = AnomalyDetectorJob.parse(parser);
                if (adJob.isEnabled()) {
                    channel.sendResponse(new BytesRestResponse(RestStatus.BAD_REQUEST, "Detector job is running: " + adJobId));
                    return;
                }
            } catch (IOException e) {
                String message = "Failed to parse anomaly detector job " + adJobId;
                logger.error(message, e);
                channel.sendResponse(new BytesRestResponse(RestStatus.BAD_REQUEST, message));
            }
        }
    }
    function.execute();
}
 
Example 8
private ActionListener<StopDetectorResponse> stopAdDetectorListener(RestChannel channel, String detectorId) {
    return new ActionListener<StopDetectorResponse>() {
        @Override
        public void onResponse(StopDetectorResponse stopDetectorResponse) {
            if (stopDetectorResponse.success()) {
                logger.info("AD model deleted successfully for detector {}", detectorId);
                channel.sendResponse(new BytesRestResponse(RestStatus.OK, "Stopped detector: " + detectorId));
            } else {
                logger.error("Failed to delete AD model for detector {}", detectorId);
                channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, "Failed to delete AD model"));
            }
        }

        @Override
        public void onFailure(Exception e) {
            logger.error("Failed to delete AD model for detector " + detectorId, e);
            channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, "Failed to execute stop detector action"));
        }
    };
}
 
Example 9
Source Project: Elasticsearch   Source File: ResponseUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void send(final RestChannel channel, final RestStatus status, final String message) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        builder.startObject()
                .field("status", status.getStatus())
                .field("message", message).endObject();
        BytesRestResponse bytesRestResponse = new BytesRestResponse(status, builder);
        if (status == RestStatus.UNAUTHORIZED) {
            bytesRestResponse.addHeader("WWW-authenticate", "Basic realm=\"Elasticsearch Authentication\"");
        }
        channel.sendResponse(bytesRestResponse);
    } catch (final IOException e) {
        logger.error("Failed to send a response.", e);
        try {
            channel.sendResponse(new BytesRestResponse(channel, e));
        } catch (final IOException e1) {
            logger.error("Failed to send a failure response.", e1);
        }
    }
}
 
Example 10
Source Project: Elasticsearch   Source File: AuthRestFilter.java    License: Apache License 2.0 6 votes vote down vote up
public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) {
    LoginUserContext user = null;
    request.putInContext(RestRequest.REQUEST_START_TIME, System.currentTimeMillis());
    try {
        user = new LoginUserContext(request, clusterService);
    } catch (NoPermissionException e) {
        logger.info("errors while parsing userinfo from request, error msg is [{}]", e.getMessage());
        ResponseUtil.send(channel, RestStatus.UNAUTHORIZED, e.getMessage());
        return;
    }

    if (user.loginUsername() == null || user.loginUsername().length() ==0) {
        ResponseUtil.send(channel, RestStatus.UNAUTHORIZED, "Username is empty");
        logger.info("Username is empty");
    }
    if (!user.authenticated() && (user.password() == null || user.password().length() ==0)) {
        ResponseUtil.send(channel, RestStatus.UNAUTHORIZED, "Password is empty");
        logger.info("Password is empty");
    }
    // put user info into context
    request.putHeader(LoginUserContext.USER_INFO_KEY, user);
    filterChain.continueProcessing(request, channel);
}
 
Example 11
public RestRequest continueProcessing(RestRequest request, RestChannel channel) throws Exception {
    try {
        if (threadContext.getTransient(OPENSHIFT_REQUEST_CONTEXT) != null) {
            OpenshiftRequestContext requestContext = threadContext.getTransient(OPENSHIFT_REQUEST_CONTEXT);
            request = utils.modifyRequest(request, requestContext, channel);
            Boolean syncAndSeed = threadContext.getTransient(SYNC_AND_SEED);
            if (requestContext != OpenshiftRequestContext.EMPTY){
                if(Boolean.TRUE.equals(syncAndSeed)) {
                    LOGGER.debug("Seeding dashboards and syncing ACLs for user {}", requestContext.getUser());
                    utils.logRequest(request);
                    final String kbnVersion = getKibanaVersion(request);
                    kibanaSeed.setDashboards(requestContext, kbnVersion, cdmProjectPrefix);
                    aclManager.syncAcl(requestContext);
                } else {
                    LOGGER.debug("Cache hit. Skipping dashboards and syncing ACLs for user {}", requestContext.getUser());
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error handling request", e);
    }
    return request;
}
 
Example 12
Source Project: Elasticsearch   Source File: RestListTasksAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    boolean detailed = request.paramAsBoolean("detailed", false);
    String[] nodesIds = Strings.splitStringByCommaToArray(request.param("node_id"));
    TaskId taskId = new TaskId(request.param("taskId"));
    String[] actions = Strings.splitStringByCommaToArray(request.param("actions"));
    TaskId parentTaskId = new TaskId(request.param("parent_task_id"));
    boolean waitForCompletion = request.paramAsBoolean("wait_for_completion", false);
    TimeValue timeout = request.paramAsTime("timeout", null);

    ListTasksRequest listTasksRequest = new ListTasksRequest();
    listTasksRequest.setTaskId(taskId);
    listTasksRequest.setNodesIds(nodesIds);
    listTasksRequest.setDetailed(detailed);
    listTasksRequest.setActions(actions);
    listTasksRequest.setParentTaskId(parentTaskId);
    listTasksRequest.setWaitForCompletion(waitForCompletion);
    listTasksRequest.setTimeout(timeout);
    client.admin().cluster().listTasks(listTasksRequest, new RestToXContentListener<ListTasksResponse>(channel));
}
 
Example 13
Source Project: elasticsearch-auth   Source File: ReloadRestAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void handleRequest(final RestRequest request,
        final RestChannel channel, final Client client) {

    authService.reload(new ActionListener<Void>() {
        @Override
        public void onResponse(final Void response) {
            ResponseUtil.send(request, channel, RestStatus.OK);
        }

        @Override
        public void onFailure(final Throwable e) {
            ResponseUtil.send(request, channel,
                    RestStatus.INTERNAL_SERVER_ERROR, "message",
                    "Failed to reload AuthService.");
        }
    });
}
 
Example 14
Source Project: elasticsearch-taste   Source File: TasteSearchRestAction.java    License: Apache License 2.0 5 votes vote down vote up
private void onError(final RestChannel channel, final Throwable t) {
    try {
        channel.sendResponse(new BytesRestResponse(channel, t));
    } catch (final Exception e) {
        logger.error("Failed to send a failure response.", e);
    }
}
 
Example 15
Source Project: elasticsearch-rest-command   Source File: JobRestHandler.java    License: The Unlicense 5 votes vote down vote up
private void sendTimeline(final RestRequest request,final RestChannel channel, SearchResponse response){
	XContentBuilder builder;
	try {
		builder = channel.newBuilder();							
		Search.buildTimeline(builder, response, logger);	
		channel.sendResponse(new BytesRestResponse(response.status(), builder));
	} catch (IOException e) {
		sendFailure(request, channel, e);
	}
}
 
Example 16
Source Project: elasticsearch-csv   Source File: CSVRestSearchAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    SearchRequest searchRequest = RestSearchAction.parseSearchRequest(request);
    searchRequest.listenerThreaded(false);
    client.search(searchRequest, new CSVToXContentListener(channel,
            request.paramAsStringArray("keys", null),
            request.paramAsBoolean("with_index", false),
                    request.paramAsBoolean("with_type", false),
                    request.paramAsBoolean("with_id", false))
    );
}
 
Example 17
Source Project: elasticsearch-dataformat   Source File: XlsContent.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void write(final File outputFile, final SearchResponse response, final RestChannel channel,
                  final ActionListener<Void> listener) {
    try {
        final OnLoadListener onLoadListener = new OnLoadListener(outputFile, listener);
        onLoadListener.onResponse(response);
    } catch (final Exception e) {
        listener.onFailure(new ElasticsearchException("Failed to write data.", e));
    }
}
 
Example 18
@Override
protected void handleApiRequest(RestChannel channel, final RestRequest request, final Client client)
        throws IOException {

    if (request.method() == Method.PATCH) {
        handlePatch(channel, request, client);
    } else {
        super.handleApiRequest(channel, request, client);
    }
}
 
Example 19
protected void handleDelete(final RestChannel channel, final RestRequest request, final Client client, final JsonNode content) throws IOException {
	final String name = request.param("name");

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

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

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

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

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

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

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

	} else {
		notFound(channel, getResourceName() + " " + name + " not found.");
	}
}
 
Example 20
Source Project: elasticsearch-dataformat   Source File: RestDataAction.java    License: Apache License 2.0 5 votes vote down vote up
private void writeResponse(final RestRequest request, final RestChannel channel, final File outputFile,
                           final long limit, final DataContent dataContent) {
    if (outputFile.length() > limit) {
        onFailure(new ElasticsearchException("Content size is too large " + outputFile.length()));
        return;
    }

    try (FileInputStream fis = new FileInputStream(outputFile)) {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final byte[] bytes = new byte[1024];
        int len;
        while ((len = fis.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }

        final ContentType contentType = dataContent.getContentType();
        final BytesRestResponse response = new BytesRestResponse(
                RestStatus.OK, contentType.contentType(),
                out.toByteArray());
        response.addHeader("Content-Disposition",
                "attachment; filename=\""
                        + contentType.fileName(request) + "\"");
        channel.sendResponse(response);
    } catch (final Throwable e) {
        throw new ElasticsearchException("Failed to render the content.", e);
    }
}
 
Example 21
protected void successResponse(RestChannel channel) {
	try {
		final XContentBuilder builder = channel.newBuilder();
		builder.startObject();
		channel.sendResponse(
				new BytesRestResponse(RestStatus.OK, builder));
	} catch (IOException e) {
		internalErrorResponse(channel, "Unable to fetch license: " + e.getMessage());
		log.error("Cannot fetch convert license to XContent due to", e);
	}
}
 
Example 22
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
  MultiSearchRequest multiSearchRequest = new MultiSearchRequest();

  String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
  String[] types = Strings.splitStringByCommaToArray(request.param("type"));
  String path = request.path();
  boolean isTemplateRequest = isTemplateRequest(path);
  IndicesOptions indicesOptions = IndicesOptions.fromRequest(request, multiSearchRequest.indicesOptions());
  multiSearchRequest.add(RestActions.getRestContent(request), isTemplateRequest, indices, types, request.param("search_type"), request.param("routing"), indicesOptions, allowExplicitIndex);

  client.execute(CoordinateMultiSearchAction.INSTANCE, multiSearchRequest, new RestToXContentListener<MultiSearchResponse>(channel));
}
 
Example 23
Source Project: elasticsearch-auth   Source File: ContentFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(final RestRequest request, final RestChannel channel,
        final RestFilterChain filterChain) {
    if (constraints == null) {
        init(request, channel, filterChain);
    } else {
        processNext(request, channel, filterChain);
    }
}
 
Example 24
Source Project: elasticsearch-csv   Source File: CSVToXContentListener.java    License: Apache License 2.0 5 votes vote down vote up
public CSVToXContentListener(RestChannel channel, String[] keys,
                             boolean withIndex, boolean withType, boolean withId) {
    super(channel);
    this.keys = keys;
    this.withIndex = withIndex;
    this.withType = withType;
    this.withId = withId;
}
 
Example 25
Source Project: elasticsearch-rest-command   Source File: CommandRestHandler.java    License: The Unlicense 5 votes vote down vote up
public void SendFailure(RestRequest request, RestChannel channel,
		Throwable e) {
	try {
		channel.sendResponse(new BytesRestResponse(channel, e));
	} catch (IOException e1) {
		logger.error("Failed to send failure response", e1);
	}
}
 
Example 26
@Override
protected void handleApiRequest(RestChannel channel, RestRequest request, Client client) throws IOException {
    if (request.method() == Method.PATCH && !allowPutOrPatch) {
        notImplemented(channel, Method.PATCH);
    } else {
        super.handleApiRequest(channel, request, client);
    }
}
 
Example 27
@Override
protected void handlePut(RestChannel channel, final RestRequest request, final Client client, final JsonNode content) throws IOException{
    if (allowPutOrPatch) {

        if(!"config".equals(request.param("name"))) {
            badRequestResponse(channel, "name must be config");
            return;
        }

        super.handlePut(channel, request, client, content);
    } else {
        notImplemented(channel, Method.PUT);
    }
}
 
Example 28
Source Project: elasticsearch-rest-command   Source File: JobRestHandler.java    License: The Unlicense 5 votes vote down vote up
public void sendFailure(RestRequest request, RestChannel channel, Throwable e) {
	try {
		channel.sendResponse(new BytesRestResponse(channel, e));
	} catch (IOException e1) {
		logger.error("Failed to send failure response", e1);
	}
}
 
Example 29
@Override
protected void handleDelete(RestChannel channel,
        RestRequest request, Client client, final JsonNode content) throws IOException
{

	client.execute(
			ConfigUpdateAction.INSTANCE,
			new ConfigUpdateRequest(CType.lcStringValues().toArray(new String[0])),
			new ActionListener<ConfigUpdateResponse>() {

				@Override
				public void onResponse(ConfigUpdateResponse ur) {
				    if(ur.hasFailures()) {
				        log.error("Cannot flush cache due to", ur.failures().get(0));
                        internalErrorResponse(channel, "Cannot flush cache due to "+ ur.failures().get(0).getMessage()+".");
                        return;
                    }
					successResponse(channel, "Cache flushed successfully.");
					if (log.isDebugEnabled()) {
					    log.debug("cache flushed successfully");
					}
				}

				@Override
				public void onFailure(Exception e) {
				    log.error("Cannot flush cache due to", e);
					internalErrorResponse(channel, "Cannot flush cache due to "+ e.getMessage()+".");
				}

			}
	);
}
 
Example 30
Source Project: elasticsearch-carrot2   Source File: LoggerUtils.java    License: Apache License 2.0 5 votes vote down vote up
static void emitErrorResponse(RestChannel channel,
                              Logger logger,
                              Exception e) {
    try {
        channel.sendResponse(new BytesRestResponse(channel, e));
    } catch (IOException e1) {
        logger.error("Failed to send failure response.", e1);
    }
}