Keycloak Authenticator SPI example not working - java

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!

Related

Scope needs to be added to parent class of backing bean otherwise exception javax.faces.application.ViewExpiredException is thrown

I am recently tasked with migrating an existing application (using myfaces 2 and primefaces 5) from Tomcat(JDK 1.7) to JBoss(openJDK 1.8). Ultimately, the app was able to startup and I managed to reach the login page and logged in successfully.
Once logged in, the SidebarBacking class will be called. This SidebarBacking class extends a AbstractBean class (with no scope defined) and injects a AppContextBean for the menu.
package com.myapp.pkg1.web.mbean.common;
#ManagedBean
#SessionScoped
public class SidebarBacking extends AbstractBean
{
....
#ManagedProperty(value="#{appcontextbean}")
AppContextBean appContextBean;
public void setAppContextBean(AppContextBean appContextBean) {
this.appContextBean = appContextBean;
}
public AppContextBean getAppContextBean() {
return appContextBean;
}
#PostConstruct
public void init()
{
MenuParser.getInstance().setParentStyle("ui-state-default");
MenuParser.getInstance().setChildStyle("ui-sidebar-menuitem-child");
root = MenuParser.getInstance().generateMenuTree(authorities(), getAppContextBean().getMenu(),true);
}
....
}
package com.myapp.pkg1.web.mbean.common;
#ManagedBean(name="appcontextbean", eager=true)
#ApplicationScoped
public class AppContextBean implements Serializable
{
...
private Menu menu;
private final String menuPath = "/xml/menu.xml";
public AppContextBean() {
if(menu == null){
try {
this.menu = MenuBuilder.getInstance().loadMenuFromClassPath(menuPath);
} catch (JAXBException e) {
throw new SystemException(e.getMessage(), e.getCause());
} catch (SAXException e) {
throw new SystemException(e.getMessage(), e.getCause());
} catch (IOException e) {
throw new SystemException(e.getMessage(), e.getCause());
}
}
}
public Menu getMenu() {
return menu;
}
public void setMenu(Menu menu) {
this.menu = menu;
}
public String getMenuPath() {
return menuPath;
}
}
package com.myapp.pkg2.web.mbean;
public class AbstractBean implements Serializable
{
...
protected FacesContext facesContext() {
return (FacesContext.getCurrentInstance());
}
protected ExternalContext externalContext() {
if (facesContext() != null)
return facesContext().getExternalContext();
else
return null;
}
protected SecurityContext securityContext(){
return SecurityContextHolder.getContext();
}
protected WebApplicationContext webApplicationContext() {
return FacesContextUtils.getWebApplicationContext(facesContext());
}
protected HttpServletRequest request() {
return (HttpServletRequest) externalContext().getRequest();
}
protected HttpSession session() {
return (HttpSession) externalContext().getSession(false);
}
protected ServletResponse response() {
return (ServletResponse) externalContext().getResponse();
}
protected void forward(String uri) throws ServletException, IOException {
RequestDispatcher dispatcher = request().getRequestDispatcher(uri);
dispatcher.forward(request(), response());
}
protected void redirect(String uri) throws IOException {
externalContext().redirect(uri);
}
protected String getRequestParameter(String key) {
return request().getParameter(key);
}
protected void putSessionAttribute(String key, Object value) {
externalContext().getSessionMap().put(key, value);
}
protected Object getSessionAttribute(String key) {
return externalContext().getSessionMap().get(key);
}
protected Object removeSessionAttribute(String key) {
return externalContext().getSessionMap().remove(key);
}
protected void addInfoMessage(String clientId, String text)
{
facesContext().addMessage(clientId, new FacesMessage(FacesMessage.SEVERITY_INFO, text, text));
}
....
}
On successfully login, I am able to see the side menu and main page with all the table of data retrieved from the database.
The issue is when I click on any of the menu link, it will throw the following exceptions.
940 SEVERE [org.omnifaces.exceptionhandler.FullAjaxExceptionHandler] (default task-1) FullAjaxExceptionHandler: An exception occurred during processing JSF ajax request. Error page '/faces/pages/common/login.xhtml' will be shown.: javax.faces.application.ViewExpiredException: /pages/inbox/myInbox.xhtmlNo saved view state could be found for the view identifier: /pages/inbox/myInbox.xhtml
at org.apache.myfaces.lifecycle.RestoreViewExecutor.execute(RestoreViewExecutor.java:132)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:170)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at com.myapp.pkg2.web.cache.NoCacheFilter.doFilter(NoCacheFilter.java:40)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at com.myapp.pkg2.web.logging.LogFilter.doFilter(LogFilter.java:33)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:64)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:55)
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.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
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.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:53)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:59)
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:269)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
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:1504)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
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)
994 SEVERE [org.omnifaces.exceptionhandler.FullAjaxExceptionHandler] (default task-1) FullAjaxExceptionHandler: An exception occurred during rendering JSF ajax response. Error page '/faces/pages/common/errorPage.xhtml' will be shown.: java.lang.IllegalStateException: Must be called before the start element is closed (attribute 'autocomplete')
....
I read that this indicates that the scope already expired when you access the page.
I am able to resolve the exception if I add a scope to the AbstractBean class, however this will cause a problem.
Whenever any data is updated, although the database is updated successfully, data across the whole website will still not be refreshed to its latest information. The data remain in the last state when they are first retrieved. Only when I logged out and logged in again, then only will the new data be reflected.
package com.myapp.pkg2.web.mbean;
#ManagedBean(name = "abstractBean")
#SessionScoped
public class AbstractBean implements Serializable
{
....
I also tried playing around with a few variation for p:commandButton but with no success
<p:commandButton id="btnAssign" value="Assign" action="#{myInbox.assignWork}" update="#all" />
<p:commandButton id="btnAssign" value="Assign" action="#{myInbox.assignWork}" update="#form" />
<p:commandButton id="btnAssign" value="Assign" action="#{myInbox.assignWork}" update="dataTable" />
<p:commandButton id="btnAssign" value="Assign" action="#{myInbox.assignWork}" update=":form:dataTable" />
<p:commandButton id="btnAssign" value="Assign" action="#{myInbox.assignWork}" process="#all" update="dataTable" />
The problem seem to be due to the scope that was added to the AbstractBean as all the backing beans (e.g. MyInboxBacking) extends the AbstractBean class. Therefore, even if they have their own scope (e.g. #RequestScoped, #ViewScoped), they will not take effect due to the parent class's scope.
As such, how can I remove the scope from the AbstractBean without causing the exception stated or is there any way I can refresh the data even with the #Sessionscoped?

Error receiving while generating excel using servlet

I have created a piece of code for generating and downloading an excel file in servlet. The code is provided below:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String act = request.getParameter("act").toLowerCase();
RequestDispatcher rd = request.getRequestDispatcher("sqleditor.jsp");
try {
if(act.equalsIgnoreCase("exec")) {
String uqry = request.getParameter("isql");
if ( !uqry.isEmpty() ) {
qp = new queryProcessor(uqry);
mp = qp.getResultSet();
request.setAttribute("result",mp);
rd.forward(request, response);
} else {
ERROR_MSG = "Please enter a query";
request.setAttribute("errormsg", ERROR_MSG);
rd.forward(request, response);
}
} else if (act.equalsIgnoreCase("excel")) {
String uqry = request.getParameter("isql");
if ( !uqry.isEmpty() ) {
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=\"" + FILENAME + "\"");
initExcelfile(response.getOutputStream());
} catch (Exception evar1) {
request.setAttribute("errormsg", evar1.getMessage());
rd.forward(request, response);
}
System.out.println("File downloaded at client successfully");
}
}
} catch (AppException evar2) {
request.setAttribute("errormsg", evar2.getmessage());
rd.forward(request, response);
} catch (SQLException evar3) {
request.setAttribute("errormsg", evar3.getMessage());
rd.forward(request, response);
} catch (NullPointerException evar4) {
request.setAttribute("errormsg", evar4.getMessage());
rd.forward(request, response);
} catch (FileNotFoundException evar5) {
request.setAttribute("errormsg", evar5.getMessage());
rd.forward(request, response);
} catch (Exception evar6) {
request.setAttribute("errormsg", evar6.getMessage());
rd.forward(request, response);
}
}
private void initExcelfile(ServletOutputStream outputStream) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Datatypes");
Object[][] datatypes = {
{"Datatype", "Type", "Size(in bytes)"},
{"int", "Primitive", 2},
{"float", "Primitive", 4},
{"double", "Primitive", 8},
{"char", "Primitive", 1},
{"String", "Non-Primitive", "No fixed size"}
};
int rowNum = 0;
System.out.println("Creating excel");
for (Object[] datatype : datatypes) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field : datatype) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
System.out.println("Workbook Created");
try {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
But when I move the initExcelfile() method to a separate class file and invoke the method from there I receive the below error:
ERROR [io.undertow.request] (default task-4) UT005023: Exception handling request to /sqle/sqleditor.jsp: java.lang.RuntimeException: java.lang.IllegalStateException: UT010006: Cannot call getWriter(), getOutputStream() already called
at io.undertow.servlet.spec.RequestDispatcherImpl.forwardImpl(RequestDispatcherImpl.java:245)
at io.undertow.servlet.spec.RequestDispatcherImpl.forwardImplSetup(RequestDispatcherImpl.java:147)
at io.undertow.servlet.spec.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:111)
at com.sqle.RequestController.doPost(RequestController.java:84)
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.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:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: UT010006: Cannot call getWriter(), getOutputStream() already called
at io.undertow.servlet.spec.HttpServletResponseImpl.getWriter(HttpServletResponseImpl.java:355)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:112)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:105)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:183)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:121)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
at org.apache.jsp.sqleditor_jsp._jspService(sqleditor_jsp.java:196)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:433)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:402)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:346)
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.jsp.JspFileHandler.handleRequest(JspFileHandler.java:32)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
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.dispatchRequest(ServletInitialHandler.java:274)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchToPath(ServletInitialHandler.java:209)
at io.undertow.servlet.spec.RequestDispatcherImpl.forwardImpl(RequestDispatcherImpl.java:221)
... 42 more
Could you please let me know what I am missing here due to which I am encountering this error.
Based on the stacktrace, it looks like you are first doing this:
initExcelfile(response.getOutputStream())
which is throwing an exception. Then in the exception handler you appear to be trying to redirect to a JSP to produce an error message. Unfortunately, that is failing because:
the JSP is going to call getWriter() on the response object to find the place to send its output,
you have already called getOutputStream() on the response object, and
you cannot call both getWriter() and getOutputStream() on the same Response object ... or you will get an IllegalStateException!
If you are going to write your spreadsheet directly to the output, you CANNOT redirect to a JSP in the event of failure. Even if the servlet framework allowed it (it doesn't!), you would be liable to get a partial spreadsheet with an error page tacked on the end. The user's web browser wouldn't be able to make sense of that.
There are two alternatives:
Get rid of that attempted redirect in the case where you get an exception while generating the spreadsheet.
Keep the redirect, but change your code so that you prepare and buffer the spreadsheet. Only open the response output stream after you have successfully generated the spreadsheet.
There is also the question of what is causing the exception in the first place. There are no obvious clues that I can see, so you will need to debug that yourself. (For example, you could attach a debugger and set a breakpoint in the exception handler, and look at the caught exception's class, message and callstack.)

#EJB inject does not work in my resteasy web service

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

"could not reset reader" while saving BLOB

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;
}
}
}

how to access the deployed war in wildly v 10?

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());
}
}

Categories

Resources