Getting response status code 0 in SmartGWT webservice call using json - json

I have developed application using SmartGWT. Now I need to call webservice using json to another application which is deployed in another server for submitting username and password. When I make a request with url and POST method, getting the response status code as 0 and response text as blank.
Here is my code,
public void sendRequest() throws Exception {
// Get login json data to be sent to server.
String strData = createLoginReqPacket();
String url = "some url";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/json");
builder.setHeader("Content-Length", strData.length() + "");
Request response = builder.sendRequest(strData, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
int statusCode = response.getStatusCode();
System.out.println("Response code ----"+response.getStatusCode()+"");
if (statusCode == Response.SC_OK) {
String responseBody = response.getText();
System.out.println("Respose :" + responseBody);
// do something with the response
} else {
GWT.log("Response error at server side ----",null);
// do in case of server error
}
}// end of method.
#Override
public void onError(Request request, Throwable exception) {
GWT.log("**** Error in service call ******",null);
}// end of method.
});
builder.send();
}// end of send request.
Please anybody knows the solution?
as i am new to GWT/SmartGwt i don't no much about it.
#ModeEngage
There is no reason to use GWT class(RequestBuilder), But i don't have any idea to use Data source. Can u give reference or stuffs to do this??
And when i run this in chrome browser i get the following in error console.
XMLHttpRequest cannot load http:// "requested Url" . Origin http:// "localhost:8888" is not allowed by Access-Control-Allow-Origin.
Any solutions???

I believe this is caused by Firewall. I've run some test, and this is the most likely explanation.

Related

Apache Camel: Unit testing for file and http components

I am fairly new to Camel & just managed to implement a use case as below with 2 routes which is using file & http components. Looking for some leads on writing junits for the same. Have tried some sample test case below based on the inputs that i found on the net. Not sure if that suffices. Appreciate your help!
Implementation:
#Override
public void configure() throws Exception {
// Global Exception Handling block
onException(FileWatcherException.class).process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("Exception handled");
}
}).to("file:C:/error?recursive=true").handled(true);
// Actively listen to the input folder for an incoming file
from("file:C:/input?noop=true&recursive=true&delete=true")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
String fileName = exchange.getIn().getHeader("CamelFileName").toString();
exchange.getIn().setHeader("fileName", fileName);
}
})
// Call the Get endpoint with fileName as input parameter
.setHeader(Exchange.HTTP_METHOD, simple("GET"))
.toD("http://localhost:8090/fileWatcher?fileName=${header.fileName}")
.choice()
// if the API returns true, move the file to the outbox folder
.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(constant(200)))
.to("file:C:/outbox?noop=true&recursive=true")
.endChoice()
// If the API's response code is other than 200, move the file to error folder
.otherwise()
.log("Moving the file to error folder")
.to("file:C:/error?recursive=true")
.end();
// Listen to the outbox folder for file arrival after it gets moved in the above step
from("file:C:/outbox?noop=true&recursive=true")
// Request Body for POST call is set in FileDetailsProcessor class
.process(new FileDetailsProcessor())
.marshal(jsonDataFormat)
.setHeader(Exchange.HTTP_METHOD, simple("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
// Call the Rest endpoint with fileName & filePath as RequestBody
.to("http://localhost:8090/fileWatcher")
.process(new MyProcessor())
.end();
}
Junit
#Test
public void checkFileWatcherFunctionality() throws Exception {
context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
// mocking all endpoints. **QUESTION** - Is this required?
mockEndpointsAndSkip("http://localhost:8090:fileWatcher?fileName=loan.csv");
mockEndpointsAndSkip("file:C:/processing");
mockEndpointsAndSkip("file:C:/error");
mockEndpointsAndSkip("http://localhost:8090:fileWatcher");
}
});
context.start();
// **QUESTION** - This is a GET call. Expecting only the HTTP status code from it. How to check that?
getMockEndpoint("mock:http://localhost:8090:fileWatcher?fileName=abc.txt").expectedBodyReceived();
// **QUESTION** - This is a POST call. How to send request body along? Expecting only the HTTP status code from it. How to check that?
getMockEndpoint("mock:http://localhost:8090:fileWatcher").expectedBodyReceived();
// **QUESTION** - Is this the right way to check?
getMockEndpoint("mock:file:C:/processing").expectedFileExists("loan.csv");;
template.sendBodyAndHeader("file:C:/inbound", "", Exchange.FILE_NAME, "loan.csv");
// QUESTION - What can be asserted now?
}
Also - How to write test cases for negative flow (exception scenario)? Looking for suggestions.
I have managed to draft the test case. Is this the right approach or can there be a better way?
This might be more of an integration test i suppose.
The issue i see now is that the test case doesn't report at the end (success or failure), instead it keeps waiting for file arrival in the input folder. What am i missing?
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FileWatcherRouteBuilderTest extends CamelTestSupport {
#Autowired
private TestRestTemplate restTemplate;
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new FileWatcherRouteBuilder();
}
#Test
public void testFileCopy() throws Exception {
template.sendBodyAndHeader("file:C:/inbound", "", Exchange.FILE_NAME, "abc.csv");
// Call the GET endpoint
ResponseEntity<String> getResponse = restTemplate.getForEntity("http:localhost:8090/fileWatcher?fileName=abc.csv",
String.class);
assertTrue("Get call is unsuccessful", getResponse.getStatusCode().is2xxSuccessful());
String response = getResponse.getBody();
assertTrue(!response.isEmpty());
// The file would have moved to output folder now.
File targetFile = new File("C:/processing");
assertTrue(targetFile.isDirectory());
assertEquals(1, targetFile.listFiles().length);
// Since we need to extract the file name, doing the below step
Exchange exchange = consumer.receive("file:C:/processing");
String fileName = exchange.getIn().getHeader("CamleFileName").toString();
// RequestBody needed for POST call
FileDetails fileDetails = new FileDetails(fileName, "C:/processing/"+fileName);
HttpHeaders headers = new HttpHeaders();
HttpEntity<FileDetails> request = new HttpEntity<FileDetails>(fileDetails, headers);
// Call the POST endpoint
ResponseEntity<String> postResponse = restTemplate.postForEntity("http://localhost:8090/fileWatcher", request, String.class);
assertTrue("Post call is unsuccessful", postResponse.getStatusCode().is2xxSuccessful());
// Asserting that after both the web service calls, the file is still available in the output folder
assertEquals(1, targetFile.listFiles().length);
}
}

