Hi Paul,

Thanks for sharing this idea. I've added a link to it in a related RFE:

"Improve parameter validation"
http://restlet.tigris.org/issues/show_bug.cgi?id=221 

If you could contribute your class that would be nice. You just need to
attach it to the RFE above and to take care of the JCA paperwork: 
http://www.restlet.org/community/contribute

Best regards,
Jerome Louvel
--
Restlet ~ Founder and Lead developer ~ http://www.restlet.org
Noelios Technologies ~ Co-founder ~ http://www.noelios.com


-----Message d'origine-----
De : Paul J. Lucas [mailto:[EMAIL PROTECTED] 
Envoye : jeudi 7 aout 2008 17:24
A : [email protected]
Objet : Any interest in a DTO class?

I wanted a simple way to get the values of request parameters into an  
Object.  I've implemented a DTO (Data Transfer Object) class that can  
be used for this.

Suppose you want to implement a query request.  You could do something  
like:

        public class QueryDTO extends DTO {
            @Required public String q;
            public SortOrder order; // SortOrder is enum { NAME, DATE, SIZE
}
            public Boolean desc;

            QueryDTO( Request request ) throws DTOException {
                super( request );
                if ( order == null ) order == SortOrder.NAME;
                if ( desc == null ) desc = Boolean.FALSE;
            }
        }

What this says is that a request has 3 query parameters.  Of those,  
"q" is a required String.  The DTO constructor takes care of all the  
parsing of form data (for both APPLICATION_WWW_FORM and  
MULTIPART_FORM_DATA cases), enforces @Require constraints, and handles  
enum values.  You can then use it like:

        public void handleGet() {
            try {
                QueryDTO dto = new QueryDTO( getRequest() );
                // ... use dto.{members} as you please ...
            }
            catch ( DTOException e ) {
                e.setStatusOf( getResponse() );
            }
        }

DTO also correctly handles array values.  For example, specifying:

            public String[] field;

allows "field" to be specified more than once:

        http://server/foo?field=val1&field=val2&;...

There are also @Permitted and @Forbidden annotations.  For example:

            @Permitted( onlyIf={"y"} )
            public Integer x;

            @Permitted( onlyIf={"x"} )
            public Integer y;

This will cause DTO to throw an exception if either "x" or "y" is  
given without the other.  (@Forbidden works similarly, but in reverse.)

If there's interest, I'd be willing to donate this code to Restlet.

- Paul

Reply via email to