I have been researching on the better framework I could use to validate the data at client and server side. I know it is important to do validations at both the side.
I had thus come across something called GWT Validation Framework which can do validations at both the side. I have few JSP's. I have o validate the data filled in by user, at client side. But I haven't found a single example on how to do it? Can anyone please enlighten on the same.
Thank you
P.S: It would be grateful if someone could assist on some better client side validation methods(other than java script).
GWT has support for compiling javax.validation into a compile module, but it isn't going to be easy to use without actually using GWT. The validation mechanism is powered by JSR-303 bean validations, and so needs to see the bean on both the client and on the server - a html client page created by a jsp isn't enough, you need to create and load a GWT module onto the page.
In GWT, you write what looks like Java, and it compiles to JavaScript. JSR303 support also gets compiled to javascript, so any amount of client side validation isn't enough - see Why is client-side validation not enough? for more explanation on that - your server also needs to run the validation.
If you are not already using GWT, then GWT's validation isn't going to make a lot of sense for your project. If you decide this all makes sense for you, then start using it - check out http://www.gwtproject.org/doc/latest/DevGuideValidation.html for more information and the sample project at https://github.com/gwtproject/gwt/tree/master/samples/validation for some source.
For client side data validation
I am using Putnami Web Toolkit (PWT).
This framework is compliant with commons JSR-303 bean validation annotations.
You can find documentation and live example at this location :
http://pwt.putnami.org/#!Validation
For server side data validation
I am using Hibernate's Bean Validation JSR-303 reference implementation ( version 4.3.2-Final ).
An example below :
imports :
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
code :
final Set<ConstraintViolation<BeanToValidate>> violations = validator.validate(form);
if (!violations.isEmpty()) {
final Set<ConstraintViolation<?>> constraintViolations = new HashSet<ConstraintViolation<?>>(
violations);
throw new ConstraintViolationException(constraintViolations);
}
Related
My target is to build a GraphQL server on Spring with (1) GraphiQL IDE (2) dynamic GraphQL schema at run-time. My GraphQL engine is GraphQL-Java.
In my first try, I use graphql-java-spring-boot-starter-webmvc and graphiql-spring-boot-starter.
Both the GraphQL server and the GraphiQL work well.
However, under the graphql-java-spring-boot-starter-webmvc framework, a #Bean of GraphQL class is needed. In this bean, the schema is loaded when the server starts so it could not been updated.
In my second try, I don't use graphql-java-spring-boot-starter-webmvc. Instead, I choose spring-boot-starter-web to start the web server and define my own RestController. This is easy to update the GraphQL instance. But I don't find a way to integrate with GraphiQL. I googled GraphiQL+Spring but all solutions are with graphql-java-spring-boot-starter.
Appreciate if anyone could provide me an idea on either approach.
It can be enabled in properties:
graphql.graphiql.enabled=true
It is accessible via the root url +/graphiql example http://localhost:8080/graphiql
You can find a good detailed example here : https://github.com/NoorKrichen/GraphQL-Spring-Boot-Example
Do you have a sample of your setup in git?
It sounds like some configuration problem. But naturally using graphql-java-spring-boot-starter-webmvc all your *.graphql schemas should be picked up in the configured schema resource path. check if you have the path set in your application.yml or if your schema is in the configured path if its already set or by default.
On your second point: "I googled GraphiQL+Spring but all solutions are with graphql-java-spring-boot-starter."
This makes sense for quick guides and demos as using Springboot the plumbing is somehow hidden away from you so that you can focus on the technology at hand being demo'd in this case GraphQl.
On GraphiQL:
Sounds like you are intending to have this embedded with your application, you may not want to do so in production. Depending on your use case there are many other alternatives that are standalone and gives you all the functionality of GraphiQL plus more e.g Altair Graphql Client and Insomnia to name a few.
I'm setting up authentication for a portion of a webapp using standard servlet container authentication (web.xml security entries) plus Tomcat Realm capabilities (to read users and roles from a database).
Everything seems to fit my requirements except one aspect: since the authentication will guard our REST APIs, I'd like every response to be in JSON format.
But with the tools I'm going to use, when there's a failed authentication Tomcat sends back a response with an HTML body.
I found this question on Spring that addresses the same issue, but it relies on Spring components.
Is there any customization possible using only servlet and Tomcat components?
From first glance, simple solution may look like custom error page for error code 401 (or any other).
Look for answer there:
how to specify the default error page in web.xml
P.S. Probably you can also use custom Servlet filter to handle content for error.
Because you're using a standard JAX-RS provider you can take advantage of the standards that exist. Normally you'd want something like:
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
#Provider
public class MyExceptionMapper implements ExceptionMapper<RuntimeException> {
#Override
#Produces(MediaType.APPLICATION_JSON)
public Response toResponse(RuntimeException exception) {
return Response.status(Response.Status.FORBIDDEN)
.entity("{\"error\": \"your error message\"}")
.type(MediaType.APPLICATION_JSON)
.build();
}
}
The hard part here is that the exceptions vary between JAX-RS providers. So, while I may get a RuntimeException with RestEasy (and I know that I do) the exception may be different with Jersey. If you implement an exception mapper that just takes Exception you can quickly figure out what type of Exception is thrown with your JAX-RS provider.
The advantage of this is that it is mostly standard in that you could move to another app server and it would not be Tomcat specific.
I am using jersey client for rest calls. Imports for my code are:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
Everything is working fine. I am using Sonar for checking my Code quality.
sonar is showing a major issue for:
Classes from "com.sun." and "sun." packages should not be used
Is this actually bad practice to use classes from sun?
If yes, what are the alternatives?
It's better to migrate to JAX-RS 2.0 client classes. Some refactoring would be necessary though. See the migration guide. For example, if you wrote like this before:
Client client = Client.create();
WebResource webResource = client.resource(restURL).path("myresource/{param}");
String result = webResource.pathParam("param", "value").get(String.class);
You should write now like this:
Client client = ClientFactory.newClient();
WebTarget target = client.target(restURL).path("myresource/{param}");
String result = target.pathParam("param", "value").get(String.class);
Because they are internal APIs: they are subject to change in a undocumented or unsupported way and they are bound to a specific JRE/JDK (Sun in your case), limiting portability of your programs.
Try to avoid uses of such APIs, always prefer a public documented and specified class.
Reference- It is a bad practice to use Sun's proprietary Java classes?
I am writing a restlet client that will invoke some Resteasy coded rest services (cannot change the server code, hence cannot use the Restlet way of annotating resources).
Resource Interface is using JAX-RS annotations and have more than one #POST method (one of the biggest problems of Restlet when dealing with this).
I was trying to do my implementaion this way:
IAppLoginResource resource = JaxRsClientResource.createJaxRsClient("http://localhost:9090/rest", IAppLoginResource.class);
final GetLoginAppInfoResponse response = resource.getLoginAppInfo( getLoginAppInfoRequest );
The problem is that the request by default is GET, I didn't find a way to specify the request method like when using ClientResource (which I can't use because I need to deal with JaxbRepresentation and Jaxb problems).
Any sample/snippet of code that implement a Restlet client using JAX-RS annotated resources?
Any ideas?
Thanks,
I've entered an issue for this topic:
https://github.com/restlet/restlet-framework-java/issues/1081
I've tested a sample application based on your code, and it works properly using the current 2.3 branch (future 2.3.3). I wonder if the fix for this issue https://github.com/restlet/restlet-framework-java/issues/1072 helps.
Regarding the documentation, I 'll complete the current page (http://restlet.com/technical-resources/restlet-framework/guide/2.3/extensions/jaxrs), cf this issue: https://github.com/restlet/restlet-framework-java/issues/1084.
You can also have a look at the org.restlet.test project, especially in this package https://github.com/restlet/restlet-framework-java/tree/2.3/modules/org.restlet.test/src/org/restlet/test/ext/jaxrs.
I'm working on a web-service-proxy with auditing (later on with caching = creating own responses) and I need to generate #Endpoints (such that will just forward i.e. call a remote web service or dummy atleast). Marshaling/unmarshaling seems neccessary for the proxy will add "something" to the request...
We are to use spring-ws and JAXB. Got all XSDs and static WSDLs of the proxied web service.
Any hints around? Anyone doing something similar? How are you doing it?
Is there a simple way how to achieve this using spring or spring-integration?
Thanks in advance..
This should be possible using both Spring WS and Spring Integration:
With Spring WS, you can create a proxy class for your remote WS, wrapping around a org.springframework.ws.client.core.WebServiceTemplate to talk to the WS - which has API's to take care of marshalling the request to xml and unmarshalling the response.
With Spring Integration, you can use an outbound Webservices gateway , but you will need to front it with a messaging gateway, which will act as your proxy, along these lines:
<int:gateway id="wsproxy" service-interface="..ProxyInterface" default-request-channel="requestChannel" default-reply-channel="replyChannel"/>
<int-ws:outbound-gateway id="wsGateway" request-channel="requestChannel" uri="http://serviceURL" marshaller="someMarshaller" unmarshaller="someUnmarshaller"/>
However, I would recommend the first approach of using the WebserviceTemplate, as you do not have a very complex integration need here.
Today I can tell how we proceeded without spring-integration. We found two different ways how to generate #Endpoint class.
1) Using XSLT and Freemarker we generated the endpoint class source in pre-compile phase. XSLT transformation walked thru all WSDL files to create one summary file which was then used to generate the source.
2) Using Javassist we copied the template class, then generated methods regarding content of JAXB2Marshaller instance and finally instantiated object using FactoryBean, all at server start-up.
Problem here we met was set of XSD files written in form that caused the root objects were generated without #XmlRootAnnotation. Javassist version we had internally works with Java 1.4 (no generics) so we used global customization file for XJC and forced #XmlRootAnnotation on root objects.
Both solutions have their pros and cons but both are simpler then using ESB.