mayduTechblog

May 6, 2009

GWT-VL: Validation with Restlet GWT

Filed under: GWT, Java — admin @ 4:15 pm

A user of GWT-VL asked me if it is possible to use GWT-VL in conjunction with the Restlet-GWT project. The answer was ambivalent. Because you could already use GWT-VL as a client side only validation library with Restlet-GWT, but you could not profit from the connection between server side and client side, which is surely one of the strong points of the GWT-VL library. Before the 0.7 release line of GWT-VL the library was only able to connect server and client side with throwing ValidationException’s that would be sent back to the client with the use of RPC. The good thing with that is, that you stay on the Java road in that you will catch RuntimeExceptions of type ValidationException which should feel quite naturally to a Java programmer. Anyway, the problem with that approach is that it only works if you connect your client side via RPC to the server side. Clearly, Restlet-GWT doesn’t do that. So I decided to think about a way how I could integrate the server to client connection without the use of RPC. What I came up with is not exactly an Restlet-GWT integration but a general way of connecting the server and the client side of GWT-VL. The idea is to just pack the validation messages into Strings and pass them from the server side to the client side. With this approach I think virtually every framework will be able to make use of GWT-VL. So if you have choosen to communicate with your services via RPC, you just use the RuntimeException mechanism. If you do not use RPC than you are now able to let GWT-VL serialize its server side ValidationException’s into Strings that you can send back to your client. The client side has added functionality that allows it to process these Strings the same way it would process the ValidationException’s sent via RPC.

So enough with talking, lets dive into how you can gain the benefits of the use of a sophisticated validation library named GWT-VL while using RestletGWT on the backend.

The validation specifics on the client side have already been initially described on the first two posts about GWT-VL so if you haven’t read them by now I would advise you on reading them first here (Part 1) and here (Part 2).

Lets assume we have a page with two input fields which we try to validate on the client and on the server. The client side code could look something like this:

  1. final TextBox codewordBox = new TextBox();
  2. final TextBox tokenBox = new TextBox();
  3.  
  4.         validator.addValidators("codeword",
  5.                 new IntegerValidator(codewordBox)
  6.                         .addActionForFailure(new StyleAction("redBorder"))
  7.         );
  8.  
  9.         validator.addValidators("token",
  10.                 new IntegerValidator(tokenBox)
  11.                         .addActionForFailure(new StyleAction("redBorder"))
  12.         );

This is not different from the usual way of using the GWT-VL library. Differences arise when we start facilitating the server side. First we call the server side from the client side and handing over some input to the server side.

  1.        button.addClickListener(new ClickListener() {
  2.             public void onClick(Widget sender) {
  3.                 if(!validator.validate())
  4.                         return; //Some client side validation errors occured, validator actions are fired automatically
  5.                 // Add an AJAX call to the server
  6.                 final Client client = new Client(Protocol.HTTP);
  7.                 Form form = new Form();
  8.                 form.add("codeword", codewordBox.getText());
  9.                 form.add("token", tokenBox.getText());
  10.                 client.post("http://localhost:8888/validate", form.getWebRepresentation(), new Callback() {
  11.                     @Override
  12.                     public void onEvent(Request request, Response response) {
  13.                         String ret = ((StringRepresentation)response.getEntity()).getText();
  14.  
  15.                         if(!validator.processSerializedValidationErrorsSilently(ret)) {
  16.                                 //The server side signaled a validation error.
  17.                                 //All the actions will have been automatically invoked by
  18.                                 //the ValidationProcessor (as usual), so just return.
  19.  
  20.                                 return;
  21.                         }
  22.  
  23.                         //If we get here no validation errors were received from the server side
  24.                         //We would now direct the user to some other page, show him a success message, etc.
  25.                     }
  26.                 });
  27.             }
  28.         });

Here we see the standard GWT-VL stuff like: validator.validate() that just invokes all the client side validators and triggers the specific actions if an error occured. One thing that is new is the validator.processSerializedValidationErrorsSilently method. But before we come to that let me explain how the call to the server works. We use RestletGWT functionality for passing the value of the text boxes to the REST service. We use the POST method to post the data to the server side service. After the service returns its data, we feed whatever came from the service to the validator.processSerializedValidationErrorsSilently method. This method will automatically check whether the returned string denotes a serialized validation exception that the ValidationProcessor should consume or not. If it finds out that the returned String denotes a ValidationException in serialized form, it will be parsed and all the actions specified on the client side for the fields that the server side has deemed errorneous are invoked. If it sees that the returned String is not a serialized ValidationException, it just silently (thus the name) returns true and the code can assume that no error came from the server side (at least no GWT-VL validation error).

