Java Code Examples for org.elasticsearch.rest.RestRequest

The following examples show how to use org.elasticsearch.rest.RestRequest. 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   Source File: RestCountAction.java    License: 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 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 checkRequest(final RestRequest request, final RestChannel channel) {
    
    if(SSLRequestHelper.containsBadHeader(threadContext, "_opendistro_security_ssl_")) {
        final ElasticsearchException exception = ExceptionUtils.createBadHeaderException();
        errorHandler.logError(exception, request, 1);
        throw exception;
    }
    
    try {
        if(SSLRequestHelper.getSSLInfo(settings, configPath, request, null) == null) {
            logger.error("Not an SSL request");
            throw new ElasticsearchSecurityException("Not an SSL request", RestStatus.INTERNAL_SERVER_ERROR);
        }
    } catch (SSLPeerUnverifiedException e) {
        logger.error("No client certificates found but such are needed (Security 8).");
        errorHandler.logError(e, request, 0);
        throw ExceptionsHelper.convertToElastic(e);
    }
}
 
Example 4
@Override
protected AbstractConfigurationValidator postProcessApplyPatchResult(RestChannel channel, RestRequest request, JsonNode existingResourceAsJsonNode,
                                                                     JsonNode updatedResourceAsJsonNode, String resourceName) {
    AbstractConfigurationValidator retVal = null;
    JsonNode passwordNode = updatedResourceAsJsonNode.get("password");

    if (passwordNode != null) {
        String plainTextPassword = passwordNode.asText();
        try {
            XContentBuilder builder = channel.newBuilder();
            builder.startObject();
            builder.field("password", plainTextPassword);
            builder.endObject();
            retVal = getValidator(request, BytesReference.bytes(builder), resourceName);
        } catch (IOException e) {
            log.error(e);
        }

        ((ObjectNode) updatedResourceAsJsonNode).remove("password");
        ((ObjectNode) updatedResourceAsJsonNode).set("hash", new TextNode(hash(plainTextPassword.toCharArray())));
        return retVal;
    }

    return null;
}
 
Example 5
@Inject
public ReindexRestAction(final Settings settings, final Client client,
        final RestController restController,
        final ReindexingService reindexingService) {
    super(settings, restController, client);
    this.reindexingService = reindexingService;

    restController.registerHandler(RestRequest.Method.GET,
            "/_reindex", this);
    restController.registerHandler(RestRequest.Method.GET,
            "/_reindex/{name}", this);

    restController.registerHandler(RestRequest.Method.POST,
            "/{index}/{type}/_reindex/{toindex}/{totype}", this);
    restController.registerHandler(RestRequest.Method.POST,
            "/{index}/{type}/_reindex/{toindex}", this);
    restController.registerHandler(RestRequest.Method.POST,
            "/{index}/_reindex/{toindex}/{totype}", this);
    restController.registerHandler(RestRequest.Method.POST,
            "/{index}/_reindex/{toindex}", this);

    restController.registerHandler(RestRequest.Method.DELETE,
            "/_reindex/{name}", this);
}
 
Example 6
@Override
public ElasticsearchSecurityException exceptionProcessingRequest(final RestRequest request, final Exception e) {
    final ElasticsearchSecurityException se = super.exceptionProcessingRequest(request, e);
    String outToken = "";
    if (e instanceof ElasticsearchException) {
        final ElasticsearchException kae = (ElasticsearchException) e;
        if (kae.getHeader("kerberos_out_token") != null) {
            outToken = " " + kae.getHeader("kerberos_out_token").get(0);
        }
    }

    se.addHeader(KrbConstants.WWW_AUTHENTICATE, KrbConstants.NEGOTIATE + outToken);

    if (logger.isDebugEnabled()) {
        logger.debug("exception for rest request: {}", e.toString());
    }

    return se;
}
 
Example 7
Source Project: elasticsearch-auth   Source File: ResponseUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void send(final RestRequest request,
        final RestChannel channel, final RestStatus status,
        final String... args) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        builder.startObject();
        builder.field("status", status.getStatus());
        for (int i = 0; i < args.length; i += 2) {
            builder.field(args[i], args[i + 1]);
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(status, builder));
    } 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 8
