flex blazeds response null for first time service call - java

I am using Flash Builder 4.5 with Blazeds service to develop flex
appliacation, here i used java for services and here i am getting
empty value from server side for first time service call, after that
from next service calling it gives correct result to me, I don't know
why i am getting null value for first time hitting the service. Here
for the first time hitting java service, the functionality is running
at java side but return value is null.
Please any one help me out.

If we use LastResult for service response then I got this error, I used requestHandler for handling response and i got my response for first time itself.
Service.addEventListener("result", resultHandler);
private function resultHandler(evt:ResultEvent):void {
var ac = evt.result;
}

Related

Error in backend of REST API: "INFO: The connection was broken. It was probably closed by the client. Reason: Closed"

So I am trying out a simple full stack project of my own that involves a java backend implementation of a REST API, for which I am using the org.restlet.com framework/package and jetty as the server.
Whilst I was testing my API using Postman I noticed something wierd: Every time I started the server only the first POST/PUT/DELETE HTTP Request would get an answer, while the next ones would not receive one and on the console this error message would appear:
/* Timestamp-not-important */ org.restlet.engine.adapter.ServerAdapter commit
INFO: The connection was broken. It was probably closed by the client.
Reason: Closed
The GET HTTP Requests however do not share that problem.
I said "Fair enough, probably it's postman's fault".. after all the request made it to the server and their effects were applied. However, now that I am building the front-end this problem blocks the server's response: instead of a JSON object I get an undefined (edit: actually I get 204 No Content) on the front-end and the same "INFO" on the back-end for every POST/PUT/DELETE after the first one.
I have no idea what it is or what I am doing wrong. It has to be the backend's problem, right? But what should I look for?
Nevermind, it was the stupidest thing ever. I tried to be "smart" about returning the same Representation object (with only a 'success' JSON field) on multiple occasions by making one instance on a static final field of a class. Turns out a new instance must be returned each time.

How to elegantly recover from network failure & repeat request to different endpoint?

I have a few servers that I make REST requests to from my program. They will all have the same response to a particular request.
I accept one ip as argument and make my requests to that server. If I wish to now accept a List<ip>, how do I elegantly switch to the next server in the list when one fails? Looping through the list on every network call seems silly.
Unfortunately I cannot make a REST call with the catch-repeat_to_next_server extracted to one function that accepts an HttpClient with the rest of the request because I'm using a 3rd part SDK to talk to the servers and every request is a chain of method calls.
I can't do this (pseudo-code):
def doRequest(HttpClient client)
for ip in list_of_ips:
try:
client.host = ip
return client.execute()
catch exp:
// move failed ip to end of list or something
throw "None of them worked"
HttpClient c
c.method = "GET /api/employees"
doRequest(c)
c.method = "GET /api/department/:id"
doRequest(c)
Are there any standard ways to solve this in clean way?
I'm using Java and Spring so I am constrained by static typing but may have some sort of Spring annotation magic that I can use that I am not aware of.
How you are making the REST call is not important.
Your psuedo code should be correct even if you need to make a million method calls per REST call.
for ip in ip_list
do_stuff_to_make_the_rest_call
perhaps_note_the_ip_that_was_used
indicate_success
break_out_of_for_loop
catch some_exception
perhaps_note_the_ip_that_failed
end for
if !success
do all_ip_failed_stuff.
procedure do_stuff_to_make_the_rest_call
make a million method calls to get one REST call attempt.

How to continue on client when heavy server computation is done

This might be a simple problem, but I can't seem to find a good solution right now.
I've got:
OldApp - a Java application started from the command line (no web front here)
NewApp - a Java application with a REST api behind Apache
I want OldApp to call NewApp through its REST api and when NewApp is done, OldApp should continue.
My problem is that NewApp is doing a lot of stuff that might take a lot of time which in some cases causes a timeout in Apache, and then sends a 502 error to OldApp. The computations continue in NewApp, but OldApp does not know when NewApp is done.
One solution I thought of is fork a thread in NewApp and store some kind of ID for the API request, and return it to OldApp. Then OldApp could poll NewApp to see if the thread is done, and if so - continue. Otherwise - keep polling.
Are there any good design patterns for something like this? Am I complicating things? Any tips on how to think?
If NewApp is taking a long time, it should immediately return a 202 Accepted. The response should contain a Location header indicating where the user can go to look up the result when it's done, and an estimate of when the request will be done.
OldApp should wait until the estimate time is reached, then submit a new GET call to the location. The response from that GET will either be the expected data, or an entity with a new estimated time. OldApp can then try again at the later time, repeating until the expected data is available.
So The conversation might look like:
POST /widgets
response:
202 Accepted
Location: "http://server/v1/widgets/12345"
{
"estimatedAvailableAt": "<whenever>"
}
.
GET /widgets/12345
response:
200 OK
Location: "http://server/v1/widgets/12345"
{
"estimatedAvailableAt": "<wheneverElse>"
}
.
GET /widgets/12345
response:
200 OK
Location: "http://server/v1/widgets/12345"
{
"myProperty": "myValue",
...
}
Yes, that's exactly what people are doing with REST now. Because there no way to connect from server to client, client just polls very often. There also some improved method called "long polling", when connection between client and server has big timeout, and server send information back to connected client when it becomes available.
The question is on java and servlets ... So I would suggest looking at Servlet 3.0 asynchronous support.
Talking from a design perspective, you would need to return a 202 accepted with an Id and an URL to the job. The oldApp needs to check for the result of the operation using the URL.
The thread that you fork on the server needs to implement the Callable interface. I would also recommend using a thread pool for this. The GET url for the Job that was forked can check the Future object status and return it to the user.