Loopj Put and Post with basic auth return null response with no error

This is an attempt to use Loopj for a Synchronous put and post call from a HTTP utility class. The code uses a syncrhonous client as it’s used inside an AsyncTask and some UI interactions depend heavily on the json response so the AsyncTask is managing making the call asynchronously.
All the get calls from the HTTP utility class are working successfully. The post and put do not and they both appear to have exactly the same problem.
The json string is created using Gson. I’ve tested the json output from the application directly in Postman and it posts exactly as expected to the API, so it appears to be well formed and behaves totally as expected without any errors.
Both the put and post calls are constructed without throwing an error. Basic authorization is being added (as shown on the client instance). The SyncHTTPClient put method is called using a null context parameter. I did a bit of research and found a single post where this was being done successfully.
https://github.com/loopj/android-async-http/issues/1139
The put call fires but doesn’t enter either the overridden methods of the handler. It just returns null. I've included a portion of the working class to view:
public void executePutSave(String name, String pass, String jsonBody) {
client.setBasicAuth(name, pass);
executeLoopJPutCall("/api/Save", jsonBody);
}
public void executeLoopJPutCall(String relativeUrl, String jsonBody) {
String url = getAbsoluteUrl(relativeUrl);
StringEntity entity = new StringEntity(jsonBody, "UTF-8");
jsonResponse = null;
client.put(null, url, entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
jsonResponse = response.toString();
Log.i(TAG, "onSuccess: " + jsonResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
jsonResponse = errorResponse.toString();
Log.e(TAG, "onFailure: " + statusCode + errorResponse );
}
}
);
}
So, apparently the header must be added explicitly when using the above code to Post or Put json to the API. Once I changed the header authentication line from this:
client.setBasicAuth(name, pass);
To this:
String userpass = name + ":" + pass;
String encoded = new String(Base64.encode(userpass.getBytes(),Base64.NO_WRAP));
client.addHeader("Authorization", "Basic "+encoded);
...everything worked as expected.
I found the information on this blog: https://github.com/loopj/android-async-http/issues/113
Passing a null context worked, too.

How to make JSON PUT request through Codename one API