Source Project: Elasticsearch   Source File: RestSnapshotAction.java    License: 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 9
@Override
public void logFailedLogin(String effectiveUser, boolean securityadmin, String initiatingUser, RestRequest request) {

    if(!checkRestFilter(Category.FAILED_LOGIN, effectiveUser, request)) {
        return;
    }

    AuditMessage msg = new AuditMessage(Category.FAILED_LOGIN, clusterService, getOrigin(), Origin.REST);
    TransportAddress remoteAddress = getRemoteAddress();
    msg.addRemoteAddress(remoteAddress);
    if(request != null && logRequestBody && request.hasContentOrSourceParam()) {
        msg.addTupleToRequestBody(request.contentOrSourceParam());
    }

    if(request != null) {
        msg.addPath(request.path());
        msg.addRestHeaders(request.getHeaders(), excludeSensitiveHeaders);
        msg.addRestParams(request.params());
    }

    msg.addInitiatingUser(initiatingUser);
    msg.addEffectiveUser(effectiveUser);
    msg.addIsAdminDn(securityadmin);

    save(msg);
}
 
Example 10
@Override
public void logSucceededLogin(String effectiveUser, boolean securityadmin, String initiatingUser, RestRequest request) {

    if(!checkRestFilter(Category.AUTHENTICATED, effectiveUser, request)) {
        return;
    }

    AuditMessage msg = new AuditMessage(Category.AUTHENTICATED, clusterService, getOrigin(), Origin.REST);
    TransportAddress remoteAddress = getRemoteAddress();
    msg.addRemoteAddress(remoteAddress);
    if(request != null && logRequestBody && request.hasContentOrSourceParam()) {
       msg.addTupleToRequestBody(request.contentOrSourceParam());
    }

    if(request != null) {
        msg.addPath(request.path());
        msg.addRestHeaders(request.getHeaders(), excludeSensitiveHeaders);
        msg.addRestParams(request.params());
    }

    msg.addInitiatingUser(initiatingUser);
    msg.addEffectiveUser(effectiveUser);
    msg.addIsAdminDn(securityadmin);
    save(msg);
}
 
Example 11
@Override
public void logSSLException(RestRequest request, Throwable t) {

    if(!checkRestFilter(Category.SSL_EXCEPTION, getUser(), request)) {
        return;
    }

    AuditMessage msg = new AuditMessage(Category.SSL_EXCEPTION, clusterService, Origin.REST, Origin.REST);

    TransportAddress remoteAddress = getRemoteAddress();
    msg.addRemoteAddress(remoteAddress);
    if(request != null && logRequestBody && request.hasContentOrSourceParam()) {
        msg.addTupleToRequestBody(request.contentOrSourceParam());
    }

    if(request != null) {
        msg.addPath(request.path());
        msg.addRestHeaders(request.getHeaders(), excludeSensitiveHeaders);
        msg.addRestParams(request.params());
    }
    msg.addException(t);
    msg.addEffectiveUser(getUser());
    save(msg);
}
 
Example 12
@Test
public void wrongCertTest() throws Exception {
    mockSamlIdpServer.setSignResponses(true);
    mockSamlIdpServer.loadSigningKeys("saml/kirk-keystore.jks", "kirk");
    mockSamlIdpServer.setAuthenticateUser("horst");
    mockSamlIdpServer.setEndpointQueryString(null);

    Settings settings = Settings.builder().put("idp.metadata_url", mockSamlIdpServer.getMetadataUri())
            .put("kibana_url", "http://wherever").put("idp.entity_id", mockSamlIdpServer.getIdpEntityId())
            .put("exchange_key", "abc").put("roles_key", "roles").put("path.home", ".").build();

    HTTPSamlAuthenticator samlAuthenticator = new HTTPSamlAuthenticator(settings, null);

    AuthenticateHeaders authenticateHeaders = getAutenticateHeaders(samlAuthenticator);

    mockSamlIdpServer.loadSigningKeys("saml/spock-keystore.jks", "spock");

    String encodedSamlResponse = mockSamlIdpServer.handleSsoGetRequestURI(authenticateHeaders.location);

    RestRequest tokenRestRequest = buildTokenExchangeRestRequest(encodedSamlResponse, authenticateHeaders);
    TestRestChannel tokenRestChannel = new TestRestChannel(tokenRestRequest);

    samlAuthenticator.reRequestAuthentication(tokenRestChannel, null);

    Assert.assertEquals(401, tokenRestChannel.response.status().getStatus());
}
 
