How To Use Response value In Another Method - java

I am working on restassured and here is my 2 methods. I want to use the albumId returned from the AlbumList method in the other method
public void AlbumList() {
Response response1 = given().spec(url).queryParam("page", 0).queryParam("size", 100)
.queryParam("sortBy", "createdDate").queryParam("contentType", "album/photo")
.queryParam("sortOrder", "ASC")
.header("Content-type", "application/json")
.header("Accept", "application/json")
.header("X-Auth-Token", payload.userAuth())
.when().get("/album")
.then().assertThat().statusCode(200).extract().response();
Assert.assertEquals(response1.jsonPath().get("[4].label"), "TLOTR");
JsonPath js = new JsonPath(response1.asString());
int count = js.getInt("size()");
// Response check part
for (int i = 0; i < count; i++) {
assertEqual(js, i, "createdDate", AlbumAttributes.actual_createdDate());
assertEqual(js, i, "lastModifiedDate", AlbumAttributes.actual_modifiedDate());
assertEqual(js, i, "uuid", AlbumAttributes.actual_uuid());
if (js.get("[" + i + "].coverPhoto") != null) {
String d = response1.jsonPath().get("[" + i + "].coverPhoto.tempDownloadURL").toString();
Assert.assertTrue(d.matches(AlbumAttributes.actual_temp_url()));
System.out.println(js.get("[" + i + "].coverPhoto.tempDownloadURL").toString() + " is equalent to : " + AlbumAttributes.actual_temp_url());
}
if (js.get("[" + i + "].coverPhoto.metadata['Thumbnail-Large']") != null) {
String e = response1.jsonPath().get("[" + i + "].coverPhoto.metadata['Thumbnail-Large']").toString();
Assert.assertTrue(e.matches(AlbumAttributes.actual_metaData_url()));
System.out.println(js.get("[" + i + "].coverPhoto.metadata['Thumbnail-Large']").toString() + " is equalent to : " + AlbumAttributes.actual_metaData_url());
}
}
String albumId = response1.jsonPath().get("[0].uuid").toString();
String albumId2 = response1.jsonPath().get("[1].uuid").toString();
}
I know these are void and doesnt return anything but idk how to use it. Bye the these methods are in the same class. Thanks in advance
public void AlbumDetails() {
Response response = given().queryParam("page", 0).queryParam("size", 100)
.queryParam("sortBy", "createdDate").queryParam("sortOrder", "DESC")
.header("Content-type", "application/json")
.header("Accept", "application/json")
.header("X-Auth-Token", payload.userAuth())
.when().get("/album/" + albumId)
.then().assertThat().statusCode(200).extract().response();
// Response check part
Assert.assertEquals("[]", response.jsonPath().get("fileList").toString());
Assert.assertEquals("album/photo", response.jsonPath().get("contentType").toString());
Assert.assertEquals("false", response.jsonPath().get("readOnly").toString());
Assert.assertTrue(response.jsonPath().get("createdDate").toString().matches(AlbumAttributes.actual_createdDate()));
Assert.assertTrue(response.jsonPath().get("lastModifiedDate").toString().matches(AlbumAttributes.actual_modifiedDate()));
Assert.assertTrue(response.jsonPath().get("uuid").toString().matches(AlbumAttributes.actual_uuid()));
System.out.println("Album Details Response Test PASS");
long albumDetails_time = response.getTime();
System.out.println("\tAlbum Detail's Api response time is : " + albumDetails_time);
}

