HTTPService not retrieving current data - apache-flex

I'm using mx.rpc.http.HTTPService to retrieve data from a web service. On the initial call to "loadWsData", HTTPservice accurately retrieves all the data.
However, on any and all subsequent calls HTTPService does not accurately retrieve the data; rather it always retrieves the first data set. I've confirmed that the web service is providing accurate data, both from web browsers and a ruby ws client script.
My code is below; any ideas on what could be the problem?
private function loadWsData(id:int):void
{
var webService:HTTPService = new HTTPService();
webService.url = "http://xxx.xxx.xxx.xxx:8080/profile/ + id;
webService.method = "GET";
webService.addEventListener(ResultEvent.RESULT, function(event:ResultEvent):void
{
var rawData:String = String(event.result);
var user:Object = JSON.decode(rawData).user; // User object always reflects the first data set retrieved.
....
....
});
webService.send();
}

Not sure what the issue might be, but I have a few suggestions on where to look.
First, there appears to be a bug in your code; the webService.url line is missing a quote mark. That could be messing up the URL you think you are sending. Odd, though, because I don't think what you have shown would compile, so I suspect this is just a cut-and-paste error when you posted this to StackOverflow, but I would trace out that URL just to be sure.
Also, I don't see code to remove the event listener (although it could be in the code you have abbreviated with ellipsis). Is it possible that there are lingering event listeners that are firing in addition to the ones you expect? If the original event listener fires, it will fire with the original data.
Another suggestion: instead of using a closure, try pulling it out to a separate function. That shouldn't be the issue, but maybe scope is playing a role here.
You could try to POST your results.
You might also add an event listener for FAULT, and see if there are any errors being thrown by your service request.

Related

What I misunderstood about the Mediator Pattern?

I'm new here and a beginner architect. I'm helping the company I work to design our new product and since I start it, I read a lot about but is never enough.
I decided to use Mediator Pattern (with Mediatr) to call my application layer.
It's cool and I got how to work with it sometimes, but sometimes I get confused.
For example, when we publish a document on our new product, we uses a RequestHandler to do everything and check all rules it needs, it's fine and works like a charm, but, when I want just a quick data, it looks likes too much for just a simple thing.
As an example, every time the user do any kind of action on my web application, I have to check if he is still logged. We have single login per user, so, if the same user connect anywhere else, the older session expires. We do it by saving on database.
On every action of my app, I go to base and check if the session key is the same, as bellow.
var sessionKey = bibliotecaCookie.Value;
var mediator = controller.GetMediator();
var isUserSessionKeyValidRequest = new IsUserSessionKeyValidRequest()
{
sessionKey = sessionKey
};
var isValidSession = mediator.Send(isUserSessionKeyValidRequest).Result;
if (!isValidSession)
throw new UnauthorizedAccessException();
So, I have a RequestHandler (a Handler and a Request which returns a bool) just to check if the user session is ok.
When the handler catches this request, it goes to database and execute a simple rule which is "Is the passed session the same as the stored session key?".
Is it right? Is it the right approach? Did I understand it right?
Thanks in advance guys

http service not working for parallel requests

I am using an http service object to make servlet requests inside a method in flex. The method is being invoked simultaneously in parallel by two events. I could see that both requests have reached the servlet, but only one returns to the result event. Also this behaviours is not consistent . is it possible that parallel invocation of the httpservice result in loss of some requests? I am sure that both requests have reached the servlet and data is returned from it. Its just that the result event is not triggered in certain cases.
Thanks in advance.
Including code to describe the issue better.
Please find the method below. The below method "callServlet" is being invoked by two separate events
private var httpObj:HTTPService=new HTTPService();
private function callServlet(text:String):void{
Alert.show(text);
httpObj = new HTTPService();
httpObj.url=<servlet URL>;
httpObj.method="POST";
httpObj.resultFormat="xml";
httpObj.contentType="application/xml";
var requestString:String=text;
httpObj.request=requestString;
httpObj.addEventListener(ResultEvent.RESULT,onResultMethods);
httpObj.addEventListener(FaultEvent.FAULT,onFaultMethod);
httpObj.send();
}
Each time i call the method, i pass a different "text" variable. I can see that the alert displays the two different texts send to it. And as explained earlier, both requests does reach the servlet and a response is sent from servlet.
But the result event "onResultMethod" is invoked just once.It doesnt invoke the "faultonFaultMethod" either.
Yes, I have seen this problem before, if you are making multiple requests from flex, some of them will be lost, that was back in 3.0 times. Browsers has a way of stopping the number of http calls, they can allow maximum of 2 calls at a time(depends on the browser), may be chain your requests one after the other or use a singleton which manages your calls.
Thanks all for help. I think i ve got the issue though i cannot guarantee the answer to be right.
The above method is called twice by two events. The httpOject variable is a private var global to the method callServlet. The listeners created in this method are being removed in the result and fault handler methods(this is not shown in the code above).
So i believe when multiple events call the method simultaneously there is a chance that the global variable httpObj is modified by both the events and hence both events result in servlet call using the same httpservice object. When the first call returns to the resulthandler i am removing the listener for resulthandler due to which the second result does not reach the resulthandler method.
This is my assumption and as of now i dont have any better solution. Do let me know if anyone comes up with a better explanation.

Actionscript 3: How to do multiple async webservice call requests