Example 13
Source Project: Elasticsearch   Source File: RestTermVectorsAction.java    License: Apache License 2.0 6 votes vote down vote up
static public void readURIParameters(TermVectorsRequest termVectorsRequest, RestRequest request) {
    String fields = request.param("fields");
    addFieldStringsFromParameter(termVectorsRequest, fields);
    termVectorsRequest.offsets(request.paramAsBoolean("offsets", termVectorsRequest.offsets()));
    termVectorsRequest.positions(request.paramAsBoolean("positions", termVectorsRequest.positions()));
    termVectorsRequest.payloads(request.paramAsBoolean("payloads", termVectorsRequest.payloads()));
    termVectorsRequest.routing(request.param("routing"));
    termVectorsRequest.realtime(request.paramAsBoolean("realtime", null));
    termVectorsRequest.version(RestActions.parseVersion(request, termVectorsRequest.version()));
    termVectorsRequest.versionType(VersionType.fromString(request.param("version_type"), termVectorsRequest.versionType()));
    termVectorsRequest.parent(request.param("parent"));
    termVectorsRequest.preference(request.param("preference"));
    termVectorsRequest.termStatistics(request.paramAsBoolean("termStatistics", termVectorsRequest.termStatistics()));
    termVectorsRequest.termStatistics(request.paramAsBoolean("term_statistics", termVectorsRequest.termStatistics()));
    termVectorsRequest.fieldStatistics(request.paramAsBoolean("fieldStatistics", termVectorsRequest.fieldStatistics()));
    termVectorsRequest.fieldStatistics(request.paramAsBoolean("field_statistics", termVectorsRequest.fieldStatistics()));
    termVectorsRequest.dfs(request.paramAsBoolean("dfs", termVectorsRequest.dfs()));
}
 
Example 14
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 15
Source Project: elasticsearch-dataformat   Source File: RestDataAction.java    License: Apache License 2.0 5 votes vote down vote up
public RestChannelConsumer prepareRequest(final RestRequest request,
        final NodeClient client) throws IOException {
    SearchRequest searchRequest = new SearchRequest();
    request.withContentOrSourceParamParserOrNull(
            parser -> RestSearchAction.parseSearchRequest(searchRequest,
                    request, parser,
                    size -> searchRequest.source().size(size)));

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

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

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

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

    return channel -> client.search(searchRequest, new SearchResponseListener(
            channel, file, limitBytes, dataContent));
}
 
Example 16
@SuppressWarnings("unchecked")
  protected String[] extractRoles(final Claims claims, final RestRequest request) {
  	// no roles key specified
  	if(rolesKey == null) {
  		return new String[0];
  	}
// try to get roles from claims, first as Object to avoid having to catch the ExpectedTypeException
  	final Object rolesObject = claims.get(rolesKey, Object.class);
  	if(rolesObject == null) {
  		log.warn("Failed to get roles from JWT claims with roles_key '{}'. Check if this key is correct and available in the JWT payload.", rolesKey);
  		return new String[0];
  	}

  	String[] roles = String.valueOf(rolesObject).split(",");

  	// We expect a String or Collection. If we find something else, convert to String but issue a warning
  	if (!(rolesObject instanceof String) && !(rolesObject instanceof Collection<?>)) {
  		log.warn("Expected type String or Collection for roles in the JWT for roles_key {}, but value was '{}' ({}). Will convert this value to String.", rolesKey, rolesObject, rolesObject.getClass());
} else if (rolesObject instanceof Collection<?>) {
    roles = ((Collection<String>) rolesObject).toArray(new String[0]);
}

  	for (int i = 0; i < roles.length; i++) {
  	    roles[i] = roles[i].trim();
  	}

  	return roles;
  }
 
Example 17
private AnomalyDetectorExecutionInput getAnomalyDetectorExecutionInput(RestRequest request) throws IOException {
    String detectorId = null;
    if (request.hasParam(DETECTOR_ID)) {
        detectorId = request.param(DETECTOR_ID);
    }

    XContentParser parser = request.contentParser();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
    AnomalyDetectorExecutionInput input = AnomalyDetectorExecutionInput.parse(parser, detectorId);
    if (detectorId != null) {
        input.setDetectorId(detectorId);
    }
    return input;
}
 
