How to connect to ElasticSearch with Java transport client? - java

I am following the ElasticSearch documentation on Java Client. I have started ElasticSearch and I can interact with it with the Rest API. I want to use the Java Client and so far I have a main like this:
public class TestElastic {
public static void main(String[] args) {
try{
TransportClient client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
JSONObject place = new JSONObject();
place.put("name", "AAAAA");
IndexResponse response = client.prepareIndex("my_database", "places", "1")
.setSource(place)
.get();
System.out.println(response.toString());
// Index name
String _index = response.getIndex();
System.out.println(_index);
// Type name
String _type = response.getType();
System.out.println(_type);
// Document ID (generated or not)
String _id = response.getId();
System.out.println(_id);
// Version (if it's the first time you index this document, you will get: 1)
long _version = response.getVersion();
System.out.println(_version);
// isCreated() is true if the document is a new one, false if it has been updated
boolean created = response.isCreated();
System.out.println(created);
client.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
In the Java logs I can see that there is a connection with 127.0.0.1:9300. But after the "prepare index" command I do not see any error and nothing is printed(I have some system out commands). In the ElasticSearch logs is also nothing relative. When I create an index with the Rest API I can see this in the logs.

Ok, as #Val mentioned I forgot to print the errors. The problem was that JSONObject is not the format that ElasticSearch wants. Map and HashMap are acceptable.

Related

How to perform system property operations in WildFly via REST?

This documentation states that one can perform certain operations for a WildFly server via REST: https://docs.jboss.org/author/display/WFLY10/The%20HTTP%20management%20API.html
However, there is no example how to add/remove/read a system property. I have no idea how the HTTP body has to look for those calls.
The answer of the following StackOverflow question says that the class SimpleOperation used in the example does not really exist: Wildfly 10 management Rest API
I would like to do the following operations:
/system-property=BLA:remove
/system-property=BLA:add(value="1,2,3,4")
and to read it.
How can I perform these operations via REST with the WildFly HTTP management API? Ideally, I would use a Java API if there was one.
With the org.wildfly.core:wildfly-controller-client API you could do something like this:
try (ModelControllerClient client = ModelControllerClient.Factory.create("localhost", 9990)) {
final ModelNode address = Operations.createAddress("system-property", "test.property");
ModelNode op = Operations.createRemoveOperation(address);
ModelNode result = client.execute(op);
if (!Operations.isSuccessfulOutcome(result)) {
throw new RuntimeException("Failed to remove property: " + Operations.getFailureDescription(result).asString());
}
op = Operations.createAddOperation(address);
op.get("value").set("test-value");
result = client.execute(op);
if (!Operations.isSuccessfulOutcome(result)) {
throw new RuntimeException("Failed to add property: " + Operations.getFailureDescription(result).asString());
}
}
You can use the REST API too, however you'll need to have a way to do digest authentication.
Client client = null;
try {
final JsonObject json = Json.createObjectBuilder()
.add("address", Json.createArrayBuilder()
.add("system-property")
.add("test.property.2"))
.add("operation", "add")
.add("value", "test-value")
.build();
client = ClientBuilder.newClient();
final Response response = client.target("http://localhost:9990/management/")
.request()
.header(HttpHeaders.AUTHORIZATION, "Digest <settings>")
.post(Entity.json(json));
System.out.println(response.getStatusInfo());
} finally {
if (client != null) client.close();
}

Chat history forwardedMessages is empty ArrayList

I am trying to implement a java smack client interacting with Openfire server. I have added the plugin for Monitoring service, also enabled archiving. Now I can see the chat history in the openFire Admin Console. I would like to do the same using Smack. This is the code I have written.
XMPPTCPConnection connection = connectToXMPP(Constants.XMPPADMINUSERNAME, Constants.XMPPADMINPWD ,Constants.XMPPDOMAIN);
MamManager mamManager = MamManager.getInstanceFor(connection);
try {
DataForm form = new DataForm(DataForm.Type.submit);
FormField field = new FormField(FormField.FORM_TYPE);
field.setType(FormField.Type.hidden);
field.addValue(MamElements.NAMESPACE);
form.addField(field);
FormField formField = new FormField("with");
formField.addValue("userlocal1#125.99.44.122");
form.addField(formField);
boolean isSupported = mamManager.isSupported();
// "" empty string for before
RSMSet rsmSet = new RSMSet(maxResults, "", RSMSet.PageDirection.before);
MamManager.MamQueryResult mamQueryResult = mamManager.page(form, rsmSet);
// MamManager.MamQueryResult mamQueryResult1 = mamManager.queryArchive(JidCreate.from("userlocal1#125.99.44.122"));
return mamQueryResult;
} catch (Exception e) {
e.printStackTrace();
}
return null;
Now the problem is the forwardedMessages ArrayList is always null. What am I doing wrong?? isSupported is true and I can see the chathistory on admin console… Please guide…
I notice that you're trying to get the last few archived messages, which makes sense. I'm not sure if your 'before' value should be empty though. For testing purposes, try reversing the page direction, and see if you can get the first/oldest few archived messages.

Creating index using bulk Api java

Can I create a new index using API bulk on ES 2.4?
I start by trying the example in the official documentation that uses the method PrepareIndex, but it does not add a new index.
In the other way when I use Administrative API, it solves the problem, so I can create this index.
public static void main(String[] args) throws IOException
{
XContentBuilder builder = jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject();
TransportClient client = null;
try {
client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
} catch (UnknownHostException e) {
System.out.println("Connection Tcp non valid : machine non reconnu ");
}
BulkRequestBuilder bulkRequest = client.prepareBulk();
bulkRequest.add(client.prepareIndex("flux","flux1","1").setSource(builder));
builder.flush();
client.close();
Your elastic search instance might have a setting that prevents automatic index creation, which means that if you post a document to a non existing index it will not create it. Look for action.auto_create_index property in /etc/elasticsearch/elasticsearch.yml
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-creation

Problems Creating New Initiative with Rally JAVA Rest API 2.0

I am using the following code snippet to try to create an Initiative in Rally (the values I am using for _ref I obtained while debugging).
public void createInitiative() {
CreateRequest request = null;
CreateResponse response = null;
JsonObject jo = new JsonObject();
String wsRef = "/workspace/11785043049";
String prjRef = "/project/11785043139";
jo.addProperty("Workspace", wsRef);
jo.addProperty("Project", prjRef);
jo.addProperty("Name","api_create_initiative_01");
jo.addProperty("Owner","/user/17085226946");
jo.addProperty("_ref", "/portfolioItem/initiative");
jo.addProperty("_type", "portfolioItem/initiative");
request = new CreateRequest("Initiative", jo);
try {
response = api.create(request);
JsonElement je = response.getObject();
System.out.println(je.getAsString());
} catch (IOException e) {
e.printStackTrace();
}
}
The response is :
{"CreateResult": {"_rallyAPIMajor": "2", "_rallyAPIMinor": "0", "Errors": ["Not authorized to perform action: Invalid key"], "Warnings": ["It is no longer necessary to append \".js\" to WSAPI resources."]}}
I have no idea which "key" is invalid.
Also, not sure if I should be using "Initiative" or "PortfolioItem/Initiative" both fail
The security token needed to be append to the url as specified in the docs when you find them.
I had cannibalized code from the rallyapi test program for api setup and the security token was not appending when performing a create. Also my code snippet above had to be changed to create("PortfolioInitiative",jo) and the property "_type" was not needed

WRONG_DOCUMENT_ERR Error after login to sugarCRM from java Axis 1.4

I want to import data from java web application to sugarCRM. I created client stub using AXIS and then I am trying to connect, it seems it is getting connected, since I can get server information. But after login, it gives me error while getting sessionID:
Error is: "faultString: org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it."
Here is my code:
private static final String ENDPOINT_URL = " http://localhost/sugarcrm/service/v3/soap.php";
java.net.URL url = null;
try {
url = new URL(ENDPOINT_URL);
} catch (MalformedURLException e1) {
System.out.println("URL endpoing creation failed. Message: "+e1.getMessage());
e1.printStackTrace();
}
> System.out.println("URL endpoint created successfully!");
Sugarsoap service = new SugarsoapLocator();
SugarsoapPortType port = service.getsugarsoapPort(url);
Get_server_info_result result = port.get_server_info();
System.out.println(result.getGmt_time());
System.out.println(result.getVersion());
//I am getting right answers
User_auth userAuth=new User_auth();
userAuth.setUser_name(USER_NAME);
MessageDigest md =MessageDigest.getInstance("MD5");
String password=convertToHex(md.digest(USER_PASSWORD.getBytes()));
userAuth.setPassword(password);
Name_value nameValueListLogin[] = null;
Entry_value loginResponse = null;
loginResponse=port.login (userAuth, "sugarcrm",nameValueListLogin);
String sessionID = loginResponse.getId(); // <--- Get error on this one
The nameValueListLogin could be be from a different document context (coming from a different source). See if this link helps.
You may need to get more debugging/logging information so we can see what nameValueListLogin consists of and where it is coming from.

Categories

Resources