Randomly Channel.Connect.Failed error when calling to a Java server from Flex application using AMF protocol

I have a project published in the Internet that is used by thousands of users every day. Basically, I'm using a server in AmazonAWS with the server part compiled in Java 6 running in a Tomcat. I'm using AMF to publish the services and my client is built in Flex 4.6 using Flash Builder to generate the classes to connect to the AMF services. The code I'm using to connect to the services is this:
public var cpcService:RemotingServicesImpl;
private function callService():void
{
FlexGlobals.topLevelApplication.callingService=true;
encryptedSession=ResourcesUtil.buildSessionId(globalSettings.sessionId, globalSettings);
var responder:Responder=new Responder(gameStateLoaded, gameStateFailed);
var token:AsyncToken=cpcService.getGameState(encryptedSession, taskKey);
token.addResponder(responder);
}
private function gameStateFailed(ev:FaultEvent=null):void
{
DisplayUtil.trackErrorInfoEvent("FATAL - FatalError", "getGameState-" + FlexGlobals.topLevelApplication.mainView.currentState, ev, encryptedSession);
}
private function gameStateLoaded(ev:Object):void
{
// my fantastic code when everything is ok
}
Normally, everything is ok and my application is working, but some calls (like 1 every 500) are not working, I know it because in the trackErrorInfoEvent function I'm registering an event in the Google Analytics, so I know this is randomly happening. This is the error:
faultCode = "Client.Error.MessageSend"
faultDetail = "Channel.Connect.Failed error NetConnection.Call.Failed: HTTP: Failed: url: 'https://appcog.cognifit.com/messagebroker/amf'"
faultString = "Send failed"
rootCause = (null)
Of course the URL is correct and is working all times.
I have seen in some blogs that adding this line:
<add-no-cache-headers>false</add-no-cache-headers>
the problem is fixed, but I have that line in my config file and is still happening.
I have checked my server logs and I have no records for service interruptions at any time.
I really apreciate any help, thanks in advance!

Newbie 'Can you do this with Dojo/Ajax' Question

I have a web page that has a function that will send an initial request to a web service.
After some predefined time, the user can send a second request.
After the user sends the first request, I want the web page to countdown when the user may send the second request.
After the countdown, I want a DB field to be updated automatically, indicating that the appropriate time has passed.
When the time has passed and the DB updated, I'd like the webpage updated to show a button that would allow the user to send the second request.
After the initial request, call a JavaScript user-defined function "countdown()" using the in-built JavaScript function "setTimeout("countdown()", 4000)", where the number "4000" resembles the number of micro-seconds that need to be passed to fire the function mentioned in the first parameter.
In the "countdown()" function, write the logic for the AJAX call, where you will be updating the database that the desired time of 4 seconds (for example) has passed & now the user can send the second request.
Also in the same AJAX call, you can print out some word (let the word be "yes" for example), which you can catch / fetch it in the "countdown()" function definition, using the "responseText" keyword of JavaScript's "XMLHttpRequestObject", in a dummy variable "flag".
Now you can write something like the following in the "countdown()" function definition:-
function countdown() {
document.getElementById("btn_second_req").style.display = 'none';
var flag = '';
// all code to prepare for AJAX call
// AJAX called, return also fetched in a variable "flag".
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
flag = XMLHttpRequestObject.responseText;
}
if (flag == 'yes') {
document.getElementById("btn_second_req").style.display = 'block';
}
}
So by default, the second request firing HTML button is hidden from the very first time, & only activated when the "flag" variable condition is satisfied.
Also since the details of the first call of any user is being kept in the DB, so in the second call, you need to check with server validation that there exists details for the first call, otherwise the second request call will not be entertained.
These type of logic can easily be implemented using any JavaScript framework library (like jQuery or Prototype) or by plain JavaScript only.
Hope it helps.
Yes, it can be done. Here is how I would do it, which is almost as you describe it.
1- The web page sent the request to the service. The service compute the time until the next request can be executed, store it in a db field/in session (depending how your service work), and send it back to the client, plus whatever it is your service send back.
2- You create a timer with the setTimeout function of javascript (or an equivalent if you use a javascript library) http://www.w3schools.com/js/js_timing.asp .
3- When the timer execute, you send a request to the webservice to ask if its ok to start the second request. The server check the time in the db field. If it is past "next request time", the server respond positive, else it return the remaining time, and the client then create a new timer.
4- You send your new request. The server check again if its "next request time" (in case someone smart hack the javascript, or if their is a bug on the client). If it is time, it execute the second request.
The only difference is that with the way I described, everything on the server execute as the result of a client action, so you don't have to mess with thread/cron job to auto update your db field.
Good luck!

Categories