I'm not able top figure out JSON put request from codename one api. I didnt find any example to make this request.
Questions:
1. I'm not sure whether I have to send the content length parameter. If yes, how can I send that?
2. I have to send the request body with just "true" nothing else. There is no key and value to use req.addArgument() method.
3. Do I have to use buildRequestBody() method to override the request. Can you provide an example?
4. How to verify the result after receiving the response.
Any help can be appreciated.
Thanks.
Please find the code below.
req.setUrl(identityUrl );
req.setPost(false);
req.setHttpMethod("PUT");
req.setContentType("application/json");
req.addRequestHeader("authorization", token);
req.addArgument("Content-Length", "4");
req.setReadResponseForErrors(true);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
d.dispose();
JSONParser parser = new JSONParser();
Map map2 = null;
try {
map2 = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(req.getResponseData()), "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
If you want the content to be embedded wholly you need to override the buildRequestBody method. Notice that post needs to be true for the body to be called.
I don't think you need content-length:
req = new ConnectionRequest(identityUrl) {
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(json.getBytes("UTF-8"));
}
protected void readResponse(InputStream input) throws IOException {
map2 = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
}
protected void postResponse() {
// response completed, this is called on the EDT do the application logic here...
}
};
req.setPost(true);
req.setHttpMethod("PUT");
req.setContentType("application/json");
req.addRequestHeader("authorization", token);
req.setReadResponseForErrors(true);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
req.setDisposeOnCompletion(d);
NetworkManager.getInstance().addToQueue(req);
Notice that I no longer need to close streams or handle IOException as the connection request does everything for me. Also notice the read/build methods are called on the network threads and not on the EDT so you need to do the rest of the flow in the postResponse.

Error with Null

I am working on a project here and am running into an issue. It was working fine before but what I am doing is sending a request to a url and am expecting a JSON response. However when I check the response it keeps coming back as null. This was not an issue before but randomly started happening. Any help would be greatly appreciate!'
Also I have another class that actually does the url requests.
This first bit is the onclick listener on the login page. It takes the text fields and converts them to strings. The way the login works is it has to push all the information into the URL which is why it is set up this way.
bt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String account = acct.getText().toString();
String uname = user.getText().toString();
String passWord = pass.getText().toString();
url = ap+"&t2mdeveloperid="+id+account+"&t2musername="+uname+"&t2mpassword="+passWord;
new Login().execute();
}
}
);
}
Alright here is the Async task that the request runs in.
private class Login extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(){
super.onPreExecute();
//Here we will display our progress bar. This is dependent on each page.
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Talk2M Account");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0){
//We need to create an object to call our service handler to make our http request.
ServiceHandler login = new ServiceHandler();
//Now we need to make a request to the url as well as recieve the response.
String response = login.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + response);
try{
JSONObject jsonObj = new JSONObject(response);
String session = jsonObj.getString(TAG_SESSION);
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
if(pDialog.isShowing())
pDialog.dismiss();
}
}
If the JSON you're getting back is null, my first guess would be to verify that you are hitting the right URL. If that is the case, then there may be an issue on the api side. You may want to test this HTTP request outside of the context of your application, in a REST client or web browser.
Regards.

Error trying to connect to an mvc server on ms-azure from a windows phone 8 app using webapi

I'm a little bit new to all of these technologies so I'll try to be as clear as I can.
I'm writing a windows phone app that sends data in string format to a server:
public class sendDataControl
{
private string response = "";
public void sendToServer(string FullSTR)
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://pricequeryserver.azurewebsites.net/api/ReceiptDataService/?incomingdata=");
webClient.UploadStringAsync(uri,FullSTR);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
}
catch (Exception ex)
...
...
}
}
void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
{
responseXml=e.Error.Message;
MessageBox.Show(responseXml);
return;
}
else
{
responseXml = e.Result;
}
}
}
The server is an MVC4, basic, with api controller I added, that needs to get the data sent from the mobile.
As a test I'm just getting back a string that I send:
public class ReceiptDataServiceController : ApiController
{
private ReceiptContext db = new ReceiptContext();
...
...
public string GetDataFromMobile(string IncomingData)
{
return IncomingData;
}
}
While running the application I get an error via responseXml:
"The remote server returned an error: NotFound".
The server returns the right answer from all kinds of browsers, while on IIS and on the azure but not from the mobile emulator.
Any suggestions?
If you take a look at the documentation for UploadStringAsync overload you are using, you will notice that it sends data using POST method. While in your controller you have only implemented GET. And for your
You have to use other overload of UploadStringAsync, which lets you specify the HTTP VERB to use. And you must specify GET. Your client code should be converted to:
webClient.UploadStringAsync(uri,"GET", FullSTR);
And the best solution for simple GET operations like your is to actually use DownloadStringAsync:
var fullUri = new Uri("http://pricequeryserver.azurewebsites.net/api/ReceiptDataService/?incomingdata=" + FullStr);
webClient.DownloadStringAsync(fullUri);
Anyway, your question has nothing to do with Windows Azure, thus the removed tag.