Using ES's UpdateByQueryRequestBuilder with Rest High Level Client - java

In Elasticsearch v5.5, we have used Transport Client when defining
UpdateByQueryRequestBuilder and it worked fine:
UpdateByQyeryRequestBuilder updateByQuery = UpdateByQueryAction.INSTANCE
.newRequestBuilder(transportClient);
Since we're upgrading to use RestHighLevelClient, the above builder no longer works and it has this as error: "The method newRequestBuilder(ElasticsearchClient) in the type UpdateByQueryAction is not applicable for the arguments (RestHighLevelClient)".
Does anyone know if i can just simply cast it like below:
UpdateByQyeryRequestBuilder updateByQuery = UpdateByQueryAction.INSTANCE
.newRequestBuilder((ElasticsearchClient) restHighLevelClient);
or there should be some other way to do it? Thanks

From the documentation. It looks like you should prepare request directly:
UpdateByQueryRequest request = new UpdateByQueryRequest("source1", "source2");
request.set...
and later execute the request:
BulkByScrollResponse bulkResponse = client.updateByQuery(request, RequestOptions.DEFAULT);
I think UpdateByQyeryRequestBuilder is a class specific for the TransportClient only.

Related

Issue Sending Request from gRPC Java Client

I have this code:
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090).usePlaintext().build();
SentenceClassificationServiceGrpc.SentenceClassificationServiceBlockingStub SentenceClassificationStub = SentenceClassificationServiceGrpc.newBlockingStub(channel);
SentenceClassificationRequest request = SentenceClassificationRequest.newBuilder().setDocument("hey").setThreshold(1);
SentenceClassificationResponse response = SentenceClassificationStub.classification(request);
and I keep on getting this error:
java: incompatible types: com.application.SentenceClassificationRequest.Builder cannot be converted to com.application.SentenceClassificationRequest
I've generated the gRPC Java files using the Maven plugin. After looking at multiple examples I'm not sure what my issue is.
Solution
You forgot to build your SentenceClassificationRequest, currently you're assigning your SentenceClassificationRequest.Builder to SentenceClassificationRequest
Just add .build() to the end of the builder
SentenceClassificationRequest request = SentenceClassificationRequest.newBuilder().setDocument("hey").setThreshold(1).build();

How to add a body to a GET request in JAX-RS

