Using JEST to write to Elasticsearch 7.3 - invalid POST method - java

I've been attempting to write some info to a working elasticsearch 7.3 cluster using the JEST api. Some resources:
here
Have run into this error message:
Incorrect HTTP method for uri [/my_index] and method [POST], allowed: [GET, DELETE, PUT, HEAD]
Im sending the data as follows:
// write directly to elastic
Map<String, Object>infoMap = new LinkedHashMap();
lagInfoMap.put("type", "consumer");
lagInfoMap.put("topicval", topic);
lagInfoMap.put("groupval", group);
lagInfoMap.put("sumval", sumLag);
try {
jestResult = jestClient.execute(new Index.Builder(infoMap).index("my_index").build());
if(!jestResult.isSucceeded()) {
LOGGER.error(jestResult.toString());
}
} catch(IOException ioe) {
LOGGER.error("Unable to write to elastic", ioe);
return false;
}
Seems like it's wanting a PUT request but it's not clear from the docs (or any examples I can find) how to modify the execute method to do so.

Some days ago I also had the same problem and finally gave up the idea of using JEST for elasticsearch 7.3, from their Github page, it doesn't look like their latest release which is 6.3.1 https://github.com/searchbox-io/Jest/releases , isn't compitable with elasticsearch 7.X.
Elasticsearch 7.X uses the PUT HTTP method to index a document, while the earlier version used the POST method, hence you get the below exception.
Incorrect HTTP method for uri [/my_index] and method [POST], allowed:
[GET, DELETE, PUT, HEAD]
I would suggest, you use elasticsearch official high level java client, instead of JEST, this is being developed activity by the elastic, company behind the elasticsearch.

Related

How to list storage classes using Kubernetes client

I am using below line of code to get details about a particular PVC
response = await `serverModule.kubeclient.api.v1.namespaces(ns).persistentvolumeclaims(pvc).get();`
The corresponding API for above call is readNamespacedPersistentVolumeClaim with below format
GET /api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}
Now, I am trying to call readStorageClass using same convention as above
response = await serverModule.kubeclient.apis.storage.k8s.io.v1.storageclasses(sc).get();
As you can see in the link, GET /apis/storage.k8s.io/v1/storageclasses/{name} is the format, I have used above syntax. But for some reason the code fails with error
Exported kubeclient, ready to process requests
TypeError: Cannot read property 'k8s' of undefined
What is the syntax error that I have made. I tried various combinations but none worked.
This issue is listing PersistentVolumeClaim is a part of coreV1Api of kubernetes and listing StorageClass is the part of StorageV1beta1Api. Following it the simplest code for listing storage class using JAVA client:
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: BearerToken
ApiKeyAuth BearerToken = (ApiKeyAuth) defaultClient.getAuthentication("BearerToken");
BearerToken.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//BearerToken.setApiKeyPrefix("Token");
StorageV1beta1Api apiInstance = new StorageV1beta1Api();
try {
V1beta1StorageClassList result = apiInstance.listStorageClass();
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling StorageV1beta1Api#listStorageClass");
e.printStackTrace();
}
Following is the official documentation link for your reference:
https://github.com/kubernetes-client/java/blob/master/kubernetes/docs/StorageV1beta1Api.md#listStorageClass
Hope this helps.
Use client.apis["storage.k8s.io"].v1.storageclasses.get() , Applicable to any api containing dots.
Hope it helps

Deserialize Google Web Kit Response (Java) and Java Servlets

I have a monolithic legacy application that I need to read and submit data to. It's using Google Web Kit and Java Servlets.
I have access to the source code, but I'm new to both Servlets and GWT.
I'm trying to encapsulate a rest client in my project that can communicate with GET/POST rest calls to the legacy server.
I've been able to send a POST request using Postman, and then used Reactive Spring 5.0 framework to sending that request.
When I try to deserialize the response, I'm running into a ton of errors.
How would I deserialize this payload?
7|0|7|http://localhost:8080/testproject/
|29F4EA1240F157649C12466F01F46F60|
com.test.client.GreetingService|greetServer|java.lang.String|
myInput1|myInput2|1|2|3|4|2|5|5|6|7|
I've searched all day, and followed a few blogs like these:
https://docs.google.com/document/d/1eG0YocsYYbNAtivkLtcaiEE5IOF5u4LUol8-LL0TIKU/edit#
https://blog.gdssecurity.com/labs/2009/10/8/gwt-rpc-in-a-nutshell.html
I'm not sure code wise how I can serialize them into my own object for my new service.
static WebClient webClient = WebClient.create();
public static void main(String[] args) {
Mono<String> body = Mono.just("7|0|7|http://localhost:8080/testproject/|29F4EA1240F157649C12466F01F46F60|com.test.client.GreetingService|greetServer|java.lang.String|myInput1|myInput2|1|2|3|4|2|5|5|6|7|");
Mono<String> response = webClient.post()
.uri("http://localhost:8080/testproject/")
.header("Content-Type", "text/x-gwt-rpc;charset=UTF-8")
.header("X-GWT-Module-Base", "http://localhost:8080/testproject/")
.header("X-GWT-Permutation", "29F4EA1240F157649C12466F01F46F60")
.cookie("JSESSIONID", "2BCEBF12GE2C3A0335F5012812A73638")
.body(body, String.class)
.retrieve()
.bodyToMono(String.class);
String unBlocked = response.block();
System.out.println(unBlocked);
//OK[1,1,["java.lang.Integer/3438228391"],0,2]
try {
ServerSerializationStreamReader streamReader = new ServerSerializationStreamReader(
Thread.currentThread().getContextClassLoader(), null);
streamReader.prepareToRead(unBlocked);
System.out.println(streamReader.readObject());
} catch ( Exception e) {
e.printStackTrace();
}
}
Error:
com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException: This application is out of date, please click the refresh button on your browser. ( Malformed or old RPC message received - expecting version between 5 and 7 )
I've tried every version of GWT because of the malformed RCP message.
Also, I tried to stick it into a string, which I'm sure is failing on its own.
You are trying to decode the server response with the code meant decode the client request. At present they use a different format for historical reasons - note how the response starts with "//OK", but the request has the version/flags/stringcount "7|0|7" beginning.
In at least a small part this is because when a client calls a server, it needs to describe what version it is speaking and where the server should find the file listing the set of classes that the client expects are allowed to be serialized. When the server responds, since the client already told it about the typed that can be serialized, it doesn't need to tell the client the same thing again.
Reading the com.google.gwt.user.client.rpc.impl.ClientSerializationStreamReader class and its docs will show the response format and how it can be decoded into objects. There is presently no server-side code that I'm aware of that is intended to do this job, but could probably be written with fairly little difficulty, just some persistence.

