Integration Testing with a CDI Injected Principal - security

I have a simple request scope bean that contains an injected Principal so that I can determine the ID of the current user. That bean is then injected into a Servlet and the Servlet uses the bean to display the user's ID. For example:
The interface:
public interface UserManager {
public String getCurrentUserName();
}
The implementation:
#RequestScoped
public class CdiUserManager implements UserManager {
#Inject
private Principal principal;
public CdiUserManager() {
}
#Override
public String getCurrentUserName() {
String name = null;
if(principal != null && principal.getName() != null){
name = principal.getName();
}
return name;
}
}
The servlet:
#WebServlet({"/public/user", "/authenticated/user"})
public class UserServlet extends HttpServlet {
#Inject
private UserManager manager;
public UserServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("UserName: " + manager.getCurrentUserName());
}
}
The servlet is mapped for both authenticated and unauthenticated access. I have the web.xml configured with the proper security constraints so that basic authentication is required for the authenticated URL only.
I also have an EAR file. The application.xml in the EAR includes the web module with the servlet and managed bean as well as the security role that is defined in the web.xml. In addition, I have an ibm-application-bnd.xml file that maps the security role in the web.xml and application.xml to the special subject ALL_AUTHENTICATED_USERS.
I have an empty beans.xml file in the WEB-INF directory of the WAR.
I have two issues at the moment that I can't seem to resolve.
1) When I access the public URL as an unauthenticated user, I would expected that either the inject Principal or the call to principal.getName() would be null or some other identifiable value... i.e. "UNAUTHENTICATED". Currently I get a NPE with the stack trace below. If I access the authenticated URL and login via basic authentication, the servlet returns my user name as expected. I'm not sure what the standard says should be returned in this case, but I would think this is a bug?
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.apache.webbeans.component.BuildInOwbBean$BuildInBeanMethodHandler.invoke(BuildInOwbBean.java:273)
at [internal classes]
at org.javassist.tmp.java.lang.Object_$$_javassist_1.getName(Object_$$_javassist_1.java)
at com.testing.cdi.CdiUserManager.getCurrentUserName(CdiUserManager.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.apache.webbeans.intercept.InterceptorHandler.invoke(InterceptorHandler.java:327)
at [internal classes]
at com.testing.cdi.CdiUserManager_$$_javassist_0.getCurrentUserName(CdiUserManager_$$_javassist_0.java)
at com.testing.cdi.UserServlet.doGet(UserServlet.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1285)
at [internal classes]
2) The second issue I have is how to integration test using the injected Principal? I'm currently using Arquillian and I've built a deployment method that looks like this:
#Deployment
public static EnterpriseArchive createDeployment() {
EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, CONTEXT_ROOT + ".ear");
WebArchive war = ShrinkWrap.create(WebArchive.class, CONTEXT_ROOT + ".war");
war.addPackages(true, UserManager.class.getPackage());
war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
war.setWebXML(new File("src/main/webapp/WEB-INF/web.xml"));
ear.setApplicationXML(new File("../testing-ear/src/main/application/META-INF/application.xml"));
ear.addAsManifestResource(new File("../testing-ear/src/main/application/META-INF/ibm-application-bnd.xml"));
ear.addAsModule(war);
return ear;
}
I'm authenticating my test user before each test case like this:
#Before
public void setup() throws LoginException, WSSecurityException {
// WLP provided classes to authenticate a user.
CallbackHandler wscbh = new WSCallbackHandlerImpl("user", "password");
LoginContext ctx = new LoginContext("WSLogin", wscbh);
ctx.login();
// Set the user as the current user on the thread.
Subject mySubject = ctx.getSubject();
WSSubject.setRunAsSubject(mySubject);
}
Then in the test case, I'm checking to see if the user name is null like this:
#Test
public void testAuthenticatedPrincipal() throws LoginException, WSSecurityException {
assertNull("User name should not be null.", manager.getCurrentUserName());
}
The execution of this test case always results in a NPE with the the stack trace:
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.apache.webbeans.component.BuildInOwbBean$BuildInBeanMethodHandler.invoke(BuildInOwbBean.java:273)
at org.apache.webbeans.component.BuildInOwbBean$BuildInBeanMethodHandler.invoke(BuildInOwbBean.java:267)
at org.javassist.tmp.java.lang.Object_$$_javassist_2.getName(Object_$$_javassist_2.java)
at com.testing.cdi.CdiUserManager.getCurrentUserName(CdiUserManager.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.apache.webbeans.intercept.InterceptorHandler.invoke(InterceptorHandler.java:327)
at org.apache.webbeans.intercept.NormalScopedBeanInterceptorHandler.invoke(NormalScopedBeanInterceptorHandler.java:117)
at org.apache.webbeans.intercept.NormalScopedBeanInterceptorHandler.invoke(NormalScopedBeanInterceptorHandler.java:108)
at com.testing.cdi.CdiUserManager_$$_javassist_1.getCurrentUserName(CdiUserManager_$$_javassist_1.java)
at com.testing.cdi.test.UserManagerTest.testAuthenticatedPrincipal(UserManagerTest.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.jboss.arquillian.junit.Arquillian$6$1.invoke(Arquillian.java:325)
at org.jboss.arquillian.container.test.impl.execution.LocalTestExecuter.execute(LocalTestExecuter.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116)
at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
at org.jboss.arquillian.container.test.impl.execution.ContainerTestExecuter.execute(ContainerTestExecuter.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:102)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.test(EventTestRunnerAdaptor.java:135)
at org.jboss.arquillian.junit.Arquillian$6.evaluate(Arquillian.java:318)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.jboss.arquillian.junit.Arquillian$5.evaluate(Arquillian.java:277)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:202)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:377)
at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:52)
at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:216)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:164)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
at org.jboss.arquillian.junit.container.JUnitTestRunner.execute(JUnitTestRunner.java:66)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.executeTest(ServletTestRunner.java:159)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.execute(ServletTestRunner.java:125)
at org.jboss.arquillian.protocol.servlet.runner.ServletTestRunner.doGet(ServletTestRunner.java:89)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1285)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:473)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1104)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:4845)
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.handleRequest(DynamicVirtualHost.java:297)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:981)
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:262)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:955)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1157)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:627)
at java.lang.Thread.run(Thread.java:863)
In the past I've built EJB projects and integration tested them using this method. An inject SessionContext replaces the Principal in that scenario. Does anyone have any advice or experience on how to get this test case to run?
P.S. I'm using the IBM JDK v1.7.1 with WebSphere Liberty Developer Edition v8.5.5.5.

