I am creating a resteasy web service using hibernate jpa framework and ejb implementation.
I created a dynamic web project and my project structure are as follow:
WebApplication.java
public class WebApplication extends Application {
private Set<Class<?>> classes = new HashSet<Class<?>>();
private Set<Object> singletons = new HashSet<Object>();
#EJB
private PersonEndpoint personEndpoint;
public WebApplication(){
classes.add(PersonEndpointBean.class);
}
#Override
public Set<Object> getSingletons(){
return singletons;
}
#Override
public Set<Class<?>> getClasses(){
return classes;
}
}
PersonEndpoint.java
public interface PersonEndpoint {
public Response creaatePersonEndpoint(Person person);
public Response updatePersonEndpoint(Person person);
public Response deletePersonEndpoint(int id);
public Response retrievePersonEndpoint(int id);
public Response retrieveAllPerson();
}
PersonEndpointBean.java
#Stateless
#Local(PersonEndpoint.class)
#Path("/Person")
#Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public class PersonEndpointBean implements PersonEndpoint{
#EJB
private PersonService service;
public PersonEndpointBean(PersonService service){
this.service = service;
}
public PersonEndpointBean(){
super();
}
#Override
#POST
#Path("/Create")
public Response creaatePersonEndpoint(Person person) {
return service.createPerson(person);
}
#Override
#POST
#Path("/Update")
public Response updatePersonEndpoint(Person person) {
return service.updatePerson(person);
}
#Override
#POST
#Path("/Delete")
public Response deletePersonEndpoint(int id) {
return service.deletePerson(id);
}
#Override
#GET
#Path("/Search/{id}")
public Response retrievePersonEndpoint(#PathParam("id") int id) {
return service.retrievePerson(id);
}
#Override
#GET
#Path("/Search")
public Response retrieveAllPerson() {
System.out.println("==========");
return service.retrieveAllPerson();
}
}
Beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-
app_2_4.xsd" id="WebApp_ID" version="2.4">
<display-name>JPAandEJB</display-name>
<context-param>
<param-name>resteasy.async.job.service.base.path</param-name>
<param-value>/asynch/jobs</param-value>
</context-param>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.ph.application.WebApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
PersonService.java
public interface PersonService {
public Response createPerson(Person person);
public Response updatePerson(Person person);
public Response deletePerson(int id);
public Response retrievePerson(int id);
public Response retrieveAllPerson();
}
PersonServiceBean.java
#Stateless
#Local(PersonService.class)
public class PersonServiceBean implements PersonService{
#EJB
private PersonDao dao;
public PersonServiceBean(PersonDao dao){
this.dao = dao;
}
public PersonServiceBean(){
super();
}
#Override
public Response createPerson(Person person) {
try{
if(person != null){
dao.insertToTable(person);
return Response.status(Response.Status.CREATED).build();
} else{
return Response.status(Response.Status.BAD_REQUEST).build();
}
} catch(Exception e){
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
#Override
public Response updatePerson(Person person) {
try{
if(person != null){
dao.updateToTable(person);
return Response.status(Response.Status.ACCEPTED).build();
} else{
return Response.status(Response.Status.BAD_REQUEST).build();
}
} catch(Exception e){
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
#Override
public Response deletePerson(int id) {
try{
Person person = dao.getRowToTable(id);
dao.deleteToTable(person);
return Response.status(Response.Status.ACCEPTED).build();
} catch(Exception e){
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
#Override
public Response retrievePerson(int id) {
try{
Person person = dao.getRowToTable(id);
return Response.status(Response.Status.ACCEPTED).entity(person).build();
} catch(Exception e){
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
#Override
public Response retrieveAllPerson() {
try{
List<Person> list = dao.getListToTable();
System.out.println("===========>" + list.size());
return Response.status(Response.Status.ACCEPTED).entity(list).build();
} catch(Exception e){
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
}
When i try to invoke the GET method using postman I get the following error logs.
09:24:05,589 ERROR [io.undertow.request] (default task-2) UT005023: Exception handling request to /SERVICE/Person/Search: org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:77)
at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:220)
at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:175)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:418)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:209)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:221)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at com.ph.endpoint.PersonEndpointBean.retrieveAllPerson(PersonEndpointBean.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:139)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:295)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:249)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:236)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:402)
... 43 more
I've search a lot of forum but it seems none is working.. TIA
Related
I followed the walkthrough for setting up a custom authenticator spi for keycloak (version 4.8.3). I pretty much only use the example code i got from here. I only changed the pom so i could compile the project and deploy it with mvn clean install wildfly:deploy. And it works ... I can configure the new authentication flow in keycloak, update the Browser Flow and set the required actions. But if i want to use the new Authentication with my application i get the following message: Invalid username or password. And in the console i get the following output:
17:12:20,721 WARN [org.keycloak.events] (default task-1) type=REFRESH_TOKEN_ERROR, realmId=master, clientId=security-admin-console, userId=null, ipAddress=127.0.0.1, error=invalid_token, grant_type=refresh_token, client_auth_method=client-secret
17:13:50,514 WARN [org.keycloak.services] (default task-4) KC-SERVICES0013: Failed authentication: org.keycloak.authentication.AuthenticationFlowException: authenticator: secret-question-authenticator
at org.keycloak.authentication.DefaultAuthenticationFlow.processFlow(DefaultAuthenticationFlow.java:194)
at org.keycloak.authentication.AuthenticationProcessor.authenticateOnly(AuthenticationProcessor.java:910)
at org.keycloak.authentication.AuthenticationProcessor.authenticate(AuthenticationProcessor.java:779)
at org.keycloak.protocol.AuthorizationEndpointBase.handleBrowserAuthenticationRequest(AuthorizationEndpointBase.java:139)
at org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint.buildAuthorizationCodeAuthorizationResponse(AuthorizationEndpoint.java:419)
at org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint.process(AuthorizationEndpoint.java:152)
at org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint.buildGet(AuthorizationEndpoint.java:108)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:140)
at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:509)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:399)
at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$0(ResourceMethodInvoker.java:363)
at org.jboss.resteasy.core.interception.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:358)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:365)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:337)
at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:137)
at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:106)
at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:132)
at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:100)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:443)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:233)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:139)
at org.jboss.resteasy.core.interception.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:358)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:142)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:219)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:227)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:791)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at org.keycloak.services.filters.KeycloakSessionServletFilter.doFilter(KeycloakSessionServletFilter.java:90)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:360)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
at java.lang.Thread.run(Thread.java:748)
17:13:50,523 WARN [org.keycloak.events] (default task-4) type=LOGIN_ERROR, realmId=Test, clientId=test, userId=null, ipAddress=192.168.1.123, error=invalid_user_credentials, auth_method=openid-connect, auth_type=code, response_type=code, redirect_uri=http://localhost:8080/sso/login, code_id=102f9drs-15d2-4e68-b123-38c092640da7, response_mode=query
I looked up the file DefaultAuthenticationFlow.java:194 on github and it seems to be a RuntimeException:
throw new RuntimeException("Unable to find factory for AuthenticatorFactory: " + model.getAuthenticator() + " did you forget to declare it in a META-INF/services file?");
I dont really know what to do about that. I have the META-INF/services from the example project included.
any idea what the problem might be here?
Update:
Here my auth. flow settings:
Bindings ยป Browser Flow: is set to test
Update:
I used something like this for my own authenticator.
public class TestAuthenticator extends UsernamePasswordForm {
#Override
public void action(AuthenticationFlowContext context) {
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
if (formData.containsKey("cancel")) {
context.cancelLogin();
return;
}
if (!validateTestForm(context, formData))
return;
context.success();
}
private boolean validateTestForm(AuthenticationFlowContext context, MultivaluedMap<String, String> formData) {
String username = formData.getFirst(AuthenticationManager.FORM_USERNAME);
String password = formData.getFirst(CredentialRepresentation.PASSWORD);
// remove leading and trailing whitespace
username = username.trim();
context.getEvent().detail(Details.USERNAME, username);
context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);
if (username == null) {
context.getEvent().error(Errors.USERNAME_MISSING);
Response challengeResponse = challenge(context, Messages.INVALID_USER);
context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
return false;
}
UserModel user;
try {
// Check if this user exists
user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
if (user != null) {
// do your own thing here ...
validateUserAndPassword(context, formData);
}
} catch (ModelDuplicateException mde) {
ServicesLogger.LOGGER.modelDuplicateException(mde);
// Could happen during federation import
if (mde.getDuplicateFieldName() != null && mde.getDuplicateFieldName().equals(UserModel.EMAIL)) {
setDuplicateUserChallenge(context, Errors.EMAIL_IN_USE, Messages.EMAIL_EXISTS,
AuthenticationFlowError.INVALID_USER);
} else {
setDuplicateUserChallenge(context, Errors.USERNAME_IN_USE, Messages.USERNAME_EXISTS,
AuthenticationFlowError.INVALID_USER);
}
return false;
}
if (user == null) {
testInvalidUser(context, user);
return false;
}
if (!enabledUser(context, user))
return false;
context.setUser(user);
return true;
}
}
public class TestAuthenticatorFactory implements AuthenticatorFactory, ConfigurableAuthenticatorFactory {
public static final String PROVIDER_ID = "test-authenticator";
private static final TestAuthenticator SINGLETON = new TestAuthenticator();
#Override
public String getId() {
return PROVIDER_ID;
}
#Override
public Authenticator create(KeycloakSession session) {
return SINGLETON;
}
private static AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = {
AuthenticationExecutionModel.Requirement.REQUIRED, AuthenticationExecutionModel.Requirement.DISABLED };
#Override
public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
return REQUIREMENT_CHOICES;
}
#Override
public boolean isUserSetupAllowed() {
return true;
}
#Override
public boolean isConfigurable() {
return true;
}
#Override
public List<ProviderConfigProperty> getConfigProperties() {
return Collections.emptyList();
}
#Override
public String getHelpText() {
return "Help";
}
#Override
public String getDisplayType() {
return "Test Authenticator";
}
#Override
public String getReferenceCategory() {
return PasswordCredentialModel.TYPE;
}
#Override
public void init(Config.Scope config) {
}
#Override
public void postInit(KeycloakSessionFactory factory) {
}
#Override
public void close() {
}
}
For who wants an example:
https://github.com/mfandre/KeycloakSPI/
This example creates an SPI to user storage... The idea is similar to authenticate the user in LDAP but in this example, we will authenticate in a RestAPI and bring the user to the keycloak!
I was using Hibernate 3, now I'm migrating to Hibernate 5, and some problems occurred (of course).
I have several DAO objects that are stored via Hibernate, and some of them have parameter/field/column "modified" which is automatically updated to current time on each save/update in Hibernate.
This is simple DAO:
#Entity
#Table(name="attachments")
#SequenceGenerator(name="common_attachments_seq", sequenceName="common_attachments_seq", allocationSize=1)
public class AttachmentDAO implements Modifications {
private Long id;
private String name;
private Blob content;
private Date modified;
public AttachmentDAO() {}
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator="common_attachments_seq")
#Column(updatable = false, nullable = false)
public Long getId() {return this.id;}
public void setId(Long id) {this.id=id;}
#Column
public String getName() {return this.name;}
public void setName(String name) {this.name=name;}
#Column
public Blob getContent() {return this.content;}
public void setContent(Blob content) {this.content=content;}
#Column
public Date getModified() {return modified;}
public void setModified(Date date) {modified=date;}
}
This is integrator that sets modifications listener:
public class HibernateIntegrator implements Integrator {
#Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
EventListenerRegistry eventListenerRegistry=serviceRegistry.getService(EventListenerRegistry.class);
ModificationsEventListener mod=new ModificationsEventListener();
eventListenerRegistry.appendListeners(EventType.UPDATE, mod);
eventListenerRegistry.appendListeners(EventType.SAVE, mod);
eventListenerRegistry.appendListeners(EventType.SAVE_UPDATE, mod);
}
#Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
}
}
This is ModificationsEventListener which actually updates "modified" parameter:
public class ModificationsEventListener extends DefaultSaveOrUpdateEventListener {
#Override
public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
Object o=event.getObject();
if (o instanceof Modifications) {
Date now=new Date();
Modifications doc=((Modifications)o);
doc.setModified(now);
}
super.onSaveOrUpdate(event);
}
}
This is the code that saves DAO:
// DiskFileItem currentFile = file uploaded to server - Apache's commons-fileupload-1.3.2.jar
Session hibSession=null;
Transaction tx=null;
try {
SessionFactory sf=AttachmentsSessionFactory.getSessionFactory();
hibSession=sf.openSession();
tx=hibSession.beginTransaction();
AttachmentDAO stub=new AttachmentDAO();
stub.setName(fileName);
long length=currentFile.getSize();
InputStream ins=currentFile.getInputStream(); // this is FileInputStream
LobCreator lobs=Hibernate.getLobCreator(hibSession);
Blob blob=lobs.createBlob(ins, length);
stub.setContent(blob);
hibSession.save(stub);
tx.commit();
ins.close();
currentFile.delete();
} catch (Exception ex) {
if (tx!=null) tx.rollback();
log.error("", ex);
} finally {
if (hibSession!=null&&hibSession.isOpen()) {
hibSession.close();
}
hibSession=null;
}
But this code throws error:
2017-05-12 11:20:38,253 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-127) could not reset reader
2017-05-12 11:20:38,254 ERROR [org.hibernate.internal.SessionImpl] (default task-127) HHH000346: Error during managed flush [could not update: [com.test.persistence.AttachmentDAO#38]]
2017-05-12 11:20:38,267 ERROR [com.gibon.qintegra.servlets.upload.AttachmentsUploadProgressListener] (default task-127) : org.hibernate.exception.GenericJDBCException: could not update: [com.gibon.qintegra.persistence.common.AttachmentDAO#38]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3111)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2961)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3341)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:145)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:582)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:456)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1282)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:465)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2963)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2339)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
at com.gibon.qintegra.servlets.upload.AttachmentsUploadProgressListener.currentFileFinished(AttachmentsUploadProgressListener.java:138)
at com.gibon.qintegra.data4ajax.AttachmentsServant.doServe(AttachmentsServant.java:255)
at com.gibon.qintegra.servlets.Data4Ajax.doProcess(Data4Ajax.java:74)
at com.gibon.qintegra.servlets.Data4Ajax.doPost(Data4Ajax.java:24)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at com.gibon.qintegra.filters.IECompatFilter.doFilter(IECompatFilter.java:44)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at com.gibon.qintegra.filters.SecurityFilter.doFilter(SecurityFilter.java:89)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: could not reset reader
at org.hibernate.engine.jdbc.BlobProxy.resetIfNeeded(BlobProxy.java:75)
at org.hibernate.engine.jdbc.BlobProxy.getUnderlyingStream(BlobProxy.java:64)
at org.hibernate.engine.jdbc.BlobProxy.getStream(BlobProxy.java:60)
at org.hibernate.engine.jdbc.BlobProxy.invoke(BlobProxy.java:101)
at com.sun.proxy.$Proxy118.getBinaryStream(Unknown Source)
at org.postgresql.jdbc.PgPreparedStatement.setBlob(PgPreparedStatement.java:1154)
at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.setBlob(WrappedPreparedStatement.java:1157)
at org.hibernate.type.descriptor.sql.BlobTypeDescriptor$4$1.doBind(BlobTypeDescriptor.java:132)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:74)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:257)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:252)
at org.hibernate.type.AbstractSingleColumnStandardBasicType.nullSafeSet(AbstractSingleColumnStandardBasicType.java:39)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2609)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3038)
... 67 more
sql that hibernate executes is this:
Hibernate:
select
nextval ('common_attachments_seq')
Hibernate:
insert
into
sys_attachments
(content, modified, name, id)
values
(?, ?, ?, ?)
Hibernate:
update
sys_attachments
set
content=?,
modified=?,
name=?,
where
id=?
Apparently problem is that Hibernate inserts record and right after that makes update. FileInputStream doesn't like it because it's closed right after insertion.
When I disable Integrator (updating "modified" field) then it works OK.
Is there any way how to make it work?
I have just seen this:
How to autogenerate created or modified timestamp field?
And it helped me to solve my problem. I had to use EventType.PRE_UPDATE and EventType.PRE_INSERT in Integrator, instead of EventType.SAVE_UPDATE, EventType.SAVE and EventType.UPDATE. And then update values in those listeners like this:
Modifications doc=((Modifications)entity);
doc.setModified(now);
setPropertyState(state, propertyNames, "modified", now);
Where property state setter is here:
private void setPropertyState(Object[] propertyStates, String[] propertyNames, String propertyName, Object propertyState) {
for(int i=0;i<propertyNames.length;i++) {
if (propertyName.equals(propertyNames[i])) {
propertyStates[i]=propertyState;
return;
}
}
}
I have a service rest on my tomcat and it correctly works but when I deploy it on another tomcat server, it throws an exception.
I'm trying to implement a ContainerRequestFilter. And this exception seems caused by the #Context resourceInfo in my authenticationFilter (the class that implements ContainerRequestFilter). But I don't understand why and how to fix it. (I followed this tutorial)
A MultiException has 3 exceptions. They are:
1. java.lang.IllegalStateException: Not inside a request scope.
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of services.AuthentificationFilter errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on services.AuthentificationFilter
org.jvnet.hk2.internal.Collector.throwIfErrors(Collector.java:88)
org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:270)
org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:414)
org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:114)
org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:102)
org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
java.util.concurrent.FutureTask.run(FutureTask.java:266)
org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.run(Cache.java:154)
org.glassfish.hk2.utilities.cache.Cache.compute(Cache.java:199)
org.jvnet.hk2.internal.SingletonContext.findOrCreate(SingletonContext.java:153)
org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2445)
org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:98)
org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:234)
org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:616)
org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:409)
org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:161)
org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:286)
org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:283)
org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:298)
org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:167)
org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:349)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
The code of my authenticationFilter
#Provider
public class AuthentificationFilter implements javax.ws.rs.container.ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION = "Authorization";
private static final String BASIC = "Basic";
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("Essayez de mettre sudo devant votre requete").build();
private static final Response ACCESS_FORBIDDEN = Response.status(Response.Status.FORBIDDEN).entity("You shall not pass !").build();
#Override
public void filter(final ContainerRequestContext context) throws IOException {
Method method = resourceInfo.getResourceMethod();
if(!method.isAnnotationPresent(PermitAll.class)) {
MultivaluedMap<String, String> headers = context.getHeaders();
List<String> authorization = headers.get(AUTHORIZATION);
if(method.isAnnotationPresent(DenyAll.class)) {
context.abortWith(ACCESS_FORBIDDEN);
return;
}else if(authorization == null || authorization.isEmpty()) {
context.abortWith(ACCESS_DENIED);
return;
}
String encodedUserPassword = authorization.get(0).replaceFirst(BASIC + " ", "");
String auth = new String(Base64.getDecoder().decode(encodedUserPassword.getBytes()));;
String[] authTab = auth.split(":");
String username = authTab[0];
String password = authTab[1];
if(method.isAnnotationPresent(RolesAllowed.class)) {
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
if(!isAllowed(username, password, rolesSet)) {
context.abortWith(ACCESS_DENIED);
return;
}
}
}
}
private boolean isAllowed(final String username, final String password, final Set<String> rolesSet)
{
boolean isAllowed = false;
User user;
if((user = new UserMapper().get(username, password)) != null) {
String role = user.getStatus().toString();
if(rolesSet.contains(role))
isAllowed = true;
}
return isAllowed;
}
}
The code of MyApplication.java that registers the filter:
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("services");
register(AuthentificationFilter.class);
}
}
And finally the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Example API</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>services.MyApplication</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Example API</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
What am I doing wrong ?
I finally found the solution. I had to create a class that implements DynamicFeature and register my AuthenticationFilter thanks to a custom constructor.
#Provider
public class AuthenticationDynamicFeature implements DynamicFeature {
#Override
public void configure(ResourceInfo resourceInfo, FeatureContext featureContext) {
featureContext.register(new AuthenticationFilter(resourceInfo));
}
}
And here the custom constructor :
public AuthenticationFilter(ResourceInfo resourceInfo) {
super();
this.resourceInfo = resourceInfo;
}
I tried a lot of other ways, and this one, it's the only one that worked for me.
I have my service as;
#Path("/fileservice/")
public class FileService {
#POST
#Path("/{path}/{filename}/{source}/{client}")
public Response getFilePath(
#PathParam("path") String filePath,
#PathParam("filename") String fileName,
#PathParam("source") String fileSource,
#PathParam("client") String clientId) {
.......
}
and have an jars activator;
#ApplicationPath("rest")
public class JaxRsActivator extends Application{
}
I do not have web.xml.
When i try to access this war from the browser;
i use;
http://localhost:8080/mywar/rest/fileservice
But I'm getting;
6:09:28,215 ERROR [org.jboss.resteasy.resteasy_jaxrs.i18n] (default task-15) RESTEASY002010: Failed to execute: javax.ws.rs.NotFoundException: RESTEASY003210: Could not find resource for full path: http://localhost:8080/mywar/rest/fileservice
at org.jboss.resteasy.core.registry.SegmentNode.match(SegmentNode.java:114)
at org.jboss.resteasy.core.registry.RootNode.match(RootNode.java:43)
at org.jboss.resteasy.core.registry.RootClassNode.match(RootClassNode.java:48)
at
org.jboss.resteasy.core.ResourceMethodRegistry.getResourceInvoker(ResourceMethodRegistry.java:445)
at org.jboss.resteasy.core.SynchronousDispatcher.getInvoker(SynchronousDispatcher.java:257)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:194)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:221)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Can anybody help me what I'm doing wrong?
You can't access that resource from a web browser because you have it set as a POST method. You'd need to use a tool that can send POST requests and provide the /{path}/{filename}/{source}/{client} parameters you have defined.
According to the JAX-RS documentation the #PathParam should be used for GET requests.
For POST requests, one should either consume JSON or JAXB, for full entity beans, or make use of the #FormParam when the intention is to retrieve information that conforms to the encoding specified by HTML forms. This answer, by #D.Shawley, may elucidate you more on this subject.
Taking the code you've posted as basis, the following is a simple working example:
The Base URI for all REST services
#ApplicationPath("/rest")
public class JaxRsActivator extends Application {}
The REST Service
#Path("/fileservice")
public class FileService {
#GET
#Path("/{id}")
#Produces("text/html")
public Response getFileId(#PathParam("id") String fileId) {
System.out.println(fileId);
return Response.ok().entity(fileId).build();
}
#POST
#Path("/file")
#Consumes(MediaType.APPLICATION_XML)
public Response createFile(MyFile myFile) {
System.out.println(myFile.id);
return Response.ok().build();
}
}
The entity
#XmlRootElement(name="file")
public class MyFile {
#XmlElement
public String id;
#XmlElement
public String name;
public MyFile() {}
}
Your WAR pom.xml file should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>war-group</groupId>
<artifactId>war-artifact</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
Then, in order to test your REST service, you could create a simple client that could look like this:
public class FileServiceClient {
public static void main(String[] args) throws Exception {
callRestServiceGET();
callRestServicePOST();
}
protected static void callRestServiceGET() {
URI uri = null;
try {
uri = new URI("http://localhost:8080/war-artifact-0.0.1-SNAPSHOT/rest/fileservice/98765");
} catch (URISyntaxException e) {
e.printStackTrace();
}
Client client = ClientBuilder.newClient();
Response response = client.target(uri).request().get();
System.out.println("GET sended, response status: " + response.getStatus());
}
protected static void callRestServicePOST() {
URI uri = null;
try {
uri = new URI("http://localhost:8080/war-artifact-0.0.1-SNAPSHOT/rest/fileservice/file");
} catch (URISyntaxException e) {
e.printStackTrace();
}
Client client = ClientBuilder.newClient();
String xml = "<file><id>1234567</id><name>abc</name></file>";
Response response = client.target(uri).request().post(Entity.xml(xml));
System.out.println("POST sended, response status: " + response.getStatus());
}
}
I am trying to create REST service using Spring.When I try to access that service it returns proper data but shows -
Exception handling request to /RESTServ/user/2: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:113) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:61) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:240) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:227) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:73) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:146) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:177) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:727) [undertow-core-1.0.15.Final.jar:1.0.15.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_45]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_45]
Caused by: java.lang.NullPointerException
at java.util.ArrayList.<init>(ArrayList.java:177) [rt.jar:1.8.0_45]
at io.undertow.servlet.spec.HttpServletResponseImpl.getHeaders(HttpServletResponseImpl.java:248) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
at org.springframework.http.server.ServletServerHttpResponse$ServletResponseHttpHeaders.get(ServletServerHttpResponse.java:160) [spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.http.server.ServletServerHttpResponse$ServletResponseHttpHeaders.containsKey(ServletServerHttpResponse.java:142) [spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.addContentDispositionHeader(AbstractMessageConverterMethodProcessor.java:349) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:221) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:153) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:165) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:80) [spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.2.3.RELEASE.jar:4.2.3.RELEASE]
... 30 more
Can anyone help me with this problem? I have checked for the data it returns and it is not null by applying breakpoints but still it shows above exception.
EDITED:
Code is:
User.java
package com.rest.service;
public class User {
private int userid;
private String firstName;
private String lastName;
private String email;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User [userid=" + userid + ", firstName=" + firstName
+ ", lastName=" + lastName + ", email=" + email + "]";
}
}
SpringServiceController.java
package com.rest.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.rest.dao.UserService;
import com.rest.service.User;
#RestController
#RequestMapping("/user/")
public class SpringServiceController {
UserService userService = new UserService();
#RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public User getUser(#PathVariable int id) {
User user = userService.getUserById(id);
return user;
}
}
I am getting data from database using UserService.java
DBUtility is class to connect to JDBC
package com.rest.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.rest.service.User;
import com.rest.utility.DBUtility;
public class UserService {
private Connection connection;
public UserService() {
connection = DBUtility.getConnection();
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement
.executeQuery("select * from tblUser");
while (rs.next()) {
User user = new User();
user.setUserid(rs.getInt("userid"));
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setEmail(rs.getString("email"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
public User getUserById(int userId) {
User user = new User();
try {
PreparedStatement preparedStatement = connection.prepareStatement("select * from tblUser where userid=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
user.setUserid(rs.getInt("userid"));
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setEmail(rs.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
}catch (Exception e) {
System.out.println("Exception is: "+e);
e.printStackTrace();
}
return user;
}
}
My web.xml is
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>RESTServ</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
And this is my rest-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<context:component-scan base-package="com.rest.controller" />
<mvc:annotation-driven />
</beans>
PS: One more thing when I delete annotation-driven tag from spring xml file then it works for simple datatype. But it doesn't work where json conversion is required.I am using WildFly - 8.1
this is an issue with WildFly - 8.1 you have to use WildFly - 8.2 or use Jboss 7.
We faced this issue while trial to migrate spring-boot-1.2.2-Final on wildfly 8.1.0-Final to spring-boot-1.3.2-Final on wildfly 8.1.0-Final.
This error does not occur on wildfly 8.2.1-Final, so if you have option tp udate your wildfly version, you should do that.
But if you still have to use wildfly-8.1.0-Final, then you could patch it.
1) get https://github.com/undertow-io/undertow/archive/1.0.15.Final.zip
2) edit io.undertow.servlet.spec.HttpServletResponseImpl located in module servlet
#Override
public String getHeaders(final String name) {
return new ArrayList<String>(exchange.getResponseHeaders().get(name));
}
to
#Override
public Collection<String> getHeaders(final String name) {
final HeaderValues headerValues = exchange.getResponseHeaders().get(name);
if (headerValues != null) {
return new ArrayList<String>(headerValues);
}
return new ArrayList<String>();
}
Add the HeaderValues import:
import io.undertow.util.HeaderValues;
package undertow-servlet with maven and then overwrite
{wildfly-root-directory}/modules/system/layers/base/io/undertow/servlet/main/undertow-servlet-1.0.15.Final.jar
with the file
{undertow-root-directory}/servlet/target/undertow-servlet-1.0.15.Final.jar
This will solve this error.
If your are using maven, add JSON Databinding dependencies specified below in your pom.xml and annotate the User class with #JsonRootName(value = "user"),
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
<version>1.9.13</version>
</dependency>
This may be helpful to those who aren't able to upgrade past Wildfly 8.1.0 in their project to address this problem. Ingvar's answer above of patching the code helped me out a lot, and here is a script that will perform the patch in one command for you (keeping a backup of your previous copy):
https://github.com/ldojo/wf-8.1.0-undertow-1.0.15-patch