Read Body (Payload) of a GET / DELETE in Java play 2.4

I'm using Play 2.4.x framework and I want get the body of a DELETE request. In Play 2.2 this can be simply done using request().body().asJson().toString()
According to the Plat 2.4 migration document, the above method only works for PUT POST and PATCH requests. Not for GET and DELETE. What is the Java code to read the Body of a DELETE request in Play 2.4
In the migration document, they mention that BodyParsers.parse.default has changed its behaviour, but you can still access to the body by specifying an other body parser:
#BodyParser.Of(BodyParser.Json.class)
public Result myAction() {
return ok("Got json: " + request().body().asJson());
}
Note: When using BodyParsers.Json.class, it will automatically verify that the incoming request contains some json and parse it.

Accessing OneNote API from Java

I am interested in writing a Java application that can access my OneNote notebooks via the OneNote API. I am not sure how to gain access to that API from within Java. Can anybody point me to an example of how to get started here? I use Eclipse as my development environment.
This as straightforward process.
The 3 steps would be:
1) create a OneNote application on the OneNote developper's page. More info here https://dev.onedrive.com/app-registration.htm. This is a one time action.
2) your java application should then provide an authentification mechanism and a tolken-refresh mechanism.
See this post for more info on the authentification mechanism part : Getting a OneNote token with Java. This post is about the OAuth 2.0 flow 'Authorization code grant flow'. More info here https://msdn.microsoft.com/en-us/library/hh243647.aspx#flows
3) your java application calls adhoc API Rest methods to retreive the needed informations.
Example to retrieve all your notebooks (using OkHttp for Http requests):
private final static String NOTEBOOKS_ENDPOINT = "https://www.onenote.com/api/v1.0/me/notes/notebooks";
public Notebooks readAllNoteBooks() {
try {
if (client == null)
client = new OkHttpClient();
Request request = createOneNoteRequest(a_valid_tolken, NOTEBOOKS_ENDPOINT);
Response response = client.newCall(request).execute();
JsonObject content = UrlHelper.parseResponse(response);
System.out.println(content);
return Notebooks.build(content.get("value"));
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Request createOneNoteRequest(String mAccessToken, String url) {
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
reqBuilder.header("Authorization", "Bearer " + mAccessToken);
return reqBuilder.build();
}
NoteBooks and NoteBook are 2 tiny classes matching the key attributes from the OneNote objects.
Microsoft has provided REST apis for accessing One note functionalities like creating and accessing notes. See OneNote Rest API reference.
singrass,
In addition to the above replies, the Android OneNote API sample may also help you. There is no OneNote application class that you can create (unless you want to create your own). You simply call the API through the HttpClient. If you are unfamiliar on how to call REST APIs in Java in general, this thread may help you.
-- James

unable to connect to Mailchimp services using java wrapper

I am using Java wrapper of mailchimp API for converting to inline CSS.
I downloaded the java wrapper and tried with method inlineCss();
I register with Mailchimp and got the Api key.
API Key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us1
I am getting the below exception while calling the ping(apiKey) method.
Could you please provide me the solution to resolve this problem.
Exception in thread "main" com.nwire.mailchimp.MailChimpServiceException: Failed to read servers response: api.mailchimp.com
at com.nwire.mailchimp.MailChimpServiceFactory$ClientFactory$1.invoke(MailChimpServiceFactory.java:190)
at $Proxy0.ping(Unknown Source)
at com.nwire.mailchimp.test.InlineTest.initialize(InlineTest.java:44)
at com.nwire.mailchimp.test.InlineTest.run(InlineTest.java:36)
at com.nwire.mailchimp.test.InlineTest.main(InlineTest.java:23)
Below is the code I am using for connecting to Mailchimp.
public void initialize() {
mcServices = MailChimpServiceFactory.getMailChimpServices();
final String ping = mcServices.ping(apiKey);
if (IMailChimpServices.PING_SUCCESS.equals(ping)) {
logger.error("MailChimp connection pinged successfully");
} else {
logger.error("Failed to ping MailChimp, response: " + ping);
}
}
Regards,
Nagesh.
Here is your solution
To support Mailchimp datacenter mapping scheme.
Access the correct datacenter
* http://.api.mailchimp.com/1.2/
* replace with position after dash in Our Api key eg.us1 ,uk2 etc.
Check your Url present in MailChimpServiceFactory class of Java-warapper
by default Java wrapper provides
config.setServerURL(new URL("http://api.mailchimp.com/1.2/"))
changed above url to "http://us1.api.mailchimp.com/1.2/"
for more information visit this link http://www.mailchimp.com/api/1.2/

Categories