Usually, a null value is used for the principal of a user who is not logged in, e.g. HttpServletRequest.getUserPrincipal() returns null if the user has not been authenticated.
Therefore, I don't think it's unreasonable for the injected Principal to be null. However, the Principal is also a CDI bean which is proxied. Since you have an injected proxy object, you can't test it for nullness but when you call getName(), CDI tries to find the real Principal for the logged in user and calls getName() on it, resulting in the NullPointerException.
I realise that's not hugely helpful since you can't really use the Principal bean to check whether the user is authenticated but I don't think it's wrong.
For the Arquillian test, you could have the test run as a client, rather than on the server so you can manually call the servlet URL and provide the authentication credentials. You'd have to have the servlet print out the username and check that the response is correct on the client.
There's some information about running tests in client mode here: https://docs.jboss.org/author/display/ARQ/Test+run+modes

Related

ClassNotFoundException While deploying the Java EE application on GlassFish 5.0 Server

During deployment of a Java EE 7 application packaged in a WAR with a minimal entity
#Entity
public class MyEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Long id;
#Basic
#Column(length=8192)
private CurrencyUnit currencyUnit;
public MyEntity() {
}
public MyEntity(Long id, CurrencyUnit currentyUnit) {
this.id = id;
this.currencyUnit = currentyUnit;
}
[getter and setter for id and currentyUnit]
and a minimal EJB with interface
#Local
public interface InitService {
MyEntity init();
}
and implementation
#Stateless
public class DefaultInitService implements InitService {
#Override
public MyEntity init() {
MyEntity retValue = new MyEntity(1L, Monetary.getCurrency("EUR"));
return retValue;
}
}
and a backing bean
#Named
#ApplicationScoped
#Eager
public class MyManagedBean {
#EJB
private InitService initService;
private MyEntity myEntity;
public MyManagedBean() {
}
#PostConstruct
private void init() {
this.myEntity = initService.init();
}
public MyEntity getMyEntity() {
return myEntity;
}
public void setMyEntity(MyEntity myEntity) {
this.myEntity = myEntity;
}
}
I get the following exception during deployment on GlassFish 5.0:
Schwerwiegend: Undeployment failed for context /monteta-clazz-not-found-issue
Schwerwiegend: Exception while loading the app : CDI deployment failure:Error instantiating :org.hibernate.validator.cdi.internal.ValidationExtension
java.util.ServiceConfigurationError: Error instantiating :org.hibernate.validator.cdi.internal.ValidationExtension
at org.jboss.weld.util.ServiceLoader.createInstance(ServiceLoader.java:315)
at org.jboss.weld.util.ServiceLoader.prepareInstance(ServiceLoader.java:247)
at org.jboss.weld.util.ServiceLoader.loadService(ServiceLoader.java:215)
at org.jboss.weld.util.ServiceLoader.loadServiceFile(ServiceLoader.java:185)
at org.jboss.weld.util.ServiceLoader.reload(ServiceLoader.java:165)
at org.jboss.weld.util.ServiceLoader.iterator(ServiceLoader.java:289)
at org.glassfish.weld.DeploymentImpl.getExtensions(DeploymentImpl.java:466)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:223)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:328)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:496)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:540)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:536)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:535)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:566)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:558)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:557)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1465)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:110)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1847)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1723)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:190)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jboss.weld.util.ServiceLoader.createInstance(ServiceLoader.java:313)
... 48 more
Caused by: java.lang.TypeNotPresentException: Type javax.money.MonetaryAmount not present
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:117)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.generics.visitor.Reifier.reifyTypeArguments(Reifier.java:68)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:138)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.generics.repository.ClassRepository.getSuperInterfaces(ClassRepository.java:108)
at java.lang.Class.getGenericInterfaces(Class.java:913)
at org.hibernate.validator.internal.util.TypeHelper.resolveTypeForClassAndHierarchy(TypeHelper.java:390)
at org.hibernate.validator.internal.util.TypeHelper.resolveTypes(TypeHelper.java:351)
at org.hibernate.validator.internal.util.TypeHelper.extractType(TypeHelper.java:327)
at org.hibernate.validator.internal.engine.constraintvalidation.ClassBasedValidatorDescriptor.<init>(ClassBasedValidatorDescriptor.java:39)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorDescriptor.forClass(ConstraintValidatorDescriptor.java:49)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at org.hibernate.validator.internal.metadata.core.ConstraintHelper.putConstraints(ConstraintHelper.java:686)
at org.hibernate.validator.internal.metadata.core.ConstraintHelper.<init>(ConstraintHelper.java:318)
at org.hibernate.validator.internal.engine.ValidatorFactoryImpl.<init>(ValidatorFactoryImpl.java:155)
at org.hibernate.validator.HibernateValidator.buildValidatorFactory(HibernateValidator.java:38)
at org.hibernate.validator.internal.engine.ConfigurationImpl.buildValidatorFactory(ConfigurationImpl.java:322)
at org.hibernate.validator.cdi.internal.ValidationExtension.<init>(ValidationExtension.java:116)
... 53 more
Caused by: java.lang.ClassNotFoundException: javax.money.MonetaryAmount
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.apache.felix.framework.ExtensionManager$ExtensionManagerWiring.getClassByDelegation(ExtensionManager.java:873)
at org.apache.felix.framework.BundleWiringImpl.searchImports(BundleWiringImpl.java:1553)
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1484)
at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:75)
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1955)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
... 78 more
The missing type is provided in
<dependency>
<groupId>javax.money</groupId>
<artifactId>money-api</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.0.1-SNAPSHOT</version>
</dependency>
A MCVE is available at https://gitlab.com/krichter/monteta-clazz-not-found-issue.
It looks like you have incorrect version of org.javamoney:moneta:1.0.1-SNAPSHOT. The SNAPSHOT dependency is for developers only but never published to Maven Repository.
You can check all available versions in Maven Central
So, to fix just try to use this one:
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.1</version>
</dependency>
For me the workaround "Money instead of floating point + CurrencyUnit" wasn't an option because even if i suppressed my classes using java.money the error was still present. Also If i removed hibernate validator from my dependencies and if i excluded it from transitives the error remains.
This way i understood the library was already present in glassfish classpath. As it was not an easy solution for me to remove it from there, and as i also needed to use java.money in my app i thought i can just add java.money in the glassfish classpath and it worked. I think its because of glassfish "delegates" classloader method which makes the app class loader to delegate to the server classloaders for loading of all the classes the server can load.
So the solution was for me to add java.money-api.jar in the lib/endorsed folder of glassfish installation.

Issue populating map in Groovy

I've got an interesting issue in groovy, I am trying to populate a map and for some reason it doesn't work, here is the program (just made a bare-bones version to see the problem easier):
public class dd2 {
Map<String, String> subscriptions = ["Listing":"a Listing","Issue":"an Issue"]
Map<String, Object> subscriptionAttributes = new HashMap<String, Object>()
public static void main(String[] args) throws Exception {
def dd = new dd2()
dd.getSubscriptionAttributes()
}
def getSubscriptionAttributes(){
subscriptions.each {
def attributes = ""
println "getting ${it.key}"
subscriptionAttributes.put(it.key, attributes)
}
}
}
if I remove:
subscriptionAttributes.put(it.key, attributes)
it iterates through the whole map of subscriptions. If I try to add to the subscriptionAttributes map it will only get Listing until eventually I get stack overflow.
What am I doing wrong?
It's due to def getSubscriptionAttributes() method name - when getter method is defined Groovy uses it wherever you use a property name. So in your case you are getting:
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844
Exception in thread "main" java.lang.StackOverflowError
at sun.net.www.protocol.file.Handler.parseURL(Handler.java:67)
at java.net.URL.<init>(URL.java:622)
at java.net.URL.<init>(URL.java:490)
at sun.misc.URLClassPath$FileLoader.getResource(URLClassPath.java:1259)
at sun.misc.URLClassPath.getResource(URLClassPath.java:239)
at java.net.URLClassLoader$1.run(URLClassLoader.java:365)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at groovy.lang.Closure.call(Closure.java:416)
at groovy.lang.Closure.call(Closure.java:430)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.callClosureForMapEntry(DefaultGroovyMethods.java:5278)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:2117)
at org.codehaus.groovy.runtime.dgm$164.invoke(Unknown Source)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:274)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at dd2.getSubscriptionAttributes(dd2.groovy:13)
at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:1850)
at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:3758)
at dd2.getProperty(dd2.groovy)
at org.codehaus.groovy.runtime.InvokerHelper.getProperty(InvokerHelper.java:174)
at groovy.lang.Closure.getPropertyTryThese(Closure.java:312)
at groovy.lang.Closure.getPropertyOwnerFirst(Closure.java:306)
at groovy.lang.Closure.getProperty(Closure.java:295)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:50)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)
at dd2$_getSubscriptionAttributes_closure1.doCall(dd2.groovy:16)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
at groovy.lang.Closure.call(Closure.java:414)
at groovy.lang.Closure.call(Closure.java:430)
because when you say:
subscriptionAttributes.put(it.key, attributes)
Groovy actually tries doing:
getSubscriptionAttributes().put(it.key, attributes)
and you get into infinite loop.
Change your method name so it does not conflict with internal map variable and you're good.

thread-weaver with hibernate unit testing

I am trying to write a multithread unit test for my hibernate test.
I chose thread-weaver and got a little play with it.
I used the HSQL Database engine for my hibernate testing which is an in memory database.
It was working perfect until i wanted to write some multi thread unit tests.
Since i am new to thread weaver, i could make some newbie mistakes.
I knew the thread weaver is loading my class with its customized loader.
But in the #ThreadedBefore i try to set the sessionFactory for HSQL one. However, i got a bunch of error logs like
log4j:ERROR "org.apache.log4j.ConsoleAppender" was loaded by [sun.misc.Launcher$AppClassLoader#ece88d2].
log4j:ERROR Could not instantiate appender named "console".
log4j:ERROR A "org.apache.log4j.ConsoleAppender" object is not assignable to a "org.apache.log4j.Appender" variable.
log4j:ERROR The class "org.apache.log4j.Appender" was loaded by
log4j:ERROR [com.google.testing.instrumentation.InstrumentedClassLoader#2a57a184] whereas object of type
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.google.testing.threadtester.MethodCaller.invoke(MethodCaller.java:71)
at com.google.testing.threadtester.BaseThreadedTestRunner.runTests(BaseThreadedTestRunner.java:179)
at com.google.testing.threadtester.BaseThreadedTestRunner.runTests(BaseThreadedTestRunner.java:143)
at com.amazon.amazonclicksdali.test.simpleTest.run(simpleTest.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at com.intellij.junit4.JUnit4TestRunnerUtil$IgnoreIgnoredTestJUnit4ClassRunner.runChild(JUnit4TestRunnerUtil.java:306)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at com.google.testing.threadtester.MethodCaller.invoke(MethodCaller.java:68)
... 30 more
Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.google.testing.threadtester.MethodCaller.invoke(MethodCaller.java:71)
at com.google.testing.threadtester.ThreadedTestWrapper.runTests(ThreadedTestWrapper.java:71)
... 35 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at com.google.testing.threadtester.MethodCaller.invoke(MethodCaller.java:68)
... 36 more
Caused by: java.lang.NullPointerException
at com.google.testing.instrumentation.InstrumentedClassLoader.loadClassData(InstrumentedClassLoader.java:152)
at com.google.testing.instrumentation.InstrumentedClassLoader.findClass(InstrumentedClassLoader.java:137)
at com.google.testing.instrumentation.InstrumentedClassLoader.loadClass(InstrumentedClassLoader.java:113)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:278)
at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:170)
at org.hibernate.cfg.Configuration.applyHibernateValidatorLegacyConstraintsOnDDL(Configuration.java:1663)
at org.hibernate.cfg.Configuration.applyConstraintsToDDL(Configuration.java:1653)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1445)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at com.amazon.amazonclicksdali.test.scheduler.repository.TestSessionHelper.getSessionFactory(TestSessionHelper.java:20)
at com.amazon.amazonclicksdali.test.simpleTest.setup(simpleTest.java:45)
... 41 more
A simple test is like this
public class simpleTest {
Script<RDBInternalReportRepository> main;
Script<RDBInternalReportRepository> second;
final RDBInternalReportRepository target = new RDBInternalReportRepository();
SessionFactory sessionFactory;
RDBInternalReport internalReport1;
#Test
public void run() {
new ThreadedTestRunner().runTests(getClass(), RDBInternalReportRepository.class);
}
#ThreadedBefore
public void setup() throws Exception {
TestSessionHelper testSessionHelper = new TestSessionHelper();
sessionFactory = testSessionHelper.getSessionFactory();
target.setSessionFactory(sessionFactory);
internalReport1 = new RDBInternalReport();
internalReport1.setReferenceId("aaa");
internalReport1.setReportName("testReportName");
internalReport1.setSubmittedDate(new DateTime(2015, 1, 1, 0, 0));
internalReport1.setMarketplaceId(1);
internalReport1.setHashKey("hashValues");
internalReport1.setDedupingString("uid");
internalReport1.setState(ReportState.SUBMITTED);
internalReport1.setErrorCount(0);
target.createOrUpdateInternalReport(internalReport1);
}
#ThreadedTest
public void testSession() throws Exception {
main = new Script<RDBInternalReportRepository>(target);
second = new Script<RDBInternalReportRepository>(target);
main.addTask(new ScriptedTask<RDBInternalReportRepository>() {
#Override
public void execute() throws Exception {
IInternalReport report1 = target.getInternalReport("aaa");
releaseTo(second);
}
});
second.addTask(new ScriptedTask<RDBInternalReportRepository>() {
#Override
public void execute() throws Exception {
releaseTo(main);
}
});
new Scripter<RDBInternalReportRepository>(main, second).execute();
}
}
It fails to even load the sessionFactory which is a simple HSQL database.
It looks as though the NullPointerException is caused by getSystemResourceAsStream() returning null. See line 136 here: https://github.com/google/thread-weaver/blob/5c316abcfdfa1832df981f90cfa5c5811003012e/main/com/google/testing/instrumentation/InstrumentedClassLoader.java
I found the following question which sounds like a pretty good explanation as to what's going on: getSystemResourceAsStream() returns null
It sounds as though a fix might be to add the following to 'InstrumentedCLassLoader.findClass()'
InputStream input = getSystemResourceAsStream(resourceName);
if (input == null) {
return Thread.currentThread().getContextClassLoader().findClass(className);
}
Can you try building threadweaver from source with this fix? Alternatively, I would need to run your entire test and verify.

Injection of EntityManager in JSF

I am using injections but I have some problems :
HTTP Status 500 - javax.ejb.EJBException: The bean encountered a non-application exception; nested exception is:
type Exception report
message javax.ejb.EJBException: The bean encountered a non-application exception; nested exception is:
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax.ejb.EJBException: The bean encountered a non-application exception; nested exception is:
java.lang.NullPointerException
javax.faces.webapp.FacesServlet.service(FacesServlet.java:321)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
javax.faces.el.EvaluationException: javax.ejb.EJBException: The bean encountered a non-application exception; nested exception is:
java.lang.NullPointerException
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:98)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
javax.faces.component.UICommand.broadcast(UICommand.java:311)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
javax.ejb.EJBException: The bean encountered a non-application exception; nested exception is:
java.lang.NullPointerException
org.apache.openejb.core.ivm.BaseEjbProxyHandler.convertException(BaseEjbProxyHandler.java:408)
org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:312)
pl.konrad.daoTest.ServiceUzytkownik$$LocalBeanProxy.dodaj(pl/konrad/daoTest/ServiceUzytkownik.java)
pl.konrad.beans.UzytkownikBean.dodajUzytkownika(UzytkownikBean.java:84)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.apache.el.parser.AstValue.invoke(AstValue.java:278)
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:102)
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
javax.faces.component.UICommand.broadcast(UICommand.java:311)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
pl.konrad.daoTest.ServiceUzytkownik.dodaj(ServiceUzytkownik.java:17)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:227)
org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:194)
org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:308)
org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:303)
org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:92)
org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:308)
pl.konrad.daoTest.ServiceUzytkownik$$LocalBeanProxy.dodaj(pl/konrad/daoTest/ServiceUzytkownik.java)
pl.konrad.beans.UzytkownikBean.dodajUzytkownika(UzytkownikBean.java:84)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.apache.el.parser.AstValue.invoke(AstValue.java:278)
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:102)
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
javax.faces.component.UICommand.broadcast(UICommand.java:311)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat (TomEE)/7.0.55 (1.7.1) logs.
And this is my Bean :
#ManagedBean(name = "uzytkownikBean")
#ViewScoped
public class UzytkownikBean implements Serializable {
private static final long serialVersionUID = 1L;
private Uzytkownik uzytkownik;
private DataModel<Uzytkownik> modelUzytkownicy;
#EJB
private ServiceUzytkownik serviceUzytkownik;
public Uzytkownik getUzytkownik() {
return uzytkownik;
}
public void setUzytkownik(Uzytkownik uzytkownik) {
this.uzytkownik = uzytkownik;
}
public DataModel<Uzytkownik> getModelUzytkownicy() {
return modelUzytkownicy;
}
public void setModelUzytkownicy(ArrayDataModel<Uzytkownik> modelUzytkownicy) {
this.modelUzytkownicy = modelUzytkownicy;
}
#PostConstruct
public void init() {
uzytkownik = new Uzytkownik();
}
public void dodajUzytkownika() {
serviceUzytkownik.dodaj(uzytkownik);
}
}
And my EJB class :
#Stateless
public class ServiceUzytkownik {
#PersistenceContext
private EntityManager em;
public void dodaj(Uzytkownik uzytkownik) {
em.persist(uzytkownik);
}
}
Whats wrong now? and if I should add it to persistence.xml. This is my config for Hibernate. When creating a dynamic web project, would add connection so maybe it is unnecessary. But for now, I have to get rid of this error. Error connecting to the database probably looks different.
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="konrad" />
<property name="javax.persistence.jdbc.password" value="konrad" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/bazahealthhelper" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>

Method not found exception on MethodExpression.invoke()

I have a need to programmatically call/invoke a method in one of my backing beans. I've looked at several examples, and from what I can see, this "should" work.
My code:
UIData data = (UIData)component;
fc = FacesContext.getCurrentInstance();
elc = fc.getELContext();
elFactory = fc.getApplication().getExpressionFactory();
mexp =
elFactory.createMethodExpression(elc, data.getValueExpression("value").getExpressionString(), Result.class, new Class[]{});
Object methodResult = mexp.invoke(elc, null);
The "data.getValueExpresssion("value").getExpressionString() returns the string:
#{reports.customer}
Info about the bean I'm calling (don't know if these are relevant):
Class's managed bean name is "report"
Class is in Session-scope
Class implements Serializable
The access modifier of the method I'm calling is
There are no parameters in the method signature
Method I'm trying to invoke:
public Result getCustomer() {
Result result = null;
try {
...perform database call
} catch (Exception e) {
log.error(e);
}
return result;
}
Stack-Trace Excerpt
SEVERE: javax.el.MethodNotFoundException: Method not found: com.npp.beans.reports.SharebackReportsBean#1ebf0d3.customer()
javax.faces.el.EvaluationException: javax.el.MethodNotFoundException: Method not found: com.npp.beans.reports.SharebackReportsBean#1ebf0d3.customer()
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:98)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
...
Caused by: javax.el.MethodNotFoundException: Method not found: com.npp.beans.reports.SharebackReportsBean#1ebf0d3.customer()
at com.sun.el.util.ReflectionUtil.getMethod(ReflectionUtil.java:155)
at com.sun.el.parser.AstValue.invoke(AstValue.java:231)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.npp.business.TableToExcelManager.initExcelWorker(TableToExcelManager.java:247)
at com.npp.beans.reports.SharebackReportsBean.exportToExcel(SharebackReportsBean.java:439)
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 com.sun.el.parser.AstValue.invoke(AstValue.java:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:102)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
... 26 more
Mar 23, 2011 11:29:34 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{reports.exportToExcel}: javax.el.MethodNotFoundException: Method not found: com.npp.beans.reports.SharebackReportsBean#1ebf0d3.customer()
javax.faces.FacesException: #{reports.exportToExcel}: javax.el.MethodNotFoundException: Method not found: com.npp.beans.reports.SharebackReportsBean#1ebf0d3.customer()
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:114)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
Any help on this is greatly appreciated!
You're attempting to treat a value expression as a method expression. This isn't going to work. Value expressions points to getter methods (and thus get can be omitted) while method expressions points to action methods, possibly taking an extra argument. Since you already have the ValueExpression, just get value from it directly instead of attempting to treat it like a MethodExpression.
Result result = (Result) data.getValueExpression("value").getValue(elc);
You should not change the EL string in the view. Just keep it value="#{reports.customer}". Otherwise it won't work in the normal view.

Resources