I am trying to dispatch fault event in GraniteDS service
method call (Flex):
userService.addUser(user, null, function addUserFault(e:TideFaultEvent):void {
Alert.show(e.fault.faultString);
});
server method (Spring):
#Override
public User addUser(User user) throws Exception{
if(findUserByName(user.getUsername()) != null)
throw new Exception("Username Already Exist");
entityManager.persist(user);
return user;
}
But what i get is silence on client side and java.lang.NoSuchMethodException in server console.
How can i use default graniteds exception converter to deliver fault event to client (Flex)?
Solved. I dont know if it's a bug or not, but you cannot set result function to null and specify fault function only - this wont work. My call method should look like:
userService.addUser(user, function addUserResult(e:TideResultEvent){
// do nothing
}, function addUserFault(e:TideFaultEvent):void {
Alert.show(e.fault.faultString);
});
in this case java Exception in remote method will be send back to flex as TideFaultEvent.
Related
A bit of background: PropertyFunction is an interface in Jena API that allows doing performing custom operations using SPARQL syntax. Example:
select ?result { ?result f:myPropertyFunction 'someObject' . }
So I made a class Launch that implements this interface and extends a class Client. Within the body of the exec method of my Launch class I establish a connection to a server and, while sending information is no problem, waiting for the server to respond is. Whenever I try to wait() for server response I get the following exception: java.lang.IllegalMonitorStateException.
Here is the body of my exec method for reference:
QueryIterator it = null;
try {
this.connect(); // works well
this.send(algorithmAndArgs); // works well
this.wait(); // exception is thrown
#SuppressWarnings("unused")
ResultSet rs = ResultSetFactory.create(it, Arrays.asList(resultIdentifiers));
} catch (Exception e) {
e.printStackTrace();
}
return it;
Anyone know what the problem may be? Thank you for your answer.
EDIT 1: One thing that I forgot to mention is that the Client class has a method called onObjectReceived(Object o, Socket s) that is triggered each time something is received from the server. I tried using a isDone variable with a while loop in the exec method and set it to true once an object is received, but it did not work.
I solved my own problem: I created an attribute private final CountDownLatch objectWasReceivedLatch = new CountDownLatch(1) and, in the exec method I do boolean objectWasReceived = objectWasReceivedLatch.await(60, TimeUnit.SECONDS); when I want to wait for a response; in the onObjectReceived method I call objectWasReceivedLatch.countDown().
I am trying to create a client library that reads JSON from an external file online. I already know about the function interfaces and optionals, but I was wondering if there is a way to allow users to supply callback functions such that the parent function exits completely. For JavaScript, such a function is as follows:
file.read('hello', function(err, data) {
// something here
});
Basically, I wish to do the same in Java. How can I do this such that the error callback supersedes the read function? What I mean is that in the event that the error callback is called, then read should not return a value at all. If the callback is not called then the read should return the value.
You could have the user pass in a function and then just not do anything with it if there is no error.
This example assumes that you have a custom class called Error that the caller is aware of and would like to interact with in case of an error.
public void read (String str, Function<Error,Void> errorFunc)
{
//interact w/ libraries, boolean error = true or false
//if there is an error, variable err of type Error contains information
if (error)
{
errorFunc.apply(err);
}
}
In Java upto 1.7 the only way to achieve javascript like callbacks is thru interface. The api user who calls your method read has the liberty of implementing what he feels needs to be done to handle the error by writing an implementation class for the interface at the invocation point.
public String read(String options,IErrorCallBack errorHandler) throws Exception {
try {
// When everything works fine return what you think should be returned.
return "Success";
}
catch(Exception e) {
// On Error call the function on the error handler.
errorHandler.doSomething();
throw e;
}
}
public interface IErrorCallBack {
public void doSomething();
}
// The invocation point.
read("myString", new IErrorCallBack() {
public void doSomething() {
// Your implementation.
}
});
I am doing something with fix protocol using quickfix library.
I wrote class like this:
public class ApplicationImpl implements Application {
...
#Override
public void toApp(Message arg0, SessionID arg1) throws DoNotSend {
//this is invoked before sending message
}
...
}
I wonder how to invoke some method after sending message?
QuickFIX does not offer a after-message-send callback.
You need to have this somewhere in your code to send a message (not in the overriden methods):
Session.sendToTarget(outgoingMessage, orderSession);
That will execute some internal quickfixJ code and then call toApp(). The toApp() method allows you do modify the message before it is sent to the broker. But ideally in order to do something after you send you just need to add code after the call to Session.sendToTarget().
If you are adventurous, you can modify QuickFIX/J to do it. The MINA network layer does provide a messageSent callback. If you override that method in QFJ's InitiatorIoHandler (or AcceptorIoHandler) you could either directly process the messageSent event or propagate it to a modified Application interface.
If I undertand correctly. You need to do some action after you send a message. If it is correct I have the following example:
public static void send(Message message) {
boolean sent = Session.sendToTarget(message, mySessionId);
if (sent){
//do something
}else {
//something else
}
System.out.println("El mensaje se mandó: " + sent);
} catch (SessionNotFound e) {
System.out.println(e);
}
}
I have a newly coded GWT/GAE app that uses RequestFactory and Editors on the client and a custom Objectify DAO Service on the back.
The flush() then persist() paths work fine on success.
Client side JSR 303 works as well as can be expected too.
My question is how to trigger server warnings/errors and handle UI updates?
I am using Chandler's Generic DAO for Objectify 2 at
http://turbomanage.wordpress.com/2010/02/09/generic-dao-for-objectify-2/
my gwt activity is calling persist( myProxy ).fire( new Receiver<> )
my dao code is throwing IllegalArgumentException and other RuntimeExceptions for business logic situations like "Duplicate email address found - want to login instead?"
Receiver<>.onSuccess() works fine to track a successful outcome.
neither Receiver<>.onFailure() nor Receiver<>.onViolation() report the RuntimeExceptions.
( Correction: onFailure() is being called for server-side exceptions)
Is there a better way to do this?
What exceptions should the DAO throw such that onViolation() or onFailure() report errors?
How should the editor(s) handle and recover from the exception?
I've found the most versatile command sequence to be
void start() {
// Either get p
context1.get(..).to( new Receiver<P> { onSuccess(P resp){p = resp;} ... }).fire();
// OR create p
p = context2.create( P.class );
// Then save p
req = context2.persist(p).to( new Receiver<P>{ /* note do not use context1 */
onViolation(...) { /*JSR 303 handler*/ };
onFailure( error ) { /* handle */ error.getMessage() };
onSuccess(X x) { /* whatever persist() returns handler */ }; } );
// drive editor with p
driver.edit( p, req);
}
....
void onSave() {
// editor
ctxt = driver.flush() /* note ctxt == context2 */
if ( driver.hasErrors() ) { /*JSR 303 handler*/};
// RF
ctxt.fire();
}
Based on the conversation excerpt below at http://groups.google.com/group/google-web-toolkit/browse_thread/thread/da863606b3893132/96956661c53e1064?hl=en
Thomas Broyer
onFailure should containg the getMessage() of the
exception you threw on the server
side.
You can tweak it by providing your own
ExceptionHandler to the
RequestFactoryServlet (extend it and
use its constructor taking an
ExceptionHandler).
onViolation will only be called if
your entities do not pass JSR-303 Bean
Validation, which is checked before
calling any service method.
If you want to
"catch" the failure in clidnt code,
you have to add a Receiver for the
persist() service method:
context.persist(p).to(new Receiver…
Here is a simple server application using Bonjour and written in Java. The main part of the code is given here:
public class ServiceAnnouncer implements IServiceAnnouncer, RegisterListener {
private DNSSDRegistration serviceRecord;
private boolean registered;
public boolean isRegistered(){
return registered;
}
public void registerService() {
try {
serviceRecord = DNSSD.register(0,0,null,"_killerapp._tcp", null,null,1234,null,this);
} catch (DNSSDException e) {
// error handling here
}
}
public void unregisterService(){
serviceRecord.stop();
registered = false;
}
public void serviceRegistered(DNSSDRegistration registration, int flags,String serviceName, String regType, String domain){
registered = true;
}
public void operationFailed(DNSSDService registration, int error){
// do error handling here if you want to.
}
}
I understand it in the following way. We can try to register a service calling "registerService" method which, in its turn, calls "DNSSD.register" method. "DNSSD.register" try to register the service and, in general case, it can end up with two results: service was "successfully registered" and "registration failed". In both cases "DNSSD.register" calls a corresponding method (either "serviceRegistered" or "operationFailed") of the object which was given to the DNSSD.register as the last argument. And programmer decides what to put into "serviceRegistered" and "operationFailed". It is clear.
But should I try to register a service from the "operationFailed"? I am afraid that in this way my application will try to register the service too frequently. Should I put some "sleep" or "pause" into "operationFailed"? But in any case, it seems to me, that when the application is unable to register a service it will be also unable to do something else (for example to take care of GUI). Or may be DNSSD.register introduce some kind of parallelism? I mean it starts a new thread but that if I try to register service from "operation Failed", I could generate a huge number of the threads. Can it happen? If it is the case, should it be a problem? And if it is the case, how can I resolve this problem?
Yes, callbacks from the DNSSD APIs can come asynchronously from another thread. This exerpt from the O'Reilly book on ZeroConf networking gives some useful information.
I'm not sure retrying the registration from your operationFailed callback is a good idea. At least without some understanding of why the registration failed, is simply retrying it with the same parameters going to make sense?