I am using Flex and Actionscript 3, along with Webservices, rpc and a callResponder. I want to be able to, for example, say:
loadData1(); // Loads webservice data 1
loadData2(); // Loads webservice data 2
loadData3(); // Loads webservice data 3
However, Actionscript 3 works with async events, so for every call you need to wait for the ResultEvent to trigger when it is done. So, I might want to do the next request every time an event is done. However, I am afraid that threading issues might arise, and some events might not happen at all. I don't think I'm doing a good job of explaining, so I will try to show some code:
private var service:Service1;
var cp:CallResponder = new CallResponder();
public function Webservice()
{
cp.addEventListener(ResultEvent.RESULT, webcalldone);
service = new Service1();
}
public function doWebserviceCall()
{
// Check if already doing call, otherwise do this:
cp.token = service.WebserviceTest_1("test");
}
protected function webcalldone(event:ResultEvent):void
{
// Get the result
var result:String = cp.lastResult as String;
// Check if other calls need to be done, do those
}
Now, I could ofcourse save the actions in an arraylist, but whose to say that the addToArrayList and the check if other calls are available do not mess eachother up, or just miss each other, thereby halting execution? Is there something like a volatile Arraylist? Or is there a completely different, but better solution for this problem?
Use an AsyncToken to keep track of which call the returned data was for http://flexdiary.blogspot.com/2008/11/more-thoughts-on-remoting.html
When I want to store data in an async manor I put it in an array and make a function that will "pop" the element as I send it off.
This function will be called on complete and on error events.
Yes I know there could be an issue with the server and data lost but oh well. That can also be handled
Events will always fire however, it may not be a complete event that gets fired but could be an error event.
Once the array is empty the function is done.

Loss of data in a JQuery call to a WebService

I've made a JQuery function that makes a call to a web service, the web service returns an int but somewhere between the web service returning its value and the JQuery picking it up the data is getting lost. below is my Jquery Function:
//Make a call to a web service to get the latest number of comments for this item
WebDesign.wfGetNumberOfCommentsForWebDesignItem(vintCurrentItemID,fGetNumberOfCommentsResult);
function fGetNumberOfCommentsResult(GetNumberOfCommentsResult){
//If the number of comments returned is not zero update the the number of comments
if (GetNumberOfCommentsResult != -1 && GetNumberOfCommentsResult != null)
{
vspanCommentsNumber.html(GetNumberOfCommentsResult);
}
else
{
vspanCommentsNumber.html("Unknown");
}
}
The variable GetNumberOfCommentsResult is null, not every time but I'd say about 10% of the time. I've recorded the data that the web service returns to the JavaScript and it's not null, it's valid data, so I'm at a loss as to how the JavaScript variable is set as null. Any ideas?
Can you confirm that you are running this in a callback, when the call to the webservice is guaranteed done, and not some timed method using setTimeout ? in the second case, a race condition could explain the variable results that you are getting.
Using FireBug (add-on for Firefox), on the Console tab you can see what data is being returned from the web service call, as well as what data is being passed.
First verify the data being moved back and forth. This is the easiest way to find a truly reproducible case.
Also, it would be helpful to see how you are calling the web service on the JavaScript side.
use fiddler or something similar to monitor http requests and actually grab the response when it is null, there has to be something different about it.

PopUpWindow and null object reference

I've been struggling with this problem for last few hours but still got no idea what's wrong. Here's the scenario:
Application built on top of the Mate framework sometimes need to exchange data with remote server over plain binary socket.
When specific packet is received I have to switch view (using ViewStack) and create custom panel (using PopUpManager class). This custom panel contains a dataGrid component which has to be populated with some XML received along with mentioned packet.
Trouble is that when I try to assign XML to DataGrid's dataProvider I constantly get "Cannot access a property or method of a null object reference" error. The only thing I can think of is some kind of race when processing events and creating components.
Here are the most interesting pieces of code:
<!-- LoginEvent.LOGIN_OK _____________________________________________________________________ -->
<EventHandlers type="{LoginEvent.LOGIN_OK}">
<MethodInvoker generator="{UserManager}" method="storeCurrentUser" arguments="{event.fullName}"/>
<EventAnnouncer generator="{NavigationEvent}" type="{NavigationEvent.MAIN}"/>
<MethodInvoker generator="{CustomSocket}" method="listBoards"/>
In the above code I react when the LOGIN_OK packet is received.
Store user's data, change the view and ask the Socket class wrapper to send request (the reponse for that request is our verySpecificPacket)
Here's detailed info about how I change the view and create custom pop up. In MainUI.mxml:
<mate:Listener type="{NavigationEvent.MAIN}" method="handleNavigationEvent" />
private function launchBoardListWindow():void {
Logger.info("launchBoardListWindow()");
var win:BoardList = PopUpManager.createPopUp(this, BoardList, true) as BoardList;
PopUpManager.centerPopUp(win);
}
private function handleNavigationEvent(event:NavigationEvent):void {
viewStack.selectedIndex = MAIN;
launchBoardListWindow();
}
The third position in EventMap isn't important, it just ask socket wrapper to send some kind of packet. The server is supposed to respond with verySpecialPacket along with XML payload. And here we are at the part where the error is. In mxml describing my custom panel I set up a listener for an event which is being dispatched after my verySpecialPacket is received.
public function handleListBoardsEvent(e:ListBoardsEvent):void {
Logger.info("handleListBoardsEvent");
xmlData = e.xml;
boardList.dataProvider = xmlData.children(); // Here's the error!!!
}
I really don't get it, since the xmlData is OK, and custom panel with all child components were created. Thanks for reading!
You're likely on the right track in respect of a race condition.
Suggestion:
Put a try { ... } catch (e:Error) { trace("error"); } block around the code in your handleListBoardsEvent() method.
Then, put a breakpoint on the trace() and, when it hits, take a good look around at the various objects involved.
My guess is that you're attempting to access the boardList object before it is created - i.e. it's null.
The other possibility is that boardList.dataProvider is a setter and there's code in the setter that's barfing. (Although, if that were the case, I'm sure you would have noticed the stacktrace inFlexBuilder)

Resources