I am trying to get the database login module to work with my project in the Wildfly 10 container.
I have followed this tutorial: https://www.examsmyantra.com/article/119/javaee/form-based-login-authentication-in-javaee7-with-wildfly-and-mysql
And it's kinda working.
I have an EAR project with an EJB module and a Web module (war). The war is not containing the EJB it's accessing it using the remote lookup.
So when I acces an restricted part of the WAR I am correctly send to the login form (j_security_check).
When I login, I can see the restricted part.
Even when I log in a servet which user I am and check if I have a specif role it works.
Servlet code:
final String username = request.getUserPrincipal().getName();
logger.info("Current username acourding to the WEB: {}", request.getUserPrincipal().getName());
logger.info("User has Role user acourding to the WEB: {}", request.isUserInRole("user"));
logger.info("User has Role admin acourding to the WEB: {}", request.isUserInRole("admin"));
Log:
INFO [com.example.web.servlet.DatasetServlet] (default task-5) Current username acourding to the WEB: user
INFO [com.example.web.servlet.DatasetServlet] (default task-5) User has Role user acourding to the WEB: true
INFO [com.example.web.servlet.DatasetServlet] (default task-5) User has Role admin acourding to the WEB: true
INFO [com.example.business.remote.DatasetEJB] (default task-5) Get active dataset for the user: user
but when I enter the EJB bean like this:
final String dataset = remote.getActiveDataset(); // this is still the servlet (WAR)
EJB:
final String username = this.ejbContext.getCallerPrincipal().getName();
logger.info("Get active dataset for the user: " + username);
logger.info("User has role 'user' {}", this.ejbContext.isCallerInRole("user"));
logger.info("User has role 'admin' {}", this.ejbContext.isCallerInRole("admin"));
I get:
Exception caught: javax.naming.NameNotFoundException: policyRegistration -- service jboss.naming.context.java.policyRegistration
PBOX00326: isCallerInRole processing failed: java.lang.IllegalStateException: PBOX00071: Failed to instantiate interface org.jboss.security.authorization.AuthorizationModule class
Exception:=PBOX00071: Failed to instantiate interface org.jboss.security.authorization.AuthorizationModule
The Full log shows this:
TRACE [org.jboss.security] (default task-5) PBOX00354: Setting security roles ThreadLocal: {}
INFO [com.example.business.remote.DatasetEJB] (default task-5) Get active dataset for the user: user
TRACE [org.jboss.security] (default task-5) PBOX00354: Setting security roles ThreadLocal: {}
2016-09-16 22:53:52,724 DEBUG [org.jboss.security] (default task-5) PBOX00293: Exception caught: javax.naming.NameNotFoundException: policyRegistration -- service jboss.naming.context.java.policyRegistration
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:106)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:207)
at org.jboss.as.naming.InitialContext$DefaultInitialContext.lookup(InitialContext.java:235)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:193)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:189)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at org.jboss.security.plugins.javaee.EJBAuthorizationHelper.getPolicyRegistrationFromJNDI(EJBAuthorizationHelper.java:353)
at org.jboss.security.plugins.javaee.EJBAuthorizationHelper.isCallerInRole(EJBAuthorizationHelper.java:170)
at org.jboss.as.security.service.SimpleSecurityManager.isCallerInRole(SimpleSecurityManager.java:229)
at org.jboss.as.ejb3.component.EJBComponent.isCallerInRole(EJBComponent.java:400)
at org.jboss.as.ejb3.context.EJBContextImpl.isCallerInRole(EJBContextImpl.java:115)
at com.example.business.remote.DatasetEJB.getActiveDataset(DatasetEJB.java:225)
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:497)
...
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)
2016-09-16 22:53:52,727 DEBUG [org.jboss.security] (default task-5) PBOX00282: Failed to instantiate class Database: java.lang.ClassNotFoundException: Database from [Module "deployment.ear.ear.business-ejb-assignment-SNAPSHOT.jar:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at org.jboss.security.plugins.authorization.JBossAuthorizationContext.instantiateModule(JBossAuthorizationContext.java:326)
at org.jboss.security.plugins.authorization.JBossAuthorizationContext.initializeModules(JBossAuthorizationContext.java:205)
at org.jboss.security.plugins.authorization.JBossAuthorizationContext.authorize(JBossAuthorizationContext.java:141)
at org.jboss.security.plugins.JBossAuthorizationManager.internalAuthorization(JBossAuthorizationManager.java:438)
at org.jboss.security.plugins.JBossAuthorizationManager.authorize(JBossAuthorizationManager.java:115)
at org.jboss.security.plugins.javaee.EJBAuthorizationHelper.isCallerInRole(EJBAuthorizationHelper.java:187)
at org.jboss.as.security.service.SimpleSecurityManager.isCallerInRole(SimpleSecurityManager.java:229)
at org.jboss.as.ejb3.component.EJBComponent.isCallerInRole(EJBComponent.java:400)
at org.jboss.as.ejb3.context.EJBContextImpl.isCallerInRole(EJBContextImpl.java:115)
at com.example.business.remote.DatasetEJB.getActiveDataset(DatasetEJB.java:225)
...
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)
2016-09-16 22:53:52,728 DEBUG [org.jboss.security] (default task-5) PBOX00326: isCallerInRole processing failed: java.lang.IllegalStateException: PBOX00071: Failed to instantiate interface org.jboss.security.authorization.AuthorizationModule class
at org.jboss.security.plugins.authorization.JBossAuthorizationContext.instantiateModule(JBossAuthorizationContext.java:336)
at org.jboss.security.plugins.authorization.JBossAuthorizationContext.initializeModules(JBossAuthorizationContext.java:205)
at org.jboss.security.plugins.authorization.JBossAuthorizationContext.authorize(JBossAuthorizationContext.java:141)
at org.jboss.security.plugins.JBossAuthorizationManager.internalAuthorization(JBossAuthorizationManager.java:438)
at org.jboss.security.plugins.JBossAuthorizationManager.authorize(JBossAuthorizationManager.java:115)
at org.jboss.security.plugins.javaee.EJBAuthorizationHelper.isCallerInRole(EJBAuthorizationHelper.java:187)
at org.jboss.as.security.service.SimpleSecurityManager.isCallerInRole(SimpleSecurityManager.java:229)
at org.jboss.as.ejb3.component.EJBComponent.isCallerInRole(EJBComponent.java:400)
at org.jboss.as.ejb3.context.EJBContextImpl.isCallerInRole(EJBContextImpl.java:115)
at com.example.business.remote.DatasetEJB.getActiveDataset(DatasetEJB.java:225)
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:497)
...
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)
TRACE [org.jboss.security.audit] (default task-5) [Error]Resource:=[org.jboss.security.authorization.resources.EJBResource:contextMap={roleRefPermissionCheck=true, roleName=user, policyRegistration=null}:method=null:ejbMethodInterface=null:ejbName=DatasetEJB:ejbPrincipal=org.wildfly.extension.undertow.security.AccountImpl$AccountPrincipal#36ebcb:MethodRoles=null:securityRoleReferences=[]:callerSubject=Subject:
Principal: user
Principal: Roles(members:user,admin)
Principal: CallerPrincipal(members:user)
:callerRunAs=null:callerRunAs=null:ejbRestrictionEnforcement=false:ejbVersion=2.0];Action=authorization;roleRefPermissionCheck=true;Exception:=PBOX00071: Failed to instantiate interface org.jboss.security.authorization.AuthorizationModule class;roleName=user;Source=org.jboss.security.plugins.javaee.EJBAuthorizationHelper;policyRegistration=null;
TRACE [org.jboss.security] (default task-5) PBOX00354: Setting security roles ThreadLocal: {}
INFO [com.example.business.remote.DatasetEJB] (default task-5) User has role 'user' false
And I don't understand why.
My guess is that the security domain is correctly configured, because otherwise the war would not be working. So it must have something to do with a missing config in the EJB.
Some additional info:
In the standalone.xml I have these settings:
<subsystem xmlns="urn:jboss:domain:ejb3:4.0">
...
<default-security-domain value="jdbcejbrick"/>
<default-missing-method-permissions-deny-access value="false"/>
<log-system-exceptions value="true"/>
</subsystem>
And
<security-domain name="jdbcejbrick" cache-type="default">
<authentication>
<login-module code="Database" flag="required">
<module-option name="dsJndiName" value="java:jboss/datasources/poc-ejb-alg"/>
<module-option name="rolesQuery" value="SELECT a.NAME, 'Roles' FROM AUTHORIZATIONS a LEFT JOIN AUTHORIZATION_USER au on au.AUTHORIZATION_ID = a.ID LEFT JOIN AUTHORIZATION_USER_GROUP aug on aug.AUTHORIZATION_ID = a.ID LEFT JOIN USER_GROUPS ug on aug.GROUP_ID = ug.ID LEFT JOIN USER_USER_GROUP uug on ug.ID = uug.GROUP_ID LEFT JOIN USERS u on (au.USER_ID = u.ID) or (uug.USER_ID = u.ID) WHERE u.NAME=?"/>
<module-option name="principalsQuery" value="select PASSWORD from USERS where NAME=?"/>
</login-module>
</authentication>
<authorization>
<policy-module code="Database" flag="required">
<module-option name="dsJndiName" value="java:jboss/datasources/poc-ejb-alg"/>
<module-option name="rolesQuery" value="SELECT a.NAME, 'Roles' FROM AUTHORIZATIONS a LEFT JOIN AUTHORIZATION_USER au on au.AUTHORIZATION_ID = a.ID LEFT JOIN AUTHORIZATION_USER_GROUP aug on aug.AUTHORIZATION_ID = a.ID LEFT JOIN USER_GROUPS ug on aug.GROUP_ID = ug.ID LEFT JOIN USER_USER_GROUP uug on ug.ID = uug.GROUP_ID LEFT JOIN USERS u on (au.USER_ID = u.ID) or (uug.USER_ID = u.ID) WHERE u.NAME=?"/>
<module-option name="principalsQuery" value="select PASSWORD from USERS where NAME=?"/>
</policy-module>
</authorization>
</security-domain>
I have a jboss-ejb3.xml in src/main/resources/META-INF of the EJB
<?xml version="1.0"?>
<jboss:ejb-jar xmlns:jboss="http://www.jboss.com/xml/ns/javaee" xmlns:sec="urn:security" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-ejb3-2_0.xsd
http://java.sun.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-ejb3-spec-2_0.xsd
urn:security urn:security"
version="3.1" impl-version="2.0">
<assembly-descriptor>
<sec:security>
<ejb-name>*</ejb-name>
<sec:security-domain>jdbcejbrick</sec:security-domain>
</sec:security>
</assembly-descriptor>
</jboss:ejb-jar>
I have an ejb-jar.xml in src/main/resources/META-INF of the EJB
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar>
<assembly-descriptor>
<security-role>
<role-name>admin</role-name>
</security-role>
<security-role>
<role-name>user</role-name>
</security-role>
</assembly-descriptor>
</ejb-jar>
I am feeling that I am real close, so please help.
Okay I was rubber ducking here :S
While explaining the problem I realised that it was a policy problem because username was already okay in the EJB
And the error "Failed to instantiate class Database: java.lang.ClassNotFoundException" gave me an idea to look at the documentation for policy-module
https://docs.jboss.org/author/display/WFLY10/Security+subsystem+configuration
<policy-module code="PermitAll" flag="required">
<module-option name="dsJndiName" value="java:jboss/datasources/poc-ejb-alg"/>
<module-option name="rolesQuery" value="SELECT a.NAME, 'Roles' FROM AUTHORIZATIONS a LEFT JOIN AUTHORIZATION_USER au on au.AUTHORIZATION_ID = a.ID LEFT JOIN AUTHORIZATION_USER_GROUP aug on aug.AUTHORIZATION_ID = a.ID LEFT JOIN USER_GROUPS ug on aug.GROUP_ID = ug.ID LEFT JOIN USER_USER_GROUP uug on ug.ID = uug.GROUP_ID LEFT JOIN USERS u on (au.USER_ID = u.ID) or (uug.USER_ID = u.ID) WHERE u.NAME=?"/>
<module-option name="principalsQuery" value="select PASSWORD from USERS where NAME=?"/>
</policy-module>
If a Wildfly developer ever read this please validate the standalone config and log a message when something like happens! :D
Hopes this ever helps someone!
Related
Trying to log channel error and using a retry policy, i log two exception stacktrace instead of only one.
Channel configuration :
<bean id="retryInterceptor" class="org.springframework.amqp.rabbit.config.StatelessRetryOperationsInterceptorFactoryBean">
<property name="messageRecoverer" ref="rejectAndDontRequeueRecoverer"/>
<property name="retryOperations" ref="retryTemplate" />
</bean>
<bean id="rejectAndDontRequeueRecoverer" class="org.springframework.amqp.rabbit.retry.RejectAndDontRequeueRecoverer"/>
<!-- Configuration du retry -->
<bean id="retryTemplate" class="org.springframework.retry.support.RetryTemplate">
<property name="backOffPolicy">
<bean class="org.springframework.retry.backoff.ExponentialBackOffPolicy">
<!-- Intervalle de temps en millisecondes entre deux tentatives -->
<property name="initialInterval" value="2000" />
</bean>
</property>
<property name="retryPolicy">
<bean class="org.springframework.retry.policy.SimpleRetryPolicy">
<!-- Nombre de retry max -->
<property name="maxAttempts" value="3" />
</bean>
</property>
</bean>
<bean id="log" class="com.logger.Logger"/>
<!-- Logger -->
<int:channel id="one" ></int:channel>
<int:channel id="error1" ></int:channel>
<int:publish-subscribe-channel id="processChannel1" />
<int:logging-channel-adapter channel="processChannel1" logger-name="log1" level="ERROR" expression="payload.message"/>
<int:service-activator input-channel="processChannel1" ref="log" output-channel="error1" />
<!-- Source -->
<rabbit:connection-factory id="connectionFactory" username="guest" password="guest" addresses="XX.XX.XX.XX:5672" cache-mode="CONNECTION" virtual-host="/" />
<int-amqp:inbound-channel-adapter channel="one" id="inboundChannelAdapter1" queue-names="myqueue" connection-factory="connectionFactory" error-channel="processChannel1" channel-transacted="true" advice-chain="retryInterceptor" />
<!-- Destination -->
<rabbit:connection-factory id="connectionFactoryRmqDest" username="guest" password="guest111" addresses="YY.YY.YY.YY:5672" cache-mode="CONNECTION" connection-cache-size="50" virtual-host="/" />
<rabbit:template id="rabbitTemplateRmqDest" connection-factory="connectionFactoryRmqDest" />
<int-amqp:outbound-channel-adapter channel="one" id="outboundChannelAdapter1" routing-key="keyMyQueue" exchange-name="direct.exchange" amqp-template="rabbitTemplateRmqDest" default-delivery-mode="PERSISTENT"/>
Logger.java
package com.logger;
public class Logger {
public Message<?> log(Message<?> message) {
System.out.println("*************************************");
throw new AmqpException("Error on channel");
}
}
Log file :
2018-03-12 16:34:43.008 [(inner bean)#160e9f2e-1] ERROR log1 - error occurred in message handler [org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint#0]; nested exception is org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
2018-03-12 16:34:43.021 [(inner bean)#160e9f2e-1] ERROR log1 - Message conversion failed
2018-03-12 16:34:45.181 [(inner bean)#160e9f2e-1] ERROR log1 - error occurred in message handler [org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint#0]; nested exception is org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
2018-03-12 16:34:45.182 [(inner bean)#160e9f2e-1] ERROR log1 - Message conversion failed
2018-03-12 16:34:49.345 [(inner bean)#160e9f2e-1] ERROR log1 - error occurred in message handler [org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint#0]; nested exception is org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
2018-03-12 16:34:49.346 [(inner bean)#160e9f2e-1] ERROR log1 - Message conversion failed
Removing the expression attributes, stack traces are (just one attempt on the 3 retries):
2018-03-12 17:24:03.303 [(inner bean)#76e1e924-1] ERROR log1 - org.springframework.messaging.MessageHandlingException: error occurred in message handler [org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint#0]; nested exception is org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile., failedMessage=GenericMessage [payload=byte[20], headers={timestamp=1520871843104, id=7c9f713f-90a1-2720-60e4-a0e33ef98ecb, amqp_receivedRoutingKey=myqueue, amqp_consumerQueue=myqueue, amqp_consumerTag=amq.ctag-ENdQ-j6xD1LRXDxGr_iJuQ, amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_redelivered=false, amqp_deliveryTag=1}]
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:139)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:89)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:425)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:375)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:188)
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter.access$1100(AmqpInboundChannelAdapter.java:56)
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener.processMessage(AmqpInboundChannelAdapter.java:246)
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener.onMessage(AmqpInboundChannelAdapter.java:203)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:848)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:771)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:102)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:198)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.retry.interceptor.RetryOperationsInterceptor$1.doWithRetry(RetryOperationsInterceptor.java:74)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:276)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:172)
at org.springframework.retry.interceptor.RetryOperationsInterceptor.invoke(RetryOperationsInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy9.invokeListener(Unknown Source)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1311)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:752)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1254)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1224)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1600(SimpleMessageListenerContainer.java:102)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1470)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:65)
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:368)
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:603)
at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1430)
at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1411)
at org.springframework.amqp.rabbit.core.RabbitTemplate.send(RabbitTemplate.java:712)
at org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint.send(AmqpOutboundEndpoint.java:134)
at org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint.handleRequestMessage(AmqpOutboundEndpoint.java:122)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
... 38 more
Caused by: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:342)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:909)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:859)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:799)
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:352)
... 46 more
2018-03-12 17:24:03.314 [(inner bean)#76e1e924-1] ERROR log1 - org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Message conversion failed
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener.onMessage(AmqpInboundChannelAdapter.java:223)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:848)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:771)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:102)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:198)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.retry.interceptor.RetryOperationsInterceptor$1.doWithRetry(RetryOperationsInterceptor.java:74)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:276)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:172)
at org.springframework.retry.interceptor.RetryOperationsInterceptor.invoke(RetryOperationsInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy9.invokeListener(Unknown Source)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1311)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:752)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1254)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1224)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1600(SimpleMessageListenerContainer.java:102)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1470)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.messaging.MessageHandlingException: nested exception is org.springframework.amqp.AmqpException: Erreur sur le channel, failedMessage=EnhancedErrorMessage [payload=org.springframework.messaging.MessageHandlingException: error occurred in message handler [org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint#0]; nested exception is org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile., failedMessage=GenericMessage [payload=byte[20], headers={timestamp=1520871843104, id=7c9f713f-90a1-2720-60e4-a0e33ef98ecb, amqp_receivedRoutingKey=myqueue, amqp_consumerQueue=myqueue, amqp_consumerTag=amq.ctag-ENdQ-j6xD1LRXDxGr_iJuQ, amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_redelivered=false, amqp_deliveryTag=1}], headers={timestamp=1520871843291, id=dbde6a9f-3c26-086f-53a1-7c98482efcce, amqp_raw_message=(Body:'[B#56360d58(byte[20])' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=null, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=NON_PERSISTENT, expiration=null, priority=null, redelivered=false, receivedExchange=, receivedRoutingKey=myqueue, receivedDelay=null, deliveryTag=1, messageCount=0, consumerTag=amq.ctag-ENdQ-j6xD1LRXDxGr_iJuQ, consumerQueue=myqueue])}] for original GenericMessage [payload=byte[20], headers={timestamp=1520871843104, id=7c9f713f-90a1-2720-60e4-a0e33ef98ecb, amqp_receivedRoutingKey=myqueue, amqp_consumerQueue=myqueue, amqp_consumerTag=amq.ctag-ENdQ-j6xD1LRXDxGr_iJuQ, amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_redelivered=false, amqp_deliveryTag=1}]
at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:96)
at org.springframework.integration.handler.ServiceActivatingHandler.handleRequestMessage(ServiceActivatingHandler.java:89)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
at org.springframework.integration.dispatcher.BroadcastingDispatcher.invokeHandler(BroadcastingDispatcher.java:236)
at org.springframework.integration.dispatcher.BroadcastingDispatcher.dispatch(BroadcastingDispatcher.java:185)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:89)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:425)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:375)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
at org.springframework.integration.endpoint.MessageProducerSupport.sendErrorMessageIfNecessary(MessageProducerSupport.java:207)
at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:191)
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter.access$1100(AmqpInboundChannelAdapter.java:56)
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener.processMessage(AmqpInboundChannelAdapter.java:246)
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener.onMessage(AmqpInboundChannelAdapter.java:203)
... 25 more
Caused by: org.springframework.amqp.AmqpException: Erreur sur le channel
at com.logger.Logger.log(Logger.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:117)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:129)
at org.springframework.expression.spel.ast.MethodReference.access$000(MethodReference.java:49)
at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:347)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88)
at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:132)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:360)
at org.springframework.integration.util.AbstractExpressionEvaluator.evaluateExpression(AbstractExpressionEvaluator.java:169)
at org.springframework.integration.util.MessagingMethodInvokerHelper.processInternal(MessagingMethodInvokerHelper.java:319)
at org.springframework.integration.util.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:155)
at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:93)
... 41 more
In the log file i have 3 attemps for transfer the message. => Retry is ok
I would like to have only one stacktrace? What the mean of the "Message conversion failed"? How can i prevent it?
Is there a way to test if the cause of an exception is empty or null? I would like to use "payload.cause.message" in the expression?
Thanks for your help,
Regards
Eric
The first log message comes from the <int:logging-channel-adapter> just because you use an error-channel="processChannel1" on the <int-amqp:outbound-channel-adapter>.
The second one comes from the AbstractMessageListenerContainer because your Logger doesn't log message, but does exactly this:
throw new AmqpException("Error on channel");
So, when we do in the AmqpInboundChannelAdapter.Listener this:
getMessagingTemplate().send(getErrorChannel(), buildErrorMessage(null,
new ListenerExecutionFailedException("Message conversion failed", e, message)));
Send error message to the error channel, you just re-throw an exception from the to the top-level AMQP listener and that one logs it one more time.
You should consider do not re-throw an exception from your Logger component, or don't use use one more <int:logging-channel-adapter> subscriber, or just don't use error-channel approach at all!
For the payload.cause.message expression you should use a SpEL ternary operator : payload.cause != null ? payload.cause.message : payload.message
UPDATE
OK. I see what's going on.
We send an exception to the errorChannel during MessageProducerSupport.sendMessage() process:
try {
this.messagingTemplate.send(getOutputChannel(), message);
}
catch (RuntimeException e) {
if (!sendErrorMessageIfNecessary(message, e)) {
throw e;
}
}
And since you have one more subscriber to throw a fresh exception (or just re-throw), that sendErrorMessageIfNecessary() finishes with a bubbled exception.
This one come to the catch (RuntimeException e) { of the AmqpInboundChannelAdapter.Listener.onMessage() like mentioned before. And a new ErrorMessage is sent to the errorChannel. That's how you see that one more logged message. But since the second subscriber re-throws an exception, that's how it comes back to the listener container and initiate retries. And that's how you see a stack trace only once, after all the retry attempts. However I can guess that it is already a wrong stack trace, because you would like to see the real reason of the sending to the AMQP problem.
What I suggest here for you as a solution is like this:
No error-channel on the <int-amqp:inbound-channel-adapter>
No second subscriber to the processChannel1 - the existing <int:logging-channel-adapter> is enough.
You configure ExpressionEvaluatingRequestHandlerAdvice with the failureChannel to the processChannel1 and onFailureExpression to the #this
Use this ExpressionEvaluatingRequestHandlerAdvice as a <request-handler-advice-chain> reference for the <int-amqp:outbound-channel-adapter>
This way you'll get logs on each retry and according the trapException = false, a real exception will be re-thrown to the listener cotnainer for retry.
I am trying to sftp file with Spring integration using a maven web projecy
Need a polling facility. If I am starting the SftpInbound.java, the polling is working. Need to have the polling at server start up.
The content of java file and configuration
SftpInbound.java
package com.myproj.integration.bsy.sftp;
import java.io.File;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.endpoint.SourcePollingChannelAdapter;
import org.springframework.integration.file.remote.RemoteFileTemplate;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.PollableChannel;
import org.springframework.scheduling.annotation.Scheduled;
import com.myproj.integration.bsy.sftp.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
public class SftpInboundReceive {
#Scheduled(fixedRate=5000)
public void inboundSftpPoll(){
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("/META-INF/spring/integration/sftp/SftpInboundReceive-context.xml", this.getClass());
RemoteFileTemplate<LsEntry> template = null;
String file1 = "a.txt";
String file2 = "b.txt";
String file3 = "c.bar";
new File("local-dir", file1).delete();
new File("local-dir", file2).delete();
try {
PollableChannel localFileChannel = context.getBean("receiveChannel", PollableChannel.class);
#SuppressWarnings("unchecked")
SessionFactory<LsEntry> sessionFactory = context.getBean(CachingSessionFactory.class);
template = new RemoteFileTemplate<LsEntry>(sessionFactory);
System.out.println("here 1" +template);
SourcePollingChannelAdapter adapter = context.getBean("sftpInbondAdapter",SourcePollingChannelAdapter.class);
adapter.start();
Message<?> received = localFileChannel.receive();
System.out.println("Received first file message 1: " + received);
received = localFileChannel.receive();
System.out.println("Received second file message: " + received);
received = localFileChannel.receive(1000);
System.out.println("Third file was received as expected" +received);
}catch(Exception e){
e.printStackTrace();
}
finally {
SftpUtils.cleanUp(template, file1, file2, file3);
//context.close();
}
}
public static void main(String args[])
{
SftpInboundReceive oInboundReceiveSample = new SftpInboundReceive();
oInboundReceiveSample.inboundSftpPoll();
}
}
The xml file SftpInboundReceive-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-sftp="http://www.springframework.org/schema/integration/sftp"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-4.1.xsd
http://www.springframework.org/schema/integration/sftp http://www.springframework.org/schema/integration/sftp/spring-integration-sftp-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- <import resource="SftpSampleCommon.xml"/> -->
<context:property-placeholder order="1"
location="classpath:/sftpuser.properties" ignore-unresolvable="true"/>
<bean id="sftpSessionFactory"
class="org.springframework.integration.file.remote.session.CachingSessionFactory">
<constructor-arg ref="defaultSftpSessionFactory" />
</bean>
<!-- host=xxx.xx.128.143 port=22 username=xxxuser passphrase= private.keyfile=classpath:META-INF/keys/sftp_rsa -->
<bean id="defaultSftpSessionFactory"
class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
<property name="host" value="${sftp.host}" />
<property name="port" value="${sftp.port}" />
<property name="user" value="${sftp.username}" />
<property name="privateKey" value="${private.keyfile}" />
<property name="privateKeyPassphrase" value="${passphrase}" />
</bean>
<!-- username & password from property file... tested <bean id="defaultSftpSessionFactory"
class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
<property name="host" value="${sftp.host}"/> <property name="port" value="${sftp.port}"/>
<property name="user" value="${sftp.username}"/> <property name="password"
value="${sftp.password}"/> </bean> -->
<!-- hardcoded, username & password... tested <bean id="defaultSftpSessionFactory"
class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
<property name="host" value="xxx.xx.128.143"/> <property name="port" value="22"/>
<property name="user" value="xxxuser"/> <property name="password" value="xxxuser#123"/>
</bean> -->
<!-- Inbound channel adapter for SFTP call . with poll facility -->
<int-sftp:inbound-channel-adapter id="sftpInbondAdapter"
auto-startup="true" channel="receiveChannel" session-factory="sftpSessionFactory"
local-directory="file:/target/foo" remote-directory="${sftp.inboundremotedir}"
auto-create-local-directory="true" delete-remote-files="false"
filename-pattern="*.txt">
<int:poller fixed-rate="100000" max-messages-per-poll="1" />
</int-sftp:inbound-channel-adapter>
<int:channel id="receiveChannel">
<int:queue />
</int:channel>
</beans>
STackTrace
p-bio-8080-exec-3][org.springframework.security.web.FilterChainProxy] / at position 5 of 12 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter'
16:02:58.368 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.FilterChainProxy] / at position 6 of 12 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
16:02:58.368 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.FilterChainProxy] / at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
16:02:58.368 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.FilterChainProxy] / at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
16:02:58.370 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.FilterChainProxy] / at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
16:02:58.371 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.authentication.AnonymousAuthenticationFilter] Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
16:02:58.371 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.FilterChainProxy] / at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
16:02:58.371 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.FilterChainProxy] / at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
16:02:58.371 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.FilterChainProxy] / at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
16:02:58.371 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.util.matcher.AntPathRequestMatcher] Checking match of request : '/'; against '/services/employee/*'
16:02:58.371 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.access.intercept.FilterSecurityInterceptor] Public object - authentication not attempted
16:02:58.371 TRACE [http-bio-8080-exec-3][org.springframework.web.context.support.XmlWebApplicationContext] Publishing event in Root WebApplicationContext: org.springframework.security.access.event.PublicInvocationEvent[source=FilterInvocation: URL: /]
16:02:58.372 DEBUG [http-bio-8080-exec-3][org.springframework.beans.factory.support.DefaultListableBeanFactory] Returning cached instance of singleton bean 'org.springframework.integration.internalMessagingAnnotationPostProcessor'
16:02:58.372 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.FilterChainProxy] / reached end of additional filter chain; proceeding with original chain
16:02:58.375 TRACE [http-bio-8080-exec-3][org.springframework.web.servlet.DispatcherServlet] Bound request context to thread: SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.context.HttpSessionSecurityContextRepository$Servlet3SaveToSessionRequestWrapper#1b0b34e]
16:02:58.376 DEBUG [http-bio-8080-exec-3][org.springframework.web.servlet.DispatcherServlet] DispatcherServlet with name 'Information Exchange Gateway Integration' processing GET request for [/DummyDataIntg/]
16:02:58.376 TRACE [http-bio-8080-exec-3][org.springframework.web.servlet.DispatcherServlet] Testing handler map [org.springframework.integration.http.inbound.IntegrationRequestMappingHandlerMapping#cdca7] in DispatcherServlet with name 'Information Exchange Gateway Integration'
16:02:58.378 WARN [http-bio-8080-exec-3][org.springframework.web.servlet.PageNotFound] No mapping found for HTTP request with URI [/DummyDataIntg/] in DispatcherServlet with name 'Information Exchange Gateway Integration'
16:02:58.378 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.context.HttpSessionSecurityContextRepository] SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
16:02:58.378 TRACE [http-bio-8080-exec-3][org.springframework.web.servlet.DispatcherServlet] Cleared thread-bound request context: SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.context.HttpSessionSecurityContextRepository$Servlet3SaveToSessionRequestWrapper#1b0b34e]
16:02:58.378 DEBUG [http-bio-8080-exec-3][org.springframework.web.servlet.DispatcherServlet] Successfully completed request
16:02:58.378 TRACE [http-bio-8080-exec-3][org.springframework.web.context.support.XmlWebApplicationContext] Publishing event in WebApplicationContext for namespace 'Information Exchange Gateway Integration-servlet': ServletRequestHandledEvent: url=[/DummyDataIntg/]; client=[127.0.0.1]; method=[GET]; servlet=[Information Exchange Gateway Integration]; session=[null]; user=[null]; time=[6ms]; status=[OK]
16:02:58.378 TRACE [http-bio-8080-exec-3][org.springframework.web.context.support.XmlWebApplicationContext] Publishing event in Root WebApplicationContext: ServletRequestHandledEvent: url=[/DummyDataIntg/]; client=[127.0.0.1]; method=[GET]; servlet=[Information Exchange Gateway Integration]; session=[null]; user=[null]; time=[6ms]; status=[OK]
16:02:58.378 DEBUG [http-bio-8080-exec-3][org.springframework.beans.factory.support.DefaultListableBeanFactory] Returning cached instance of singleton bean 'org.springframework.integration.internalMessagingAnnotationPostProcessor'
16:02:58.378 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.access.ExceptionTranslationFilter] Chain processed normally
16:02:58.378 DEBUG [http-bio-8080-exec-3][org.springframework.security.web.context.SecurityContextPersistenceFilter] SecurityContextHolder now cleared, as request processing completed
16:04:37.403 INFO [task-scheduler-4][org.springframework.integration.file.FileReadingMessageSource] Created message: [GenericMessage [payload=\target\foo\b.txt, headers={timestamp=1420540477403, id=f8c32928-411b-99b7-f4a0-0dd1b119fc44}]]
16:04:37.403 ERROR [task-scheduler-4][org.springframework.integration.handler.LoggingHandler] \target\foo\b.txt
16:06:17.403 INFO [task-scheduler-9][org.springframework.integration.file.FileReadingMessageSource] Created message: [GenericMessage [payload=\target\foo\brjb.txt, headers={timestamp=1420540577403, id=061634bf-0562-962b-e583-53a302cdb0d4}]]
16:06:17.403 ERROR [task-scheduler-9][org.springframework.integration.handler.LoggingHandler] \target\foo\brjb.txt
16:07:57.403 INFO [task-scheduler-10][org.springframework.integration.file.FileReadingMessageSource] Created message: [GenericMessage [payload=\target\foo\d.txt, headers={timestamp=1420540677403, id=abea1188-fc5a-15b0-c40c-73ea686a88c0}]]
16:07:57.403 ERROR [task-scheduler-10][org.springframework.integration.handler.LoggingHandler] \target\foo\d.txt
16:09:37.403 INFO [task-scheduler-4][org.springframework.integration.file.FileReadingMessageSource] Created message: [GenericMessage [payload=\target\foo\g.txt, headers={timestamp=1420540777403, id=461a8e48-6ebf-5d1c-ab3f-ce28e54e00b8}]]
16:09:37.403 ERROR [task-scheduler-4][org.springframework.integration.handler.LoggingHandler] \target\foo\g.txt
16:11:17.403 INFO [task-scheduler-3][org.springframework.integration.file.FileReadingMessageSource] Created message: [GenericMessage [payload=\target\foo\h.txt, headers={timestamp=1420540877403, id=4cbeeceb-5949-0e1c-1492-45ec17172480}]]
16:11:17.403 ERROR [task-scheduler-3][org.springframework.integration.handler.LoggingHandler] \target\foo\h.txt
16:12:57.403 INFO [task-scheduler-9][org.springframework.integration.file.FileReadingMessageSource] Created message: [GenericMessage [payload=\target\foo\p.txt, headers={timestamp=1420540977403, id=3767b4bb-4de4-3178-f693-5ac0bd94a766}]]
16:12:57.403 ERROR [task-scheduler-9][org.springframework.integration.handler.LoggingHandler] \target\foo\p.txt
16:14:37.403 INFO [task-scheduler-6][org.springframework.integration.file.FileReadingMessageSource] Created message: [GenericMessage [payload=\target\foo\wiki.txt, headers={timestamp=1420541077403, id=bd3d0082-9788-fc31-1596-ab7a79186c17}]]
16:14:37.403 ERROR [task-scheduler-6][org.springframework.integration.handler.LoggingHandler] \target\foo\wiki.txt
error log in java file**strong text**
20:25:52.807 ERROR [task-scheduler-1][org.springframework.integration.handler.LoggingHandler] org.springframework.messaging.MessagingException: Problem occurred while synchronizing remote to local directory; nested exception is org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is org.springframework.core.NestedIOException: Failed to list files; nested exception is 2: No such file
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.synchronizeToLocalDirectory(AbstractInboundFileSynchronizer.java:209)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizingMessageSource.doReceive(AbstractInboundFileSynchronizingMessageSource.java:167)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizingMessageSource.doReceive(AbstractInboundFileSynchronizingMessageSource.java:57)
at org.springframework.integration.endpoint.AbstractMessageSource.receive(AbstractMessageSource.java:64)
at org.springframework.integration.endpoint.SourcePollingChannelAdapter.receiveMessage(SourcePollingChannelAdapter.java:124)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:192)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:55)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:149)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:146)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:298)
at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:52)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:49)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:292)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is org.springframework.core.NestedIOException: Failed to list files; nested exception is 2: No such file
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:343)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer.synchronizeToLocalDirectory(AbstractInboundFileSynchronizer.java:167)
... 22 more
Caused by: org.springframework.core.NestedIOException: Failed to list files; nested exception is 2: No such file
at org.springframework.integration.sftp.session.SftpSession.list(SftpSession.java:103)
at org.springframework.integration.sftp.session.SftpSession.list(SftpSession.java:50)
at org.springframework.integration.file.remote.session.CachingSessionFactory$CachedSession.list(CachingSessionFactory.java:205)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer$1.doInSession(AbstractInboundFileSynchronizer.java:171)
at org.springframework.integration.file.remote.synchronizer.AbstractInboundFileSynchronizer$1.doInSession(AbstractInboundFileSynchronizer.java:167)
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:334)
... 23 more
Caused by: 2: No such file
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2198)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2215)
at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1565)
at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1526)
at org.springframework.integration.sftp.session.SftpSession.list(SftpSession.java:91)
... 28 more
You need to take a look how to start Spring Context from Web application using web.xml or WebApplicationInitializer for Servlet 3 environment. In this case the SftpInboundReceive-context.xml can be a part of common ApplicationContext and the polling facility (<int-sftp:inbound-channel-adapter>) will start automatically on application startup, which is caused on server start, when the last one see the web context of your application.
Please, read more docs for Spring Framework: http://projects.spring.io/spring-framework/
Spring Integration is just an EIP extension and follow with the same configuration and lifecycle rules.
I see that you just use the SFTP sample from Spring Intregration. You can found there samples for Tomcat and for Spring Boot as well.
On my way to migrate from JBoss 7 to WildFly, I encountered another problem. When calling an rest service which is protected by #RolesAllowed("ADMIN") I get the following error:
13:46:44,359 ERROR [org.jboss.as.ejb3.invocation] (default task-1) JBAS014134: EJB Invocation failed on component TestFacade for method public java.lang.String net.dice.facade.TestFacade.generateTestdata(): javax.ejb.EJBAccessException: JBAS013323: Invalid User
at org.jboss.as.ejb3.security.SecurityContextInterceptor$1.run(SecurityContextInterceptor.java:66) [wildfly-ejb3-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.as.ejb3.security.SecurityContextInterceptor$1.run(SecurityContextInterceptor.java:46) [wildfly-ejb3-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.as.ejb3.security.SecurityContextInterceptor.processInvocation(SecurityContextInterceptor.java:92) [wildfly-ejb3-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64) [wildfly-ejb3-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:59) [wildfly-ejb3-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:55) [wildfly-ejb3-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.ContextClassLoaderInterceptor.processInvocation(ContextClassLoaderInterceptor.java:64)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:326)
at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:448)
at org.jboss.invocation.AccessCheckingInterceptor.processInvocation(AccessCheckingInterceptor.java:61)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:326)
at org.jboss.invocation.PrivilegedWithCombinerInterceptor.processInvocation(PrivilegedWithCombinerInterceptor.java:80)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:185)
at org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:182)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
at org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:73)
at net.dice.facade.TestFacade$$$view3.generateTestdata(Unknown Source) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_51]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_51]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_51]
at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_51]
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:137) [resteasy-jaxrs-3.0.6.Final.jar:]
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:280) [resteasy-jaxrs-3.0.6.Final.jar:]
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:234) [resteasy-jaxrs-3.0.6.Final.jar:]
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:221) [resteasy-jaxrs-3.0.6.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:356) [resteasy-jaxrs-3.0.6.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:179) [resteasy-jaxrs-3.0.6.Final.jar:]
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220) [resteasy-jaxrs-3.0.6.Final.jar:]
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56) [resteasy-jaxrs-3.0.6.Final.jar:]
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51) [resteasy-jaxrs-3.0.6.Final.jar:]
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.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:130) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at net.dice.filter.DiceFilter.doFilter(DiceFilter.java:48) [classes:]
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:56) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:85) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.0.0.Final.jar:1.0.0.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.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:113) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.security.handlers.AuthenticationCallHandler.handleRequest(AuthenticationCallHandler.java:52) [undertow-core-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.security.handlers.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:51) [undertow-core-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:61) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:56) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.0.Final.jar:1.0.0.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.0.Final.jar:1.0.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:25) [undertow-core-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:240) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:227) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:73) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:146) [undertow-servlet-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:168) [undertow-core-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:687) [undertow-core-1.0.0.Final.jar:1.0.0.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_51]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_51]
at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_51]
My Bean:
#Stateless
#Path("testdata")
#RolesAllowed({ "ADMIN" })
public class TestFacade extends GenericService {
web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>REST services</web-resource-name>
<url-pattern>/rest/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>dice</realm-name>
</login-config>
<security-role>
<role-name>ADMIN</role-name>
</security-role>
<security-role>
<role-name>USER</role-name>
</security-role>
My standalone.xml:
<security-domain name="dice">
<authentication>
<login-module code="Database" flag="required">
<module-option name="dsJndiName" value="java:/jdbc/dice"/>
<module-option name="principalsQuery" value="select passwordHash from player where lower(playertag)= lower(?)"/>
<module-option name="rolesQuery" value="select role, 'Roles' from playerrole pr join player p on (pr.player_id = p.id) where lower(p.playertag)= lower(?)"/>
<module-option name="unauthenticatedIdentity" value="guest"/>
<module-option name="hashAlgorithm" value="SHA-256"/>
<module-option name="hashEncoding" value="base64"/>
</login-module>
</authentication>
</security-domain>
The query for the roles returns: ADMIN, Roles (like mentioned in the spec)
The strange thing is when I remove the #RolesAllowed and check the Roles of the User with isCallerInRole(String) he has the admin role.
System.out.println(ctx.isCallerInRole("ADMIN")); // true
System.out.println(ctx.isCallerInRole("USER")); // false (is ok. he is just admin)
System.out.println(ctx.isCallerInRole("USERdsd")); // false (nonexisting role)
Can anyone spot my mistake? Thanks a lot!
Solved it. The default security domain for the ejb subsystem was set to other per default. I just removed in (standalone.xml) and it worked!
As #mkuff described, removing the default security domain from the EJB subsystem helps. Here's how to do that with JBoss CLI:
$WILDFLY_LOCATION/bin/jboss-cli.sh -c \
--command='/subsystem=ejb3:undefine-attribute(name=default-security-domain)'
This is also a problem with JBoss 7.2. A call to a method in a SLSB annotated with #PermitAll worked fine in JBoss 7.1.1 and 7.1.3 but got permission denied in jboss 7.2.0.Final.
After reading this I changed the default security domain to our applications domain and it worked. What I don't really see is why #PermitAll methods need to do any authenticating at all.
I've set up OpenLdap on a debian 6 vm (192.168.1.150:389)
I have created a JSF project with Jboss AS7.1 and am trying to authenticate against the ldap server above. The problem is that jboss displays a message indicating that my password is not valid so i don't know how to keep on debugging this problem since i can see no other relevant output.
I have configured TRACE debug levels for org.jboss.security
I have tried countless tutorials but without any relevant errors i can't continue to debug this.
What would cause the above error (incorrect password) besides providing the wrong password?
Here's some output and config files. I will attach anything you request if i've forgotten it.
My jboss standalone.xml configuration is as follows:
319 <security-domain name="CrudJSFRealm">
320 <authentication>
321 <login-module code="org.jboss.security.auth.spi.LdapExtLoginModule" flag="required">
322 <module-option name="java.naming.factory.initial" value="com.sun.jndi.ldap.LdapCtxFactory"/>
323 <module-option name="java.naming.provider.url" value="ldap://192.168.1.150:389"/>
324 <module-option name="java.naming.security.authentication" value="simple"/>
325 <module-option name="bindDN" value="cn=admin"/>
326 <module-option name="bindCredential" value="passwd"/>
327
328 <module-option name="baseCtxDN" value="ou=People,dc=nps2,dc=local"/>
329 <module-option name="rolesCtxDN" value="ou=Roles,dc=nps2,dc=local"/>
330
331 <module-option name="baseFilter" value="(uid={0})"/><!--ok-->
332 <module-option name="roleFilter" value="(member={1})"/><!--ok-->
333 <module-option name="roleAttributeID" value="cn"/><!--ok-->
334 <module-option name="roleAttributeIsDN" value="false"/>
335 <module-option name="uidAttributeID" value="member"/>
336 <module-option name="roleNameAttributeID" value="cn"/>
337
338 <module-option name="roleRecursion" value="0"/><!--ok-->
339 <module-option name="allowEmptyPasswords" value="false"/>
340 <!--<module-option name="throwValidateError" value="true"/>-->
341 <module-option name="java.naming.referral" value="follow"/>
342 </login-module>
343 </authentication>
344 </security-domain>
I am correctly referencing the CrudJSFRealm in my jboss-web.xml file since the ldap connection is being used:
<!-- Realm that will be used -->
<security-domain>java:/jaas/CrudJSFRealm</security-domain>
Here's my openldap structure:
dn: dc=nps2,dc=local
objectClass: top
objectClass: dcObject
objectClass: organization
o: nps2.local
dc: nps2
dn: ou=People,dc=nps2,dc=local
ou: People
objectClass: top
objectClass: organizationalUnit
dn: uid=sm0ke,ou=People,dc=nps2,dc=local
uid: sm0ke
cn: Dimitrios Kordas
objectClass: account
objectClass: posixAccount
objectClass: top
objectClass: shadowAccount
shadowLastChange: 15149
shadowMax: 99999
shadowWarning: 7
loginShell: /bin/bash
uidNumber: 1000
gidNumber: 1000
homeDirectory: /home/sm0ke
gecos: Dimitrios Kordas,,,
userPassword:: ***
# Roles, nps2.local
dn: ou=Roles,dc=nps2,dc=local
objectClass: top
objectClass: organizationalUnit
ou: Roles
# users, Roles, nps2.local
dn: cn=users,ou=Roles,dc=nps2,dc=local
objectClass: top
objectClass: groupOfNames
member: uid=sm0ke,ou=People,dc=nps2,dc=local
member: uid=nobody,ou=People,dc=nps2,dc=local
cn: users
# root, Roles, nps2.local
dn: cn=root,ou=Roles,dc=nps2,dc=local
objectClass: top
objectClass: groupOfNames
member: uid=sm0ke,ou=People,dc=nps2,dc=local
member: uid=nobody,ou=People,dc=nps2,dc=local
cn: root
So basically i have 2 users (sm0ke and nobody) and 2 Roles root and users.
There's a member attribute to each role.
Here's the output when trying to pass authentication in my JSF project:
14:30:32,196 TRACE [org.jboss.as.web.security] (http--127.0.0.1-8080-1) Begin invoke, caller=null
14:30:32,204 DEBUG [org.apache.catalina.authenticator.AuthenticatorBase] (http--127.0.0.1-8080-1) Security checking request POST /CrudJSF/j_security_check
14:30:32,206 DEBUG [org.apache.catalina.authenticator.FormAuthenticator] (http--127.0.0.1-8080-1) Authenticating username 'sm0ke'
14:30:32,211 TRACE [org.jboss.security.authentication.JBossCachedAuthenticationManager] (http--127.0.0.1-8080-1) Begin isValid, principal:sm0ke, cache entry: null
14:30:32,211 TRACE [org.jboss.security.authentication.JBossCachedAuthenticationManager] (http--127.0.0.1-8080-1) defaultLogin, principal=sm0ke
14:30:32,213 TRACE [org.jboss.security.auth.login.XMLLoginConfigImpl] (http--127.0.0.1-8080-1) Begin getAppConfigurationEntry(CrudJSFRealm), size=5
14:30:32,216 TRACE [org.jboss.security.auth.login.XMLLoginConfigImpl] (http--127.0.0.1-8080-1) End getAppConfigurationEntry(CrudJSFRealm), authInfo=AppConfigurationEntry[]:
[0]
LoginModule Class: org.jboss.security.auth.spi.LdapExtLoginModule
ControlFlag: LoginModuleControlFlag: required
Options:
name=baseFilter, value=(uid={0})
name=uidAttributeID, value=member
name=java.naming.referral, value=follow
name=bindDN, value=cn=admin
name=rolesCtxDN, value=ou=Roles,dc=nps2,dc=local
name=roleNameAttributeID, value=cn
name=roleRecursion, value=0
name=baseCtxDN, value=ou=People,dc=nps2,dc=local
name=java.naming.factory.initial, value=com.sun.jndi.ldap.LdapCtxFactory
name=java.naming.security.authentication, value=simple
name=allowEmptyPasswords, value=false
name=roleFilter, value=(member={1})
name=java.naming.provider.url, value=ldap://192.168.1.150:389
name=bindCredential, value=****
name=roleAttributeIsDN, value=false
name=roleAttributeID, value=cn
14:30:32,226 TRACE [org.jboss.security.auth.spi.LdapExtLoginModule] (http--127.0.0.1-8080-1) initialize
14:30:32,227 TRACE [org.jboss.security.auth.spi.LdapExtLoginModule] (http--127.0.0.1-8080-1) Security domain: CrudJSFRealm
14:30:32,228 TRACE [org.jboss.security.auth.spi.LdapExtLoginModule] (http--127.0.0.1-8080-1) login
14:30:32,230 TRACE [org.jboss.security.auth.spi.LdapExtLoginModule] (http--127.0.0.1-8080-1) Logging into LDAP server, env={uidAttributeID=member, baseFilter=(uid={0}), allowEmptyPasswords=false, java.naming.referral=follow, java.naming.security.credentials=***, jboss.security.security_domain=CrudJSFRealm, java.naming.security.authentication=simple, baseCtxDN=ou=People,dc=nps2,dc=local, roleAttributeIsDN=false, rolesCtxDN=ou=Roles,dc=nps2,dc=local, java.naming.security.principal=cn=admin, roleRecursion=0, java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory, roleFilter=(member={1}), java.naming.provider.url=ldap://192.168.1.150:389, roleNameAttributeID=cn, roleAttributeID=cn, bindDN=cn=admin, bindCredential=***}
14:30:32,251 DEBUG [org.jboss.security.auth.spi.LdapExtLoginModule] (http--127.0.0.1-8080-1) Bad password for username=sm0ke
14:30:32,253 TRACE [org.jboss.security.auth.spi.LdapExtLoginModule] (http--127.0.0.1-8080-1) abort
14:30:32,253 ERROR [org.jboss.security.authentication.JBossCachedAuthenticationManager] (http--127.0.0.1-8080-1) Login failure: javax.security.auth.login.FailedLoginException: Password Incorrect/Password Required
at org.jboss.security.auth.spi.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:270) [picketbox-4.0.7.Final.jar:4.0.7.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [classes.jar:1.6.0_33]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [classes.jar:1.6.0_33]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [classes.jar:1.6.0_33]
at java.lang.reflect.Method.invoke(Method.java:597) [classes.jar:1.6.0_33]
at javax.security.auth.login.LoginContext.invoke(LoginContext.java:769) [classes.jar:1.6.0_33]
at javax.security.auth.login.LoginContext.access$000(LoginContext.java:186) [classes.jar:1.6.0_33]
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:683) [classes.jar:1.6.0_33]
at java.security.AccessController.doPrivileged(Native Method) [classes.jar:1.6.0_33]
at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:680) [classes.jar:1.6.0_33]
at javax.security.auth.login.LoginContext.login(LoginContext.java:579) [classes.jar:1.6.0_33]
at org.jboss.security.authentication.JBossCachedAuthenticationManager.defaultLogin(JBossCachedAuthenticationManager.java:449) [picketbox-infinispan-4.0.7.Final.jar:4.0.7.Final]
at org.jboss.security.authentication.JBossCachedAuthenticationManager.proceedWithJaasLogin(JBossCachedAuthenticationManager.java:383) [picketbox-infinispan-4.0.7.Final.jar:4.0.7.Final]
at org.jboss.security.authentication.JBossCachedAuthenticationManager.authenticate(JBossCachedAuthenticationManager.java:371) [picketbox-infinispan-4.0.7.Final.jar:4.0.7.Final]
at org.jboss.security.authentication.JBossCachedAuthenticationManager.isValid(JBossCachedAuthenticationManager.java:160) [picketbox-infinispan-4.0.7.Final.jar:4.0.7.Final]
at org.jboss.as.web.security.JBossWebRealm.authenticate(JBossWebRealm.java:214) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.authenticator.FormAuthenticator.authenticate(FormAuthenticator.java:280) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:381) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Thread.java:680) [classes.jar:1.6.0_33]
14:30:32,272 TRACE [org.jboss.security.authentication.JBossCachedAuthenticationManager] (http--127.0.0.1-8080-1) End isValid, false
14:30:32,273 TRACE [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/CrudJSF]] (http--127.0.0.1-8080-1) Username sm0ke NOT successfully authenticated
14:30:32,481 DEBUG [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/CrudJSF].[Faces Servlet]] (http--127.0.0.1-8080-1) Disabling the response for futher output
14:30:32,486 DEBUG [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/CrudJSF].[Faces Servlet]] (http--127.0.0.1-8080-1) The Response is vehiculed using a wrapper: org.apache.catalina.connector.Response
14:30:32,495 DEBUG [org.apache.catalina.authenticator.AuthenticatorBase] (http--127.0.0.1-8080-1) Failed authenticate() test ??/CrudJSF/j_security_check
14:30:32,504 TRACE [org.jboss.as.web.security] (http--127.0.0.1-8080-1) End invoke, caller=null
14:30:32,506 TRACE [org.jboss.security.SecurityRolesAssociation] (http--127.0.0.1-8080-1) Setting threadlocal:null
14:30:32,514 TRACE [org.jboss.as.web.security] (http--127.0.0.1-8080-1) Begin invoke, caller=null
14:30:32,515 DEBUG [org.apache.catalina.authenticator.AuthenticatorBase] (http--127.0.0.1-8080-1) Security checking request GET /CrudJSF/javax.faces.resource/main.css.xhtml
14:30:32,518 DEBUG [org.apache.catalina.realm.RealmBase] (http--127.0.0.1-8080-1) Checking constraint 'SecurityConstraint[Restricted Area - ADMIN Only]' against GET /javax.faces.resource/main.css.xhtml --> false
14:30:32,522 DEBUG [org.apache.catalina.realm.RealmBase] (http--127.0.0.1-8080-1) Checking constraint 'SecurityConstraint[Restricted Area - USER and ADMIN]' against GET /javax.faces.resource/main.css.xhtml --> false
14:30:32,527 DEBUG [org.apache.catalina.realm.RealmBase] (http--127.0.0.1-8080-1) Checking constraint 'SecurityConstraint[Restricted Area - ADMIN Only]' against GET /javax.faces.resource/main.css.xhtml --> false
14:30:32,528 DEBUG [org.apache.catalina.realm.RealmBase] (http--127.0.0.1-8080-1) Checking constraint 'SecurityConstraint[Restricted Area - USER and ADMIN]' against GET /javax.faces.resource/main.css.xhtml --> false
14:30:32,529 DEBUG [org.apache.catalina.realm.RealmBase] (http--127.0.0.1-8080-1) Checking constraint 'SecurityConstraint[Restricted Area - ADMIN Only]' against GET /javax.faces.resource/main.css.xhtml --> false
14:30:32,530 DEBUG [org.apache.catalina.realm.RealmBase] (http--127.0.0.1-8080-1) Checking constraint 'SecurityConstraint[Restricted Area - USER and ADMIN]' against GET /javax.faces.resource/main.css.xhtml --> false
14:30:32,531 DEBUG [org.apache.catalina.realm.RealmBase] (http--127.0.0.1-8080-1) Checking constraint 'SecurityConstraint[Restricted Area - ADMIN Only]' against GET /javax.faces.resource/main.css.xhtml --> false
14:30:32,532 DEBUG [org.apache.catalina.realm.RealmBase] (http--127.0.0.1-8080-1) Checking constraint 'SecurityConstraint[Restricted Area - USER and ADMIN]' against GET /javax.faces.resource/main.css.xhtml --> false
14:30:32,533 DEBUG [org.apache.catalina.realm.RealmBase] (http--127.0.0.1-8080-1) No applicable constraint located
14:30:32,533 DEBUG [org.apache.catalina.authenticator.AuthenticatorBase] (http--127.0.0.1-8080-1) Not subject to any constraint
14:30:32,538 TRACE [org.jboss.as.web.security] (http--127.0.0.1-8080-1) End invoke, caller=null
14:30:32,538 TRACE [org.jboss.security.SecurityRolesAssociation] (http--127.0.0.1-8080-1) Setting threadlocal:null
I just spotted that my bindDN is incomplete. I changed it to the complete: "cn=admin,dc=nps2,dc=local" and it worked.
Pretty hard to spot when there's no appropriate output in the logs though.
I want to test my EJBs on an embedded Glassfish using Arquillian.
The important thing is that I have to have security up because my bean logic does some programmatic security checking (sessionContext.isCallerInRole(role)).
Is it possible to simulate a login with Arquillian on an Embedded Glassfish?
How do I setup the Embedded Glassfish to use user and role property files?
[EDIT]
I found a post who's directions I decided to follow (http://community.jboss.org/message/580290) but I still got issues.
1 my arquillian.xml isn't picked up
2 I get warnings concerning #Resource SessionContext
3 I can't get the running server's instance
src/test/resources/arquillian.xml:
<arquillian xmlns="http://jboss.com/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:glassfish="urn:arq:org.jboss.arquillian.container.glassfish.embedded_3">
<glassfish:container>
<glassfish:bindHttpPort>9090</glassfish:bindHttpPort>
<glassfish:instanceRoot>src/test/glassfish</glassfish:instanceRoot>
<glassfish:autoDelete>true</glassfish:autoDelete>
</glassfish:container>
</arquillian>
my test:
#RunWith(Arquillian.class)
public class ArquillianTestCase {
#Deployment
public static JavaArchive createDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "test.jar")
.addClasses(FileBrowser.class, FileBrowserBean.class).addAsResource("META-INF/ejb-jar.xml")
.addAsResource("META-INF/glassfish-ejb-jar.xml");
return jar;
}
#EJB
private FileBrowser fileBrowser;
#Test
public void setupSecurity() throws Exception {
GlassfishTestHelper.createFileUser("user1", "xxx", "role1");
}
#Test
public void testLoadConfiguration() throws Exception {
final boolean loggedIn = GlassfishTestHelper.loginFileUser("user1", "xxx");
Assert.assertEquals(true, loggedIn);
this.fileBrowser.loadConfiguration();
}
my login helper class:
public final class GlassfishTestHelper {
private GlassfishTestHelper() {
}
public static void createFileUser(final String username, final String password, final String groups) throws Exception {
final Server server = Server.getServer(Server.getServerNames().get(0)); // NPE
final String command = "create-file-user";
final ParameterMap params = new ParameterMap();
params.add("userpassword", password);
params.add("groups", groups);
params.add("username", username);
final CommandRunner runner = server.getHabitat().getComponent(CommandRunner.class);
final ActionReport report = server.getHabitat().getComponent(ActionReport.class);
runner.getCommandInvocation(command, report).parameters(params).execute();
if (report.getMessage() != null) {
throw new Exception(String.format("Failed to create user : %s - message %s", username, report.getMessage()),
report.getFailureCause());
}
}
public static boolean loginFileUser(final String username, final String password) throws Exception {
final ProgrammaticLogin login = new ProgrammaticLogin();
return login.login(username, password.toCharArray(), "fileRealm", true);
}
}
my EJB:
#Stateless
#Local(FileBrowser.class)
public class FileBrowserBean implements FileBrowser {
#Resource
private SessionContext sessionContext;
#Override
public Set<Application> loadConfiguration() throws FileBrowserException {
// ...
}
}
If I run the test, this is the output:
Running com.jnj.gtsc.services.filebrowser.ArquillianTestCase
18-Apr-2011 16:14:30 org.jboss.arquillian.impl.client.container.ContainerRegistryCreator getActivatedConfiguration
INFO: Could not read active container configuration: null
18-Apr-2011 16:14:31 com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl findDerbyClient
INFO: Cannot find javadb client jar file, derby jdbc driver will not be available by default.
18-Apr-2011 16:14:31 org.hibernate.validator.util.Version <clinit>
INFO: Hibernate Validator null
18-Apr-2011 16:14:31 org.hibernate.validator.engine.resolver.DefaultTraversableResolver detectJPA
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
18-Apr-2011 16:14:32 com.sun.enterprise.v3.services.impl.GrizzlyService createNetworkProxy
INFO: Network listener https-listener on port 0 disabled per domain.xml
18-Apr-2011 16:14:32 com.sun.enterprise.v3.server.AppServerStartup run
INFO: GlassFish Server Open Source Edition 3.1 (java_re-private) startup time : Embedded (655ms), startup services(395ms), total(1,050ms)
18-Apr-2011 16:14:32 com.sun.enterprise.v3.services.impl.GrizzlyProxy$2$1 onReady
INFO: Grizzly Framework 1.9.31 started in: 121ms - bound to [0.0.0.0:8181]
18-Apr-2011 16:14:32 org.glassfish.admin.mbeanserver.JMXStartupService$JMXConnectorsStarterThread run
INFO: JMXStartupService: JMXConnector system is disabled, skipping.
18-Apr-2011 16:14:33 com.sun.enterprise.security.SecurityLifecycle <init>
INFO: SEC1002: Security Manager is OFF.
18-Apr-2011 16:14:33 com.sun.enterprise.security.SecurityLifecycle onInitialization
INFO: SEC1010: Entering Security Startup Service
18-Apr-2011 16:14:33 com.sun.enterprise.security.PolicyLoader loadPolicy
INFO: SEC1143: Loading policy provider com.sun.enterprise.security.jacc.provider.SimplePolicyProvider.
18-Apr-2011 16:14:34 com.sun.enterprise.security.auth.realm.Realm doInstantiate
INFO: SEC1115: Realm [admin-realm] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.
18-Apr-2011 16:14:34 com.sun.enterprise.security.auth.realm.Realm doInstantiate
INFO: SEC1115: Realm [file] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.
18-Apr-2011 16:14:34 com.sun.enterprise.security.auth.realm.Realm doInstantiate
INFO: SEC1115: Realm [certificate] of classtype [com.sun.enterprise.security.auth.realm.certificate.CertificateRealm] successfully created.
18-Apr-2011 16:14:34 com.sun.enterprise.security.SecurityLifecycle onInitialization
INFO: SEC1011: Security Service(s) Started Successfully
18-Apr-2011 16:14:34 com.sun.enterprise.web.WebContainer createHttpListener
INFO: WEB0169: Created HTTP listener [http-listener] on host/port [0.0.0.0:8181]
18-Apr-2011 16:14:34 com.sun.enterprise.web.WebContainer createHosts
INFO: WEB0171: Created virtual server [server]
18-Apr-2011 16:14:34 com.sun.enterprise.web.WebContainer loadSystemDefaultWebModules
INFO: WEB0172: Virtual server [server] loaded default web module []
18-Apr-2011 16:14:35 org.glassfish.apf.impl.DefaultErrorHandler warning
WARNING: Incorrect #Resource annotation class definition - missing lookup attribute
symbol: FIELD
location: private javax.ejb.SessionContext com.jnj.gtsc.services.filebrowser.ejb.FileBrowserBean.sessionContext
18-Apr-2011 16:14:35 org.glassfish.apf.impl.DefaultErrorHandler warning
WARNING: Incorrect #Resource annotation class definition - missing lookup attribute
symbol: FIELD
location: private javax.ejb.SessionContext com.jnj.gtsc.services.filebrowser.ejb.FileBrowserBean.sessionContext
classLoader = WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)
SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7#720f6c
18-Apr-2011 16:14:35 com.sun.ejb.containers.BaseContainer initializeHome
INFO: Portable JNDI names for EJB FileBrowserBean : [java:global/test/FileBrowserBean!com.jnj.gtsc.services.filebrowser.ejb.FileBrowser, java:global/test/FileBrowserBean]
18-Apr-2011 16:14:36 com.sun.enterprise.web.WebApplication start
INFO: WEB0671: Loading application [test] at [/test]
18-Apr-2011 16:14:36 org.glassfish.deployment.admin.DeployCommand execute
PlainTextActionReporterSUCCESSDescription: deploy AdminCommandApplication deployed with name test.
INFO: test was successfully deployed in 2,845 milliseconds.
[name=test
18-Apr-2011 16:14:36 org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher injectClass
INFO: BeanManager cannot be located at java:comp/BeanManager. Either you are using an archive with no beans.xml, or the BeanManager has not been bound to that location in JNDI.
18-Apr-2011 16:14:36 org.jboss.arquillian.testenricher.cdi.CDIInjectionEnricher injectClass
INFO: BeanManager cannot be located at java:comp/BeanManager. Either you are using an archive with no beans.xml, or the BeanManager has not been bound to that location in JNDI.
18-Apr-2011 16:14:36 com.sun.appserv.security.ProgrammaticLogin login
SEVERE: SEC9050: Programmatic login failed
com.sun.enterprise.security.auth.login.common.LoginException: Login failed: Unable to locate a login configuration
at com.sun.enterprise.security.auth.login.LoginContextDriver.doPasswordLogin(LoginContextDriver.java:394)
at com.sun.enterprise.security.auth.login.LoginContextDriver.login(LoginContextDriver.java:240)
at com.sun.enterprise.security.auth.login.LoginContextDriver.login(LoginContextDriver.java:153)
at com.sun.appserv.security.ProgrammaticLogin$1.run(ProgrammaticLogin.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.appserv.security.ProgrammaticLogin.login(ProgrammaticLogin.java:168)
at com.jnj.gtsc.services.filebrowser.util.GlassfishTestHelper.loginFileUser(GlassfishTestHelper.java:67)
at com.jnj.gtsc.services.filebrowser.ArquillianTestCase.testLoadConfiguration(ArquillianTestCase.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.jboss.arquillian.junit.Arquillian$6$1.invoke(Arquillian.java:259)
at org.jboss.arquillian.impl.execution.LocalTestExecuter.execute(LocalTestExecuter.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.arquillian.impl.core.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.impl.core.EventContextImpl.invokeObservers(EventContextImpl.java:98)
at org.jboss.arquillian.impl.core.EventContextImpl.proceed(EventContextImpl.java:80)
at org.jboss.arquillian.impl.core.ManagerImpl.fire(ManagerImpl.java:126)
at org.jboss.arquillian.impl.core.ManagerImpl.fire(ManagerImpl.java:106)
at org.jboss.arquillian.impl.core.EventImpl.fire(EventImpl.java:67)
at org.jboss.arquillian.impl.execution.ContainerTestExecuter.execute(ContainerTestExecuter.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.arquillian.impl.core.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.impl.core.EventContextImpl.invokeObservers(EventContextImpl.java:98)
at org.jboss.arquillian.impl.core.EventContextImpl.proceed(EventContextImpl.java:80)
at org.jboss.arquillian.impl.TestContextHandler.createTestContext(TestContextHandler.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.arquillian.impl.core.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.impl.core.EventContextImpl.proceed(EventContextImpl.java:87)
at org.jboss.arquillian.impl.TestContextHandler.createClassContext(TestContextHandler.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.arquillian.impl.core.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.impl.core.EventContextImpl.proceed(EventContextImpl.java:87)
at org.jboss.arquillian.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.arquillian.impl.core.ObserverImpl.invoke(ObserverImpl.java:90)
at org.jboss.arquillian.impl.core.EventContextImpl.proceed(EventContextImpl.java:87)
at org.jboss.arquillian.impl.core.ManagerImpl.fire(ManagerImpl.java:126)
at org.jboss.arquillian.impl.EventTestRunnerAdaptor.test(EventTestRunnerAdaptor.java:101)
at org.jboss.arquillian.junit.Arquillian$6.evaluate(Arquillian.java:251)
at org.jboss.arquillian.junit.Arquillian$4.evaluate(Arquillian.java:214)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:303)
at org.jboss.arquillian.junit.Arquillian.access$300(Arquillian.java:45)
at org.jboss.arquillian.junit.Arquillian$5.evaluate(Arquillian.java:228)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:173)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:303)
at org.jboss.arquillian.junit.Arquillian.access$300(Arquillian.java:45)
at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:187)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:127)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
at org.jboss.arquillian.junit.JUnitTestRunner.execute(JUnitTestRunner.java:69)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.doGet(ServletTestRunner.java:84)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.SecurityException: Unable to locate a login configuration
at com.sun.security.auth.login.ConfigFile.<init>(ConfigFile.java:93)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at javax.security.auth.login.Configuration$3.run(Configuration.java:247)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.Configuration.getConfiguration(Configuration.java:242)
at javax.security.auth.login.LoginContext$1.run(LoginContext.java:237)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.init(LoginContext.java:234)
at javax.security.auth.login.LoginContext.<init>(LoginContext.java:367)
at javax.security.auth.login.LoginContext.<init>(LoginContext.java:444)
at com.sun.enterprise.security.auth.login.LoginContextDriver.doPasswordLogin(LoginContextDriver.java:381)
... 107 more
Caused by: java.io.IOException: Unable to locate a login configuration
at com.sun.security.auth.login.ConfigFile.init(ConfigFile.java:250)
at com.sun.security.auth.login.ConfigFile.<init>(ConfigFile.java:91)
... 122 more
classLoader = WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)
SharedSecrets.getJavaNetAccess()=java.net.URLClassLoader$7#720f6c
PlainTextActionReporterSUCCESSNo monitoring data to report.
Glassfish standalone instance configuration may be used with Arquillian GlassFish Embedded containter adapter. You need to check security in your tests, so you must prepare your GlassFish instance configuration first. This can be achieved also by programmatic configuration (see https://stackoverflow.com/a/20411981/2169124), but for me configuration in test resources looks more natural. To configure users in file realm (used by default) you need to:
Install standalone Glassfish server;
Start Glassfish instance with asadmin command:
$GLASSFISH_HOME/bin/asadmin start-domain
Add users to file realm with asadmin command (stored in file named keyfile):
$GLASSFISH_HOME/bin/asadmin create-file-user --user username
Copy folders
$GLASSFISH_HOME/glassfish/domains/domain1/config
$GLASSFISH_HOME/glassfish/domains/domain1/docroot
to test resources (for example src/test/resources/domain, assuming that you are using maven)
In arquillian.xml define path to glassfish configuration (it will be copied to target/test-classes/domain by maven):
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<container qualifier="glassfish-embedded" default="true">
<configuration>
<property name="instanceRoot">target/test-classes/domain</property>
</configuration>
</container>
Map users to roles in glassfish-application.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-application PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Java EE Application 6.0//EN" "http://glassfish.org/dtds/glassfish-application_6_0-1.dtd">
<glassfish-application>
<security-role-mapping>
<role-name>admin</role-name>
<principal-name>username</principal-name>
</security-role-mapping>
</glassfish-application>
Add glassfish-application.xml to test artifact:
ShrinkWrap.create(EnterpriseArchive.class)
.addAsModule(ejbJar)
.addAsManifestResource(new File("src/test/resources/glassfish-application.xml"))
In test method use ProgrammaticLogin to handle authentication:
ProgrammaticLogin programmaticLogin = new ProgrammaticLogin();
programmaticLogin.login("username", "password");