Problems Creating New Initiative with Rally JAVA Rest API 2.0 - java

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

Related

Volley JSON Object Request for POST-ing an array, having a (string) tag and a JSON object

After looking at many examples available on Stack Overflow, I still haven't been able to figure out how to make it work out in my case yet. So, could you please provide me with some guidelines wherever possible? Specifically, I have already built a JSON array containing a tag and a JSON object, which should look like below when being posted (including the square brackets "[]"):
[
"location",
{
"coordinateA":12.45817,
"coordinateB":23.9195856
}
]
The corresponding JAVA code is as follows:
JSONObject CoordinatesFinalObj = new JSONObject();
JSONObject Location = new JSONObject();
try {
CoordinatesFinalObj.put("location-one", LocationOne);
} catch (JSONException e) {
e.printStackTrace();
}
try {
LocationOne.put("coordinateA", 12.45817);
LocationOne.put("coordinateB", 23.9195856);
} catch (JSONException e) {
e.printStackTrace();
}
When I POST-ed such the JSON array to our server using Volley JSON Object Request, it always returned the error 417. I actually did something similar by posting a Python array with a tag and a JSON object inside without any problems. And there are no special requirements of the http request header as imposed by our server.
JsonObjectRequest CoordinatesJsonObjectReq = new JsonObjectRequest(Request.Method.POST,
url, **CoordinatesFinalObj**, new Response.Listener<JSONObject>()...).
So, my question here is: Is Volley JSON Object Request a good fit for this purpose or I shall simply switch to use a string-based POST method (e.g. HttpURLConnection though it is a deprecated module). I am very confused why it is not working here...

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();
}

How to get the actual values from OutboundJaxrsResponse in java?

In my RestClient returns below response to my jersey service.
OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
The above one returns the list. How can I get the list and how to validate each record id? If id is not available in my database need to store missing id. how to handle this?
Below is my code;
public Response list() throws Exception {
Response response = null;
RestClient client = service.getClient();
try {
response = client.invokeServiceGETForArray(serviceType, "/test/name", null, null);
JsonArray responseLst = (JsonArray) response.readEntity(JsonArrayBuilder.class);
System.out.println("Response Array List :: " + responseLst);
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getLocalizedMessage()).build();
}
return response;
}
above code snippet returns the below response :
OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
I am trying to read response using below code :
JsonArray responseLst = (JsonArray) response.readEntity(JsonArrayBuilder.class);
But it is throwing below exception.
java.lang.IllegalStateException: Method not supported on an outbound message.
at org.glassfish.jersey.message.internal.OutboundJaxrsResponse.readEntity(OutboundJaxrsResponse.java:145)
Thanks in advance,

How to connect to ElasticSearch with Java transport client?

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.

Unable to add product details while creating new quote

I am developing an android app to create a new Quote in vTiger(ver 5.4) CRM server.
I was able to generate the new quote but the product_id and quantity that I sent for addition in quote details were not added in it. The other details are being shown in the new quote except the list of products, their quantities and pricing.
I have also studied the vTiger webservices tutorial but it was not helpful in this case.
I found an accepted answer of similar question but it is in php not in Android/JAVA.
This is how I am sending the details required to create a new quote in vTiger server.:-
try {
objectJson.put("subject", subject);
objectJson.put("account_id", accountId);
objectJson.put("bill_street", address);
objectJson.put("assigned_user_id", "19x1");
objectJson.put("conversion_rate", "1.000");
objectJson.put("currency_id", "21x1");
objectJson.put("hdnTaxType", "group");
objectJson.put("productid", productId);
objectJson.put("quantity", quantity);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String data = null;
try {
data = URLEncoder.encode("sessionName", "UTF-8")
+ "=" + URLEncoder.encode(sessionId, "UTF-8");
data += "&" + URLEncoder.encode("element", "UTF-8") + "="
+ URLEncoder.encode(objectJson.toString(), "ISO-8859-1");
data += "&" + URLEncoder.encode("elementType", "UTF-8") + "="
+ URLEncoder.encode(moduleName, "UTF-8"); //moduleName='Quotes'
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://vtiger_url/webservice.php?operation=create");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
}
catch(Exception ex)
{
}
The above code helps me to generate the quote without product details.
After studying the above mentioned php answer, I changed the URL that I was using in my code to this:- http://vtiger_url/webservice.php?total=23000&operation=create. This helped me to add the total amount to the newly created quote but I wasn't successful to add rest of the details using this method.
The answer you have found seems to be suitable, even if it's a php solution. The problem you descirbed:
I have tried this too but unfortunately I am not able to access Inventoryproductrel table.
maybe already indicates a lack of proper authentication or missing privileges. So my suggestion is to
Find out why you can't access the table Inventoryproductrel. Try to access that table using your authentication privileges (sessionID), examine the response for any hints and try to solve the table isn't accessible issue.
Finally follow the suggestions from this answer.
Just another hint. If you can successfully access that table via you web browser, than I would sniff the request and have a look at the http parameters and their values. Based on those findings you can modify your request.
Always consider, the web browser can only do the same as you android application.
These lines were added in existing code:-
JSONArray pdoInformation = new JSONArray();
try{
// Added these lines in try block to send product details
for(int i=0; i<productIds.size(); i++) {
JSONObject obj = new JSONObject();
obj.put("productid", productIds.get(i) );
obj.put("qty", quantities.get(i));
obj.put("listprice", listprices.get(i));
pdoInformation.put(obj);
}
objectJson.put("pdoInformation", pdoInformation);
}
Here product details were needed to be sent in a JSONArray with name as "pdoInformation".
for loop is used to send multiple product details.
Here productIds, quantities and listprices are three mandatory product details stored as ArrayList.
Why don't you use the web service to create products as well? That should be supported as per the documentation.
Once you create the products and get their ids, you can create a quote object that includes these ids. The objects and their fields are not very well documented for the rest APIs, so you could use the query/describe APIs to get as much information as possible about what data needs to be supplied for creating the different objects.
From the description of the Quotes module, you would need to include item_details which will contain the product and quantity information. The exact field name and format can be obtained by the describe API as described in the web service documentation
To get a description of the vTiger objects
String modeleName = "Quotes"; //Use Products if you want a description of the Products module
String data = null;
try {
data = URLEncoder.encode("sessionName", "UTF-8")
+ "=" + URLEncoder.encode(sessionId, "UTF-8");
data += "&" + URLEncoder.encode("elementType", "UTF-8") + "="
+ URLEncoder.encode(moduleName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
System.out.println(data);
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://vtiger_url/webservice.php?operation=describeobject");
// Send GET data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
} catch(Exception ex) {
}
Note that it's pretty much the same as what you are doing, only the url & parameters are different, and the request type is GET instead of POST
To create a product, you would follow the same procedure as you did for the quote, only the url and parameters would be different
#help as far i understand your question is how to send JsonObject with data to specified Server is that correct ? if it is the correct then i suggest you to use Volley library for networking and here are many examples that may useful to you .http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/ and http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
Just go through it. It provides easiest way to perform networking operations and also cancellation of request is also possible with this library.
Sample Code:
final String URL = "SERVER_URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
Using this code you can send your data to your server and at server side you can use php code to receive this jsondata and parse it.
Thanks.

Categories

Resources