org.elasticsearch.rest.RestRequest Java Examples
The following examples show how to use
org.elasticsearch.rest.RestRequest.
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: RestSnapshotAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
@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 #2
Source File: RestCountAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
@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 #3
Source File: AuthTokenProcessorHandler.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
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 #4
Source File: TasteActionRestAction.java From elasticsearch-taste with Apache License 2.0 | 6 votes |
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 #5
Source File: ValidatingDispatcher.java From deprecated-security-ssl with Apache License 2.0 | 6 votes |
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 #6
Source File: InternalUsersApiAction.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@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 #7
Source File: RestTermVectorsAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
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 #8
Source File: HTTPSamlAuthenticatorTest.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@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 #9
Source File: ReindexRestAction.java From elasticsearch-reindexing with Apache License 2.0 | 6 votes |
@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 #10
Source File: KerberosAuthenticationFailureHandler.java From elasticsearch-shield-kerberos-realm with Apache License 2.0 | 6 votes |
@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 #11
Source File: AbstractAuditLog.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@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
Source File: ResponseUtil.java From elasticsearch-auth with Apache License 2.0 | 6 votes |
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 #13
Source File: AbstractAuditLog.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@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 #14
Source File: AbstractAuditLog.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@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 #15
Source File: RestISBNFormatterAction.java From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 | 5 votes |
@Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { final String value = request.param("value"); final ISBNFormatRequest isbnFormatRequest = new ISBNFormatRequest().setValue(value); return channel -> client.execute(ISBNFormatAction.INSTANCE, isbnFormatRequest, new RestStatusToXContentListener<>(channel)); }
Example #16
Source File: RestSimpleFeatureStore.java From elasticsearch-learning-to-rank with Apache License 2.0 | 5 votes |
@Override public List<Route> routes() { return unmodifiableList(asList( new Route(RestRequest.Method.PUT, "/_ltr/{store}/_" + this.type + "/{name}"), new Route(RestRequest.Method.PUT, "/_ltr/_" + this.type + "/{name}"), new Route(RestRequest.Method.POST, "/_ltr/{store}/_" + this.type + "/{name}"), new Route(RestRequest.Method.POST, "/_ltr/_" + this.type + "/{name}"), new Route(RestRequest.Method.DELETE, "/_ltr/{store}/_" + this.type + "/{name}"), new Route(RestRequest.Method.DELETE, "/_ltr/_" + this.type + "/{name}"), new Route(RestRequest.Method.GET, "/_ltr/{store}/_" + this.type + "/{name}"), new Route(RestRequest.Method.GET, "/_ltr/_" + this.type + "/{name}"), new Route(RestRequest.Method.HEAD, "/_ltr/{store}/_" + this.type + "/{name}"), new Route(RestRequest.Method.HEAD, "/_ltr/_" + this.type + "/{name}") )); }
Example #17
Source File: RestHandlerUtils.java From anomaly-detection with Apache License 2.0 | 5 votes |
/** * Checks to see if the request came from Kibana, if so we want to return the UI Metadata from the document. * If the request came from the client then we exclude the UI Metadata from the search result. * * @param request rest request * @return instance of {@link org.elasticsearch.search.fetch.subphase.FetchSourceContext} */ public static FetchSourceContext getSourceContext(RestRequest request) { String userAgent = Strings.coalesceToEmpty(request.header("User-Agent")); if (!userAgent.contains(KIBANA_USER_AGENT)) { return new FetchSourceContext(true, Strings.EMPTY_ARRAY, UI_METADATA_EXCLUDE); } else { return null; } }
Example #18
Source File: RestIndexAnomalyDetectorAction.java From anomaly-detection with Apache License 2.0 | 5 votes |
@Override public List<Route> routes() { return ImmutableList .of( // Create new Route(RestRequest.Method.POST, AnomalyDetectorPlugin.AD_BASE_DETECTORS_URI), // update new Route( RestRequest.Method.PUT, String.format(Locale.ROOT, "%s/{%s}", AnomalyDetectorPlugin.AD_BASE_DETECTORS_URI, DETECTOR_ID) ) ); }
Example #19
Source File: RestCountAction.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override protected Table getTableWithHeader(final RestRequest request) { Table table = new Table(); table.startHeaders(); table.addCell("epoch", "alias:t,time;desc:seconds since 1970-01-01 00:00:00, that the count was executed"); table.addCell("timestamp", "alias:ts,hms;desc:time that the count was executed"); table.addCell("count", "alias:dc,docs.count,docsCount;desc:the document count"); table.endHeaders(); return table; }
Example #20
Source File: RestSimpleFeatureStore.java From elasticsearch-learning-to-rank with Apache License 2.0 | 5 votes |
@Override public List<Route> routes() { return unmodifiableList(asList( new Route(RestRequest.Method.PUT, "/_ltr/{store}"), new Route(RestRequest.Method.PUT, "/_ltr"), new Route(RestRequest.Method.POST, "/_ltr/{store}"), new Route(RestRequest.Method.POST, "/_ltr"), new Route(RestRequest.Method.DELETE, "/_ltr/{store}"), new Route(RestRequest.Method.DELETE, "/_ltr"), new Route(RestRequest.Method.GET, "/_ltr"), new Route(RestRequest.Method.GET, "/_ltr/{store}") )); }
Example #21
Source File: AbstractApiAction.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
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 #22
Source File: OpenShiftTokenAuthenticationTest.java From openshift-elasticsearch-plugin with Apache License 2.0 | 5 votes |
@Test public void testExtractCredentials() throws Exception { when(contextFactory.create(any(RestRequest.class))).thenReturn(context); when(apiService.localSubjectAccessReview(anyString(), anyString(), anyString(), anyString(), anyString(), eq(ArrayUtils.EMPTY_STRING_ARRAY))) .thenReturn(true); AuthCredentials creds = backend.extractCredentials(request, threadContext); assertEquals(username, creds.getUsername()); assertEquals(context, threadContext.getTransient(ConfigurationSettings.OPENSHIFT_REQUEST_CONTEXT)); assertTrue(creds.isComplete()); }
Example #23
Source File: HTTPJwtAuthenticator.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
@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 #24
Source File: RestSimpleFeatureStore.java From elasticsearch-learning-to-rank with Apache License 2.0 | 5 votes |
@Override public List<Route> routes() { return unmodifiableList(asList( new Route(RestRequest.Method.GET, "/_ltr/{store}/_" + type), new Route(RestRequest.Method.GET, "/_ltr/_" + type) )); }
Example #25
Source File: KerberosAuthenticationFailureHandler.java From elasticsearch-shield-kerberos-realm with Apache License 2.0 | 5 votes |
@Override public ElasticsearchSecurityException missingToken(final RestRequest request) { final ElasticsearchSecurityException e = super.missingToken(request); e.addHeader(KrbConstants.WWW_AUTHENTICATE, KrbConstants.NEGOTIATE); if (logger.isDebugEnabled()) { logger.debug("missing token for rest request"); } return e; }
Example #26
Source File: RestCoordinateMultiSearchAction.java From siren-join with GNU Affero General Public License v3.0 | 5 votes |
@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 #27
Source File: FileAuthenticationBackendTest.java From openshift-elasticsearch-plugin with Apache License 2.0 | 5 votes |
@Test public void testExtractCredentialsWithAuthHeaderAndPassword() { RestRequest request = givenRequestWithAuth("Basic Zm9vOmJhcgo="); //Basic foo:bar AuthCredentials exp = new AuthCredentials("foo","bar".getBytes()); AuthCredentials act = auth.extractCredentials(request, context); assertEquals("Exp. the AuthCredentials to match", exp, act); }
Example #28
Source File: RequestUtils.java From openshift-elasticsearch-plugin with Apache License 2.0 | 5 votes |
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 #29
Source File: AbstractApiAction.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
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
Source File: RestDataAction.java From elasticsearch-dataformat with Apache License 2.0 | 5 votes |
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)); }