Example 18
public String getBearerToken(RestRequest request) {
    String token = request.header(X_FORWARDED_ACCESS_TOKEN);
    if(token == null) {
        if (request.header(AUTHORIZATION_HEADER) != null) {
            final String[] auth = StringUtils.defaultIfEmpty(request.header(AUTHORIZATION_HEADER), "").split(" ");
            if (auth.length >= 2 && "Bearer".equals(auth[0])) {
                token = auth[1];
            }
        }
    }
    return  StringUtils.defaultIfEmpty(token, "");
}
 
Example 19
private BytesReference getContent(final RestRequest request, final OpenshiftRequestContext context) {
    String content = request.content().utf8ToString();
    if(OpenshiftRequestContext.EMPTY != context && content.contains("_index\":\"" + defaultKibanaIndex)) {
        LOGGER.debug("Replacing the content that references the default kibana index");
        String replaced = content.replaceAll("_index\":\"" + defaultKibanaIndex + "\"", "_index\":\"" + context.getKibanaIndex() + "\"");
        return new BytesArray(replaced);
    }
    return request.content();
}
 
Example 20
@Override
public AuthCredentials extractCredentials(RestRequest request, ThreadContext context) throws ElasticsearchSecurityException {
    final String authorizationHeader = request.header("Authorization");
    if (authorizationHeader != null) {
        if (authorizationHeader.trim().toLowerCase().startsWith("basic ")) {
            final String decoded = new String(DatatypeConverter.parseBase64Binary(authorizationHeader.split(" ")[1]),
                    StandardCharsets.UTF_8);

            //username:password
            //Assume password is all chars from the last : to the end
            //this is the only way to send service accounts
           
            final int delimiter = decoded.lastIndexOf(':');

            String username = null;
            String password = null;

            if (delimiter > 0) {
                username = decoded.substring(0, delimiter);
                
                if(decoded.length() - 1 != delimiter) {
                    password = decoded.substring(delimiter + 1).trim();
                }
            }
            if (username != null && StringUtils.isNotEmpty(password)) {
                return new AuthCredentials(username, password.getBytes(StandardCharsets.UTF_8)).markComplete();
            }
        }
    }
    return null;
}
 
Example 21
public RolesMappingValidator(final RestRequest request, final BytesReference ref, final Settings esSettings, Object... param) {
	super(request, ref, esSettings, param);
	this.payloadMandatory = true;
	allowedKeys.put("backend_roles", DataType.ARRAY);
	allowedKeys.put("and_backend_roles", DataType.ARRAY);
	allowedKeys.put("hosts", DataType.ARRAY);
	allowedKeys.put("users", DataType.ARRAY);
	allowedKeys.put("description", DataType.STRING);

	mandatoryOrKeys.add("backend_roles");
	mandatoryOrKeys.add("and_backend_roles");
	mandatoryOrKeys.add("hosts");
	mandatoryOrKeys.add("users");
}
 
Example 22
RestChannelConsumer delete(NodeClient client, String type, String indexName, RestRequest request) {
    assert SUPPORTED_TYPES.contains(type);
    String name = request.param("name");
    String id = generateId(type, name);
    String routing = request.param("routing");
    return (channel) ->  {
        RestStatusToXContentListener<DeleteResponse> restR = new RestStatusToXContentListener<>(channel, (r) -> r.getLocation(routing));
        client.prepareDelete(indexName, ES_TYPE, id)
                .setRouting(routing)
                .execute(ActionListener.wrap((deleteResponse) -> {
                        // wrap the response so we can send another request to clear the cache
                        // usually we send only one transport request from the rest layer
                        // it's still unclear which direction we should take (thick or thin REST layer?)
                        ClearCachesAction.ClearCachesNodesRequest clearCache = new ClearCachesAction.ClearCachesNodesRequest();
                        switch (type) {
                        case StoredFeature.TYPE:
                            clearCache.clearFeature(indexName, name);
                            break;
                        case StoredFeatureSet.TYPE:
                            clearCache.clearFeatureSet(indexName, name);
                            break;
                        case StoredLtrModel.TYPE:
                            clearCache.clearModel(indexName, name);
                            break;
                        }
                        client.execute(ClearCachesAction.INSTANCE, clearCache, ActionListener.wrap(
                                (r) -> restR.onResponse(deleteResponse),
                                // Is it good to fail the whole request if cache invalidation failed?
                                restR::onFailure
                        ));
                    },
                    restR::onFailure
                ));
    };
}
 