So let’s see what exactly happens on the server side. We have a Restlet resource that supports the POST method and validates the input:

  1. public class ValidateResource extends Resource {
  2.  
  3.     public ValidateResource(Context context, Request request, Response response) {
  4.         super(context, request, response);
  5.         getVariants().add(new Variant(MediaType.TEXT_PLAIN));
  6.         this.setModifiable(true); //Needed to support POST
  7.     }
  8.  
  9.     @Override
  10.     public void acceptRepresentation(Representation entity) throws ResourceException {
  11.         Form form = new Form(entity);
  12.         //Get the values from the post
  13.         String text1 = form.getFirstValue("codeword");
  14.         String text2 = form.getFirstValue("token");
  15.  
  16.         int codeword = -1;
  17.         int token = -1;
  18.  
  19.        //We convert the strings coming from the form to their intended type
  20.        //Note: If we would use RPC we wouldn’t need this step ;>
  21.  
  22.         try {
  23.                 codeword = Integer.parseInt(text1);
  24.         }catch(NumberFormatException ex) {
  25.                 try {
  26.                         ServerValidation.exception("noInteger", "codeword", text1);
  27.                 }catch(ValidationException ex2) {
  28.                         getResponse().setEntity(getValidationRepresentation(ex2));
  29.                         return;
  30.                 }
  31.         }
  32.  
  33.         try {
  34.                 token = Integer.parseInt(text2);
  35.         }catch(NumberFormatException ex) {
  36.                 try {
  37.                         ServerValidation.exception("noInteger", "token", text1);
  38.                 }catch(ValidationException ex2) {
  39.                         getResponse().setEntity(getValidationRepresentation(ex2));
  40.                         return;
  41.                 }
  42.         }
  43.  
  44.         try {
  45.                 new ServerValidation(false)
  46.                         .inRange(codeword,0, 100, "codeword")
  47.                         .inRange(token,0, 100, "token")
  48.                         .validate();
  49.         }catch(ValidationException ex) {
  50.                 //Ok, we got an validation error we talk that back to the client and quit the server side processing
  51.                 getResponse().setEntity(getValidationRepresentation(ex));
  52.                 return;
  53.         }
  54.         StringRepresentation str = new StringRepresentation("Success");
  55.         getResponse().setEntity(str);
  56.     }
  57.  
  58.     private StringRepresentation getValidationRepresentation(ValidationException ex) {
  59.         String serializedException = null;
  60.  
  61.         //Serialize the validation exception to a string which can be send over the wire to the client
  62.         serializedException = ServerValidation.serializeValidationException(ex);
  63.  
  64.         return new StringRepresentation(serializedException);
  65.     }
  66. }

Of course you probably have some code to make the parsing easier to write. You should create a method that will do this for you. But for clarity reasons I did go the “verbose” way. So you see what exactly needs to be done.

That’s basically all there is to do to get server and client side validation to act together as a  a pair like you are used to when using GWT-VL and all without RPC.

The first release to provide the forementioned features is the 0.7a release (but you really should download the newest 0.7b) wich you can get from Sourceforge.

Note: The new release also features support for parameterized custom validation messages.

So, thanks for listening and if you have comments, questions or feature requests do not hesitate to drop me a mail or use the Tracker and Forums on Sourceforge.

Kind regards,

Anatol Mayen

19 Comments »

Nice framework, buy I have a question…Could you tell me how to change de messages descriptions? I need spanish language…thanks!!!

Comment by Sergio — October 27, 2009 @ 5:19 pm


Hi Sergio!

You can create your own ValidationMessages_es.properties file and create your own Interface extending StandardValidationMessages and pass it to an instance of the ValidationMessages class, something like this:

public interface MyStdMessages extends StandardValidationMessages {

}

Now you need a MyStdMessages.properties file which contains your spanish translations. Just copy the contents of the existing file as a starting point: http://gwt-vl.svn.sourceforge.net/viewvc/gwt-vl/trunk/src/main/java/eu/maydu/gwt/validation/client/i18n/StandardValidationMessagesImpl_en.properties?view=markup

Now you can populate your ValidationProcessor like this:

ValidationProcessor validator = new DefaultValidationProcessor(GWT.create(MyStdMessages.class));

Hope this helps!

Kind regards, Anatol

Comment by admin — October 28, 2009 @ 3:26 pm