I'm trying to consume a REST API that requires a body with a GET request. But as a GET usually doesn't have a body, I can't find a way to attach a body in my request. I am also building the REST API, but the professor won't allow us to change the method to POST (he gave us a list of the endpoints we are to create, no more, no less).
I'm trying to do it like this:
Response r = target.request().method(method, Entity.text(body));
Where I set the method to GET and the body to my get body. However, using this approach I get an exception:
javax.ws.rs.ProcessingException: RESTEASY004565: A GET request cannot have a body.
Is there any way to do this with JAX-RS? We learned to use JAX-RS so I would prefer a solution using this, as I'm not sure my professor would allow us to use any other REST client. I'm currently using RESTEasy, provided by the WildFly server.
(This is not a duplicate of HTTP GET with request body because I'm asking on how to create a GET request with body in JAX-RS, not if it should be done.)
This depends on what is your JAX-RS implementation. This check can be disabled in Jersey 2.25 using SUPPRESS_HTTP_COMPLIANCE_VALIDATION property:
ClientConfig config = new ClientConfig();
config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
JerseyClient client = JerseyClientBuilder.createClient(config);
WebTarget target = client.target(URI.create("https://www.stackoverflow.com"));
Response response = target.request().method("GET", Entity.text("BODY HERE"));
Instead of exception you will get an INFO log
INFO: Detected non-empty entity on a HTTP GET request. The underlying HTTP transport connector may decide to change the request method to POST.
However in RESTEasy 3.5.0.Final there is a hardcoded check in both URLConnectionEngine and ApacheHttpClient4Engine:
if (request.getEntity() != null)
{
if (request.getMethod().equals("GET")) throw new ProcessingException(Messages.MESSAGES.getRequestCannotHaveBody());
You would have to create your own implementation of the ClientHttpEngine to skip this. Then you need to supply it when building the client:
ClientHttpEngine engine = new MyEngine();
ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();

SSLPeerUnverifiedException:"peer not authenticated" while using groovy's RestClient with ignoreSSLIssues()

I am writing an integration test for my Rest end point and I have choosen groovy's RestClient. My rest call is on "HTTPS" and I started facing SSL exceptions.
While digging more into this, I was happy to know about ignoreSSLIssues() method (http://groovy.codehaus.org/modules/http-builder/doc/ssl.html). As this is available in 0.7.1 version of HttpBuilder, I upgraded this jar and some dependent jars as well. So with this in place, as per the doc, i was hoping the below code to work -
def httpBuilder = new HTTPBuilder('baseurl')
httpBuilder.ignoreSSLIssues()
def resp = httpBuilder.get(path : 'restPath')
println resp
But this is still throwing javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated.
Any help on this is appreciated.
Thanks.
Just ran into this issue. You also get this deceptive error if you use an outbound proxy and haven't configured the HTTPBuilder class to use it explicitly.
You need to set the setProxy() method of HTTPBuilder. JVM OPTS such as -Dhttp.proxyHost do not seem to be respected by HTTPBuilder for whatever reason. My version looks something like this:
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.HEAD
def http = new HTTPBuilder( 'https://www.dev.java.net/' )
http.setProxy("my.proxy.com", 8080, "http")
http.ignoreSSLIssues()
def status = http.request( HEAD ) {
response.success = { it.status }
}

Uri not Absolute exception getting while calling Restful Webservice

The below code snippet is using to call my web service using restful API.
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
String uri= "https://127.0.0.1:8443/cas-server-webapp-3.5.0/login";
WebResource resource = client.resource(URLEncoder.encode(uri));
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("username", "suresh");
queryParams.add("password", "suresh");
resource.queryParams(queryParams);
ClientResponse response = resource.type(
"application/x-www-form-urlencoded").get(ClientResponse.class);
String en = response.getEntity(String.class);
System.out.println(en);
And getting this exception while running the above code
com.sun.jersey.api.client.ClientHandlerException: java.lang.IllegalArgumentException: URI is not absolute
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:680)
I googled many articles and did'nt get where i am doing wrong .
Side note :cas-server-webapp-3.5.0 war deployed on my machine in Apache tomacat7
An absolute URI specifies a scheme; a URI that is not absolute is said to be relative.
http://docs.oracle.com/javase/8/docs/api/java/net/URI.html
So, perhaps your URLEncoder isn't working as you're expecting (the https bit)?
URLEncoder.encode(uri)
For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: #Value annotation.
The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.
Maybe the problem only in your IDE encoding settings. Try to set UTF-8 everywhere:
In an API Key Authorization Scenario...
You may be performing the 2nd REST call after getting an AUTH_TOKEN and ENDPOINT_URL from the first REST call.
Check your concatenation of "<ENDPOINT_URL> + <API_METHOD_URI>", you may be sending only the API_METHOD_URI.
This happened to me using the Streamsets integration platform trying to connect to Oracle's Responsys API.
For me, I was getting this error, when configuation in yaml files, which composed my URL was changed. oops,

Put request parameters not getting set

This may be standard stuff but unable to get it wokring.
I'm using org.apache.commons.httpclient.methods for making Http request from my Java code. In one instance I've to make a PUT request and pass some parameters. I'm doing it the following way:
PutMethod putMethod = new PutMethod(url);
putMethod.getParams().setParameter("param1", "param1Value");
putMethod.getParams().setParameter("param2", "param2Value");
httpClient.executeMethod(putMethod);
But at the server, when it tries to read these parameters - it can only get null.
However, When I modify my url as url?param1=param1Value&param2=param2Value it works.
How do I get it working using setParameter method?
To add Query Params to PutMethod, follow this method.
NameValuePair[] putParameters = new NameValuePair[2];
putParameters[0] = new NameValuePair(Param1, value1);
putParameters[1] = new NameValuePair(Param2, value2);
HttpClient client = new HttpClient();
PutMethod putMethod = new PutMethod(url);
putMethod.setQueryString(putParameters);
Then Call,
int response = client.executeMethod(putMethod);
Instead of putMethod.setQueryString(putParameters); you could also use
putMethod.setRequestBody(EncodingUtil.formUrlEncode(putParameters, "UTF-8"));
(This is deprecated)
GetMethod, PostMethod have slight differences when adding Query Params compared to the above code.
For More Code Examples : http://www.massapi.com/class/pu/PutMethod.html
Hope this helps.
your server side code has to support the PUT method
for example if its a Servlet you can include the method
doPUT(); // your put request will be delivered to this method
if you use REST based frameworks such as jersey
you can use
#PUT
Response yourPutMethod(){..}

Categories