Example 23
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (!EnabledSetting.isADPluginEnabled()) {
        throw new IllegalStateException(CommonErrorMessages.DISABLED_ERR_MSG);
    }

    String detectorId = request.param(DETECTOR_ID, AnomalyDetector.NO_ID);
    logger.info("AnomalyDetector {} action for detectorId {}", request.method(), detectorId);

    XContentParser parser = request.contentParser();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
    // TODO: check detection interval < modelTTL
    AnomalyDetector detector = AnomalyDetector.parse(parser, detectorId, null, detectionInterval, detectionWindowDelay);

    long seqNo = request.paramAsLong(IF_SEQ_NO, SequenceNumbers.UNASSIGNED_SEQ_NO);
    long primaryTerm = request.paramAsLong(IF_PRIMARY_TERM, SequenceNumbers.UNASSIGNED_PRIMARY_TERM);
    WriteRequest.RefreshPolicy refreshPolicy = request.hasParam(REFRESH)
        ? WriteRequest.RefreshPolicy.parse(request.param(REFRESH))
        : WriteRequest.RefreshPolicy.IMMEDIATE;

    return channel -> new IndexAnomalyDetectorActionHandler(
        settings,
        clusterService,
        client,
        channel,
        anomalyDetectionIndices,
        detectorId,
        seqNo,
        primaryTerm,
        refreshPolicy,
        detector,
        requestTimeout,
        maxAnomalyDetectors,
        maxAnomalyFeatures
    ).start();
}
 
Example 24
Source Project: elasticsearch-auth   Source File: ReloadRestAction.java    License: Apache License 2.0 5 votes vote down vote up
@Inject
public ReloadRestAction(final Settings settings, final Client client,
        final RestController restController, final AuthService authService) {
    super(settings, restController, client);
    this.authService = authService;

    restController.registerHandler(RestRequest.Method.POST,
            "/_auth/reload", this);
}
 
Example 25
@Override
protected SwaggerModel handleRequest(RestRequest request, Client client, RoutesProvider routesProvider) throws Exception {
    SwaggerProvider swaggerProvider = new SwaggerProvider(
        routesProvider.getInfo(),
        routesProvider.getRoutes()
    );

    return swaggerProvider.getApiDeclaration(request.param("resource"));
}
 
Example 26
private void handlePatch(RestChannel channel, final RestRequest request, final Client client)
        throws IOException  {
    if (request.getXContentType() != XContentType.JSON) {
        badRequestResponse(channel, "PATCH accepts only application/json");
        return;
    }

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

    JsonNode jsonPatch;

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

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

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

    ObjectNode existingAsObjectNode = (ObjectNode) existingAsJsonNode;

    if (Strings.isNullOrEmpty(name)) {
        handleBulkPatch(channel, request, client, existingConfiguration, existingAsObjectNode, jsonPatch);
    } else {
        handleSinglePatch(channel, request, client, name, existingConfiguration, existingAsObjectNode, jsonPatch);
    }
}
 
Example 27
@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 28
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    String indexName = indexName(request);
    if (request.method() == RestRequest.Method.DELETE) {
        return delete(client, type, indexName, request);
    } else if (request.method() == RestRequest.Method.HEAD || request.method() == RestRequest.Method.GET) {
        return get(client, type, indexName, request);
    } else {
        return addOrUpdate(client, type, indexName, request);
    }
}
 
Example 29
protected void handleApiRequest(final RestChannel channel, final RestRequest request, final Client client) throws IOException {

		try {
			// validate additional settings, if any
			AbstractConfigurationValidator validator = getValidator(request, request.content());
			if (!validator.validate()) {
				request.params().clear();
				badRequestResponse(channel, validator);
				return;
			}
			switch (request.method()) {
				case DELETE:
					handleDelete(channel,request, client, validator.getContentAsNode()); break;
				case POST:
					handlePost(channel,request, client, validator.getContentAsNode());break;
				case PUT:
					handlePut(channel,request, client, validator.getContentAsNode());break;
				case GET:
					handleGet(channel,request, client, validator.getContentAsNode());break;
				default:
					throw new IllegalArgumentException(request.method() + " not supported");
			}
		} catch (JsonMappingException jme) {
			throw jme;
			//TODO strip source
			//if(jme.getLocation() == null || jme.getLocation().getSourceRef() == null) {
			//    throw jme;
			//} else throw new JsonMappingException(null, jme.getMessage());
		}
	}
 
Example 30
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.");
	}
}