The easiest way is to change the return type of the AlbumList() method from void to String:
public String AlbumList() {
And in AlbumDetails() method we should change:
.when().get("/album/" + AlbumList())
Another option is to create instance variable albumId, not locally in AlbumList() method, and use it:
public class SomeClass {
public String albumId;
public void AlbumList() {
...
albumId = response1.jsonPath().get("[0].uuid").toString();
}
public void AlbumDetails() {
...
.when().get("/album/" + albumId)
...
}
}
P.S. Here are some more tips:
due to clean code more correct name describes what these methods do, e.g. getAlbumList() or storeAlbumList() and smth similar for another method;
for extracting jsonPath from response we can use: JsonPath js = given()....extract().jsonPath();

Related

java.lang.IllegalStateExeption: Expectet a string but was BEGIN_ARRAY at line 1 column 16 path $[0].questions

I looked at some other threads about this topic and integrated the solution it offered but it still throws the same error. this is the first time i try to call an api on android. here i want to 'GET' an array of objects. There is no stack trace since the app does not crash. i think the problem has to do with the array of questions.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.100:3000/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Post>> call = jsonPlaceHolderApi.getPosts();
call.enqueue(new Callback<List<Post>>() {
#Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (!response.isSuccessful()){
textViewResult.setText("Code: " + response.code());
return;
}
List<Post> posts = response.body();
for (Post post : posts){
String content = "";
content += "Doctor: " + post.getDoctor() + "\n";
content += "Name: " + post.getName() + "\n";
content += "Questions: " + post.getQuestions() + "\n\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<Post>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
here is an example of the json data:
[
{
"questions":[...],
"_id":"5f42954a7e252b48ec3564b6",
"name":"Lifestyle",
"doctor":"doctoremail#gmail.com",
"__v":0
},
{
"questions":[...],
"_id":"5f4299687e252b48ec3564b7",
"name":"Headache",
"doctor":"doctoremail#gmail.com",
"__v":0
},
{
"questions":[...],
"_id":"5f429b2f7e252b48ec3564b9",
"name":"Foot pain",
"doctor":"doctoremail#gmail.com",
"__v":0
}
]
I fixed it. the problem was that the 'questions' property in my model was of type string in stead of List String
package com.example.medlog;
import java.util.List;
public class Post {
private String name;
private String doctor;
private List<String> questions;
public String getName() {
return name;
}
public String getDoctor() {
return doctor;
}
public List<String> getQuestions() {
return questions;
}
}

Java rest elastic search json documents

I am trying to sends json documents to elasticsearch by using java rest .
I just need to know how to initialize the variable "entities[i]" and put json documents in its.I have try many ways but still do not get something which work.
here is the code from elastticsearch website: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/_example_requests.html
int numRequests = 10;
final CountDownLatch latch = new CountDownLatch(numRequests);
for (int i = 0; i < numRequests; i++) {
restClient.performRequestAsync(
"PUT",
"/twitter/tweet/" + i,
Collections.<String, String>emptyMap(),
//assume that the documents are stored in an entities array
entities[i],
new ResponseListener() {
#Override
public void onSuccess(Response response) {
System.out.println(response);
latch.countDown();
}
#Override
public void onFailure(Exception exception) {
latch.countDown();
}
}
);
}
//wait for all requests to be completed
latch.await();
Thanks you
int numRequests = 1;
final CountDownLatch latch = new CountDownLatch(numRequests);
HttpEntity entity = new NStringEntity(
"{\n" +
" \"user\" : \"kimchy\",\n" +
" \"post_date\" : \"2009-11-15T14:12:12\",\n" +
" \"message\" : \"trying out Elasticsearch\"\n" +
"}", ContentType.APPLICATION_JSON);
List<HttpEntity> entities = asList(entity);
for (int i = 0; i < numRequests; i++) {
restClient.performRequestAsync(
"PUT",
"/twitter/tweet/" + i,
Collections.<String, String>emptyMap(),
entities.get(i),
new ResponseListener() {
#Override
public void onSuccess(Response response) {
System.out.println(response);
latch.countDown();
}
#Override
public void onFailure(Exception exception) {
latch.countDown();
}
}
);
}
latch.await();
The entity is a type HttpEntity.You need to create list of HttpEntity objects in the list and use them.

Sending data stream to multiple URLs using org.apache.commons.httpclient.HttpClient

Firstly, let me say I not a java programmer, I am a programmer on the IBM Iseries. However, I've been tasked with changing a current java application that currently sends a stream of data to one URL that will allow that same stream of data to be sent to multiple URLs based on a properties file. Our java app runs on the Iseries and we are using the org.apache.commons.httpclient.HttpClient class to send the data and the response is processed. Everything works great right now, but I wanted to see if anyone could point me in the right direction to complete this task.
Essentially, I need to send the same block of data to multiple URLs within the same thread or instance. I'm not sure if its possible or the best way to try to complete this. So, is there a way to create multiple instances within the same thread that will send the same data stream to multiple URLs? Before you start commenting I will say again that I am not a java programmer and I wasn't even sure how to phrase the question.
Added code sample:
public class Replication_CC implements TextProcessor {
public static String VERSION = "v2014.1.0";
static Logger log = Logger.getLogger(Replication_CC.class);
String url;
int retries = 1;
public Replication_CC(Properties p) {
super();
url = p.getProperty("url");
log.info("Service URL set to " + url);
retries = PropertiesUtil.getOptionalIntProperty(p, "retries", 1);
log.info("Retries set to " + retries);
}
public static void main(String[] args) throws Exception {
log.info("Replication " + VERSION);
log.info("Initializing...");
Properties p = PropertiesUtil.loadProperties(Replication_CC.class.getResource("/Replication_CC.properties"));
DQServer server = new DQServer(p, new Replication_CC(p));
server.run();
}
public String process(String request) throws Exception {
long processStart = System.currentTimeMillis();
String response = null;
for (int i=0; i<=retries; i++) {
try {
response = send(request, url);
if (response!=null) break;
}
catch (Exception e) {
log.warn("Error processing: " + e.getMessage());
if (i<retries) {
log.warn("Trying again (retry " + (i+1) + "...");
}
else {
log.error("Giving up on this transaction.");
break;
}
}
}
long processFinished = System.currentTimeMillis();
log.info("Request was processed in " + (processFinished-processStart) + "ms.");
return response;
}
public String send(String request, String url) throws Exception {
log.debug("Creating request...");
HttpClientParams params = new HttpClientParams();
params.setParameter("http.useragent", "http-api / Replication");
HttpClient client = new HttpClient(params);
PostMethod post = new PostMethod(url);
/*
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (String key : globalRequest.keySet()) {
params.add(nvp(key, globalRequest.get(key)));
}
*/
post.setRequestBody(request);
// Log the request
if (log.isDebugEnabled()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
post.getRequestEntity().writeRequest(baos);
baos.close();
log.debug("HTTP Request: \n" + StringUtils.repeat("*", 100) + "\n" + "Content Type: "
+ post.getRequestEntity().getContentType() + "\n" + "Content Length: "
+ post.getRequestEntity().getContentLength() + "\n" + "Request Headers: "
+ ArrayUtils.toString(post.getRequestHeaders()) + "\n" + "Request Params: " + baos.toString() + "\n" +
StringUtils.repeat("*", 100));
}
try {
log.info("Sending request...");
int responseCode = client.executeMethod(post);
//log.debug(String.format("Http Response Code [%s]", responseCode));
log.debug("Http Response Code [" + responseCode + "]");
if (responseCode == HttpStatus.SC_OK) {
String charset = post.getResponseCharSet();
log.debug("Response Character Set [" + charset + "]");
/*
byte[] body = post.getResponseBody();
String response = new String(body, charset);
*/
String response = IOUtils.toString(post.getResponseBodyAsStream());
log.debug("Response Body: \n" + response);
return response;
}
else {
throw new Exception(post.getStatusLine().toString());
}
}
catch (IOException ioe) {
log.error(ioe);
throw ioe;
}
finally {
post.releaseConnection();
}
}
One simple way is to include multiple URL's in the existing url property separated by a unique character. I chose "|" (pipe) in this example because it's highly unlikely to see a pipe in a normal url.
Java identifies methods by name and parameter signature. We can use that to our advantage by adding a String url parameter to the existing process method and creating a new process(String request) method that will split and iterate over the url's. The only downside is that it will only return the last response to the DQServer class.
public String process(String request) throws Exception {
String response;
for (String u : url.split("\\|")) {
response = process(request, u);
}
return response;
}
public String process(String request, String url) throws Exception {
long processStart = System.currentTimeMillis();
String response = null;
for (int i=0; i<=retries; i++) {
try {
response = send(request, url);
if (response!=null) break;
}
catch (Exception e) {
log.warn("Error processing: " + e.getMessage());
if (i<retries) {
log.warn("Trying again (retry " + (i+1) + "...");
}
else {
log.error("Giving up on this transaction.");
break;
}
}
}
long processFinished = System.currentTimeMillis();
log.info("Request was processed in " + (processFinished-processStart) + "ms.");
return response;
}
The complete sample is available on GitHub Gist.

Jersey webservice returning a null JSON

I want to get the data of a database table to the client end. I'm sending the data via a JSON. When I print the output result in the client end it gives the following result.
{"pricing":null}
When I print return statement in the server end, it outputs the following
[Connection.Pricing#3d5bae2]
There are no errors. What have I done wrong?
Here is my Client Side Code
public String loadTable(String tablename) throws ClientProtocolException, IOException {
pathParams.add("tablename", tablename);
ClientResponse response = service.path("access").path("loadtable").queryParams(pathParams).type(MediaType.APPLICATION_JSON).get(ClientResponse.class);
String responseString = response.getEntity(String.class);
return responseString;
This is my Server End
#Path("/loadtable")
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Pricing> loadTable(#QueryParam("tablename") String tablename) throws Exception {
List<Pricing> pricing = new ArrayList<Pricing>();
try {
query = c.prepareStatement("select * from " + tablename);
ResultSet ets_rs = query.executeQuery();
while (ets_rs.next()) {
pricing.add(new Pricing(ets_rs.getString(1), ets_rs.getString(2), ets_rs.getString(3), ets_rs.getString(4), ets_rs.getString(5), ets_rs.getString(6)));
}
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null) {
c.close();
}
}
return pricing;
Here is my POJO class in the server end
#XmlRootElement
class Pricing {
String category;
String lower_limit;
String class_no;
String value;
String employee;
String upper_limit;
public Pricing() {
}
Pricing(String a, String b, String c, String d, String e, String f) {
category = a;
lower_limit = b;
upper_limit = c;
class_no = d;
value = e;
employee = f;
}
//getters
}
You need to override toString method in your Pricing class to print the object in a beautiful way. The default toString() method shows the object class and its hash code separated by # character and hence you see this
Pricing#3d5bae2
Here is one implmentation of toString method for Pricing class:
#Override
public String toString() {
return "Pricing [category=" + category + ", lower_limit=" + lower_limit
+ ", class_no=" + class_no + ", value=" + value + ", employee="
+ employee + ", upper_limit=" + upper_limit + "]";
}

Moving Spring3 MVC Errors to Ajax?

I am working on a project adding some Ajax to a Spring-MVC project. I removed the tags
<form:errors path="fieldName"/>
That would insert the error the JSP, now I am trying to make some Ajax code to display the errors on the page. can anyone should me how to updated the following code to display the error messages and NOT the errors?
success: function(response)
{
// we have the response
$('#error').hide('fast');
if(response.status == "SUCCESS")
{
$('#error').hide('fast');
alert("Thanks for submitting. We will get back to you as soon as possible.\n\n" + response.result);
$('#error').hide('slow');
}else
{
errorInfo = "";
for( i = 0 ; i < response.result.length ; i++){
errorInfo += "<br>" + (i + 1) +". " + response.result[i].code;
}
$('#error').html("Please correct following errors: " + errorInfo);
$('#info').hide('slow');
$('#error').show('slow');
$('#input').show('slow');
}
},
error: function(e){
alert('Error: ' + e);
}
});
The above code works to display the errors but not the error messages
below is my java code:
#RequestMapping(value = "/ajax.html", method = RequestMethod.POST)
public #ResponseBody
JsonResponse addMessage(#Valid
#ModelAttribute(value = "memberrequest") MemberRequest memberrequest,
BindingResult result) {
JsonResponse res = new JsonResponse();
if (!result.hasErrors()) {
res.setStatus("SUCCESS");
// Setting data over to RT
String Ticket = zzz.sentWebRequest(memberrequest);
/*
* Setting out the ticket number to be displayed to user
*/
Map<String, Object> model = new HashMap<String, Object>();
Ticket t = new Ticket();
t.setTicketDetails(Ticket);
model.put("ticket", t);
res.setResult(Ticket);
} else {
res.setStatus("FAIL");
res.setResult(result.getAllErrors());
}
return res;
}
}
JSON Class:
public class JsonResponse { private String status = null; private
Object result = null;
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Object getResult() { return result; }
public void setResult(Object result) { this.result = result; }
}
Try response.result[i].defaultMessage instead of response.result[i].code.
response.result
There is no result attribute in response object according to XMLHttpRequest 2 by W3C
If you pass some text value in response form server end. you can get it response.responseText as a whole text.

Categories

Resources