СПС.

Я тут

Trackback by Сергей — April 4, 2010 @ 6:16 pm


serff.ru…

Имею возможность поделиться практическим опытом в описанной проблемат…

Trackback by serff.ru — April 20, 2010 @ 11:45 am


sharpei-dogs.ru…

Изобретенная мной мысль серьезно отличается от опубликованной авт…

Trackback by sharpei-dogs.ru — April 23, 2010 @ 3:17 pm


makefitnes.ru…

Не всем дано добиться результата, надо еще что бы руки росли из нуж…

Trackback by makefitnes.ru — April 25, 2010 @ 12:34 am


formula1funs.ru…

Сильно хочется поделиться опытом с кем-либо по теме. У кого есть воз…

Trackback by formula1funs.ru — April 28, 2010 @ 8:55 am


myenglishcom.com…

Имею возможность поделиться практическим опытом в описанной пробле…

Trackback by myenglishcom.com — May 1, 2010 @ 12:24 pm


УРА.!…

Всех с 1 мая!…

Trackback by ВАн4ezzZ — May 2, 2010 @ 8:14 am


russia4project.ru…

Теория классная. Результатами исследований может кто-то похвас…

Trackback by russia4project.ru — May 3, 2010 @ 8:03 pm


http://rel” rel=”nofollow”>хм…

Что то со ссылками…

Trackback by Monah — June 5, 2010 @ 1:19 am


http://rel” rel=”nofollow”> Спасибо,…

Хотя новость уже читал…

Trackback by Сергей — June 5, 2010 @ 11:47 pm


Hello! Please e-mail me your contacts. I have a question zachary@complective.ru” rel=”nofollow”>……

Thanks!…

Trackback by Frankie — June 11, 2010 @ 8:39 pm


Medicamentspot.com International Legal RX Medications. Special Internet Prices (up to 40% off average US price). NO PRIOR PRESCRIPTION REQUIRED!…

Combivir@buy.online” rel=”nofollow”>.…

Trackback by CAMERON — June 24, 2010 @ 12:55 pm



PillSpot.org. Canadian Health&Care.No prescription online pharmacy.Special Internet Prices.Best quality drugs. Low price pills. Order pills online

Buy:Accutane.Human Growth Hormone.Nexium.100% Pure Okinawan Coral Calcium.Lumigan.Arimidex.Zovirax.Petcam (Metacam) Oral Suspension.Prevacid.Prednisolone.Retin-A.Valtrex.Synthroid.Actos.Zyban.Mega Hoodia….

Trackback by LYNN — July 15, 2010 @ 8:52 pm



MedicamentSpot.com. Canadian Health&Care.Special Internet Prices.No prescription online pharmacy.Best quality drugs. High quality pills. Buy pills online

Buy:Cialis Professional.Maxaman.Viagra.Levitra.Super Active ED Pack.Zithromax.VPXL.Viagra Professional.Propecia.Viagra Super Force.Cialis Soft Tabs.Tramadol.Viagra Super Active+.Cialis.Viagra Soft Tabs.Cialis Super Active+.Soma….

Trackback by DUANE — July 21, 2010 @ 3:44 pm


Dress http://bavenues0pjw.ANTIQUEFURNINISHING.INFO/tag/Dress+Barn+Avenues+rhea/ : rhea…

Avenues…

Trackback by Barn — August 30, 2010 @ 4:50 am



CheapTabletsOnline.Com. Canadian Health&Care.Best quality drugs.Special Internet Prices.No prescription online pharmacy. Low price drugs. Order pills online

Buy:Prozac.Seroquel.Buspar.Zocor.Cozaar.Advair.Amoxicillin.Female Pink Viagra.SleepWell.Benicar.Nymphomax.Wellbutrin SR.Lasix.Lipitor.Ventolin.Female Cialis.Acomplia.Aricept.Lipothin.Zetia….

Trackback by HOMER — September 5, 2010 @ 12:50 pm



CheapTabletsOnline.com. Canadian Health&Care.No prescription online pharmacy.Special Internet Prices.Best quality drugs. No prescription pills. Order drugs online

Buy:Arimidex.Mega Hoodia.Human Growth Hormone.Accutane.100% Pure Okinawan Coral Calcium.Synthroid.Valtrex.Lumigan.Retin-A.Prednisolone.Prevacid.Petcam (Metacam) Oral Suspension.Nexium.Zovirax.Zyban.Actos….

Trackback by LEO — September 6, 2010 @ 9:11 am


RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress