weblogic ejb ComplianceException - java

I try to deploy an application which uses EJB on weblogic 10.3. I use the framework seam 2.2.0
I created an EJB project and en EAR project with workshop.
When I compile the project, I get this error:
weblogic.ejb.container.compliance.ComplianceException: No business interface, component interface or web service endpoint interface found for Session Bean Authenticator
Here is the bean code:
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.contexts.SessionContext;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.faces.Redirect;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.jboss.seam.security.crypto.BinTools;
import org.jboss.seam.security.management.IdentityManager;
import org.jboss.seam.security.management.JpaIdentityStore;
#Stateless
#Local
#Name("authenticator")
public class Authenticator {
}
And here is the exception:
weblogic.ejb.container.compliance.ComplianceException: No business interface, component interface or web service endpoint interface found for Session Bean Authenticator
at weblogic.ejb.container.compliance.SessionBeanClassChecker.checkInterfacesExist(SessionBeanClassChecker.java:177)
at weblogic.ejb.container.compliance.Ejb30SessionBeanClassChecker.checkInterfacesExist(Ejb30SessionBeanClassChecker.java:27)
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 weblogic.ejb.container.compliance.EJBComplianceChecker.check(EJBComplianceChecker.java:337)
at weblogic.ejb.container.compliance.EJBComplianceChecker.checkDeploymentInfo(EJBComplianceChecker.java:286)
at weblogic.ejb.container.ejbc.EJBCompiler.complianceCheckJar(EJBCompiler.java:952)
at weblogic.ejb.container.ejbc.EJBCompiler.checkCompliance(EJBCompiler.java:920)
at weblogic.ejb.container.ejbc.EJBCompiler.doCompile(EJBCompiler.java:246)
at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:552)
at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:519)
at weblogic.ejb.container.deployer.EJBDeployer.runEJBC(EJBDeployer.java:393)
at weblogic.ejb.container.deployer.EJBDeployer.compileJar(EJBDeployer.java:715)
at weblogic.ejb.container.deployer.EJBDeployer.compileIfNecessary(EJBDeployer.java:618)
at weblogic.ejb.container.deployer.EJBDeployer.prepare(EJBDeployer.java:1154)
at weblogic.ejb.container.deployer.EJBModule.prepare(EJBModule.java:425)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:93)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:387)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:37)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:58)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:42)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:615)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:37)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:191)
at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:16)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:155)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.createAndPrepareContainer(ActivateOperation.java:197)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:89)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:217)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:723)
at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1190)
at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:248)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:159)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:157)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$000(DeploymentReceiverCallbackDeliverer.java:12)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$1.run(DeploymentReceiverCallbackDeliverer.java:45)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:516)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
at weblogic.ejb.container.compliance.EJBComplianceChecker.check(EJBComplianceChecker.java:327)
at weblogic.ejb.container.compliance.EJBComplianceChecker.checkDeploymentInfo(EJBComplianceChecker.java:286)
at weblogic.ejb.container.ejbc.EJBCompiler.complianceCheckJar(EJBCompiler.java:952)
at weblogic.ejb.container.ejbc.EJBCompiler.checkCompliance(EJBCompiler.java:920)
at weblogic.ejb.container.ejbc.EJBCompiler.doCompile(EJBCompiler.java:246)
at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:552)
at weblogic.ejb.container.ejbc.EJBCompiler.compileEJB(EJBCompiler.java:519)
at weblogic.ejb.container.deployer.EJBDeployer.runEJBC(EJBDeployer.java:393)
at weblogic.ejb.container.deployer.EJBDeployer.compileJar(EJBDeployer.java:715)
at weblogic.ejb.container.deployer.EJBDeployer.compileIfNecessary(EJBDeployer.java:618)
at weblogic.ejb.container.deployer.EJBDeployer.prepare(EJBDeployer.java:1154)
at weblogic.ejb.container.deployer.EJBModule.prepare(EJBModule.java:425)
at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:93)
at weblogic.application.internal.flow.DeploymentCallbackFlow$1.next(DeploymentCallbackFlow.java:387)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:37)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:58)
at weblogic.application.internal.flow.DeploymentCallbackFlow.prepare(DeploymentCallbackFlow.java:42)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:615)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:37)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:191)
at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:16)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:155)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.createAndPrepareContainer(ActivateOperation.java:197)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:89)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:217)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:723)
at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1190)
at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:248)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:159)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:157)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$000(DeploymentReceiverCallbackDeliverer.java:12)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$1.run(DeploymentReceiverCallbackDeliverer.java:45)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:516)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
>
Here is my ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
version="3.0">
<interceptors>
<interceptor>
<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
</interceptor>
</interceptors>
<assembly-descriptor>
<interceptor-binding>
<ejb-name>Authentificator<ejb-name>
<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
</ejb-jar>
I don't understand my error.
Thanks for your help.

This happens because Weblogic is looking for an interface that Authenticator implements.
Change to:
#Stateless
#Name("authenticator")
public class Authenticator implements AuthenticatorLocal {
#Override
public void oneMethod()
{
//enter code here
}
}
#Local
public interface AuthenticatorLocal {
void oneMethod();
}
Note: the interface must have at least one overridden method, otherwise you'll get the same error again.

Happens because weblogic will search for an interface for EJB Local service:
#Stateless
#Local
#Name("authenticator")
public class Authenticator {
}
if you implement an interface, and provide it to EJB this problem is solved. Like this:
#Stateless
#Local(IAuthenticator.class)
#Name("authenticator")
public class Authenticator implements IAuthenticator{
//your business logic
}
public interface IAuthenticator {
// interface
}

Related

Resource not injecting Datasource from web.xml - Java Framework - Payara Micro - NullPointerException

My Payara REST API is working fine without DB Connection, and also Postgres localhost connection works fine through DriverManager i.e.:
Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "pass#123")
However, Datasource for postgresql in web.xml & Resource is throwing NullPointerException in below code:
public class AppService {
#Resource(name="java:global/esWf")
DataSource ds;
public Response test (
...
Connection conn = ds.getConnection();
...
WEB-INF/web.xml: -
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<display-name>PG-DataSource</display-name>
<data-source>
<name>java:global/esWf</name>
<class-name>org.postgresql.ds.PGSimpleDataSource</class-name>
<url>jdbc:postgresql://localhost:5432/postgres</url>
<user>postgres</user>
<password>pass#123</password>
<property>
<name>fish.payara.slow-query-threshold-in-seconds</name>
<value>5</value>
</property>
</data-source>
</web-app>
I have also tried replacing url with separate elements for server, port, db name!
This is first time I am trying to connect via Datasource & Resource, and could be am missing something minor!
Links referred: - https://blog.payara.fish/setting-up-a-data-source-in-payara-micro,
https://dzone.com/articles/easy-java-ee-microservices-with-payara-micro,
Payara DB Examples etc
Error: -
java.lang.NullPointerException
at es.dms.DmsSrv.test(DmsSrv.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:176)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:469)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:391)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:80)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:253)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
at org.glassfish.jersey.internal.Errors.process(Errors.java:244)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:232)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:680)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:394)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:366)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:319)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1636)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:259)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:757)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:577)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:158)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
at java.lang.Thread.run(Thread.java:748)
This looks like the same issue as in resource injection in cdi bean.
Injection using #Resource doesn't work in plain CDI beans and JAX-RS resources. It only works in enterprise beans.
You have 2 options:
turn your bean into a stateless EJB - just add #Stateless annotation to the class:
#Stateless
#RequestScoped
#Path("app")
public class AppService {
#Resource(name="java:global/esWf")
DataSource ds;
public Response test (
Create a CDI producer and then inject the datasource as a CDI bean. The best practice is to use a qualifier to mark which DS you want to inject (in case there are multiple datasources in the app):
#Qualifier
#Retention(RUNTIME)
#Target({METHOD, FIELD, PARAMETER, TYPE})
public #interface Eswf {
}
---------------
#RequestScoped
public DsProducer {
#Produces
#Resource(name="java:global/esWf")
#Eswf
Datasource eswfDatasource;
}
------------------
#RequestScoped
#Path("app")
public class AppService {
#Inject
#Eswf
DataSource ds;
public Response test (
P.S. I think that you also need to change the JNDI name to use the java:app/ namespace instad of java:global/ because the DS should be available only to the deployed application. You can test whether you can retrieve the DS by JNDI name using `new InitialContext().lookup("java:global/esWf"). That should work anywhere in your application, not only in EJBs.

No processor claimed any of these annotations: javax.servlet.annotation.MultipartConfig

Why isn't a MultipartConfig annotation processor working on the annotated class? When I build my Java project with Gradle I get this warning:
No processor claimed any of these annotations: javax.servlet.annotation.MultipartConfig,javax.servlet.annotation.WebServlet
And when I send a file to that servlet from a form I get
HTTP ERROR 500
Problem accessing /historyUpload/upload. Reason:
Server Error
Caused by:
java.lang.IllegalStateException: No multipart config for servlet
at org.eclipse.jetty.server.Request.getParts(Request.java:2303)
at org.eclipse.jetty.server.Request.getParts(Request.java:2290)
at org.eclipse.jetty.server.Request.getPart(Request.java:2279)
at javax.servlet.http.HttpServletRequestWrapper.getPart(HttpServletRequestWrapper.java:386)
at com.mycom.UploadServlet.doPost(UploadServlet.java:32)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
[...]
But I have javax.servlet-api-3.1.0.jar in my build.gradle - my project module includes several other HttpServlet classes that build and execute OK against it. That JAR does include javax.servlet.annotation.MultipartConfig .
UploadServlet.java :
package com.mycom.uploadservlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#SuppressWarnings("serial")
#MultipartConfig(location="/tmp/upload", fileSizeThreshold=1024*1024, maxFileSize=1024*1024*50)
public class UploadServlet extends HttpServlet
{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
out.printf("Got part: name=%s, size=%d%n",req.getPart("file").getName(), req.getPart("file").getSize());
int i=0;
for(Part part: req.getParts())
{
out.printf("Got part: name=%s, size=%d%n",part.getName(), part.getSize());
part.write(String.format("part-%02d.dat",i++));
}
}
}
The problem was that I defined a <servlet> configuration in web.xml , that overrides the #WebServlet() annotation on the class UploadServlet. I didn't use an #WebServlet annotation, because I had the <servlet> configuration in web.xml. But that overriding also overrides any #MultipartConfig annotation on the class UploadServlet, even if no <multipart-config> block is included in the <servlet> block. So to process a form of enctype="multipart/form-data" either the <servlet> block in web.xml must include a <multipart-config> block, or no <servlet> block in web.xml and instead annotate the class with #MultipartConfig() (and so also #WebServlet).
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.mycom.UploadServlet</servlet-class>
<multipart-config>
<max-file-size>10485760</max-file-size>
<max-request-size>20971520</max-request-size>
<file-size-threshold>5242880</file-size-threshold>
</multipart-config>
</servlet>

get java.lang.ArrayStoreException on Springboot and ehcache

I have a method that calls a webservice and for same input arguments, I want the result to be cached. So, here is what i did so far:
The main class:
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.ClassPathResource;
#EnableCaching
#ComponentScan
#SpringBootApplication
public class AccServer extends SpringBootServletInitializer {
#Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
#Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
}
}
Method to cache:
import java.util.List;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
#Service
public class SomeClass implements ISomeClass {
#Override
#Cacheable("acc")
public List<Integer> trs() {
return webSrv.trs();
}
}
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
<diskStore path="java.io.tmpdir" />
<cache name="acc" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
</ehcache>
And I get:
Caused by: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
at sun.reflect.annotation.AnnotationParser.parseClassArray(Unknown Source)
at sun.reflect.annotation.AnnotationParser.parseArray(Unknown Source)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(Unknown Source)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(Unknown Source)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(Unknown Source)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(Unknown Source)
at java.lang.Class.createAnnotationData(Unknown Source)
at java.lang.Class.annotationData(Unknown Source)
at java.lang.Class.createAnnotationData(Unknown Source)
at java.lang.Class.annotationData(Unknown Source)
at java.lang.Class.getAnnotation(Unknown Source)
at org.springframework.cache.annotation.SpringCacheAnnotationParser.getAnnotations(SpringCacheAnnotationParser.java:201)
at org.springframework.cache.annotation.SpringCacheAnnotationParser.parseCacheAnnotations(SpringCacheAnnotationParser.java:64)
at org.springframework.cache.annotation.SpringCacheAnnotationParser.parseCacheAnnotations(SpringCacheAnnotationParser.java:52)
at org.springframework.cache.annotation.AnnotationCacheOperationSource$1.getCacheOperations(AnnotationCacheOperationSource.java:113)
at org.springframework.cache.annotation.AnnotationCacheOperationSource.determineCacheOperations(AnnotationCacheOperationSource.java:142)
at org.springframework.cache.annotation.AnnotationCacheOperationSource.findCacheOperations(AnnotationCacheOperationSource.java:110)
at org.springframework.cache.interceptor.AbstractFallbackCacheOperationSource.computeCacheOperations(AbstractFallbackCacheOperationSource.java:142)
at org.springframework.cache.interceptor.AbstractFallbackCacheOperationSource.getCacheOperations(AbstractFallbackCacheOperationSource.java:97)
at org.springframework.cache.interceptor.CacheOperationSourcePointcut.matches(CacheOperationSourcePointcut.java:39)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:211)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:248)
at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:280)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:118)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:88)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:69)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:346)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:298)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
... 135 more
I also use #Cacheable("acc") annotation for the method which should be cached for the result.
Any answers would be appreciated.
The issue is with the #Cacheable trs() method (of your #Service SomeClass class) which is NOT returning List<Integer> object because of which you are getting sun.reflect.annotation.TypeNotPresentExceptionProxy exception.
You need to ensure that trs() is returning the List<Integer> object.
Thanks to fellows how contributed on this question, finally after long time of debugging, I just found that there is need for excluding two dependencies from project, so that it becomes:
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</exclusion>
That exception means something attempted to do a lookup on an annotation that's not present on the classpath. Unfortunately, the JDK isn't telling us much about it but I think we've improved the error message in recent version of the framework (and therefore boot).
You could also add a breakpoint in the faulty code and it will tell you what it's trying to resolve. That should give you a hint of what the missing annotation is. Most of the time, this isn't strictly related to the component that does the lookup (i.e. it might very well be unrelated to caching). If you share a sample app, we could easily figure it out.

CDI (Weld), DeltaSpike, Tomcat and persistence.xml

I am setting up a new project using Tomcat, Weld (for CDI) and DeltaSpike (Data, JPA and JSF modules)
I have reached the point now where I am trying to create a JPA repository (backed by Hibernate) by following the directions in the DeltaSpike documentation (http://deltaspike.apache.org/documentation/data.html).
I am struggling to hook up the persistence unit in the way the documentation describes as my EntityManagerFactory object is always null
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
public class EntityManagerProducer {
#PersistenceUnit(unitName = "srdPersistenceUnit")
private EntityManagerFactory emf;
#Produces // you can also make this #RequestScoped
public EntityManager create() {
return emf.createEntityManager();
}
public void close(#Disposes EntityManager em) {
if (em.isOpen()) {
em.close();
}
}
}
I have created a persistence.xml file which is in the /META-INF/ directory of the jar file that contains my service/data layer
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="srdPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>java:comp/env/jdbc/srdDCP</non-jta-data-source>
<properties>
</properties>
</persistence-unit>
</persistence>
I was previously using Spring to handle dependency injection and the JPA stuff which worked fine so I know my data source is set up correctly as a Tomcat JNDI resource.
Now however I see this exception (suggesting that the EntityManagerFactory is not being injected)
Caused by: java.lang.NullPointerException
at testproj.data.entity.EntityManagerProducer.create(EntityManagerProducer.java:18)
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.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:78)
at org.jboss.weld.injection.producer.ProducerMethodProducer.produce(ProducerMethodProducer.java:95)
at org.jboss.weld.injection.producer.AbstractMemberProducer.produce(AbstractMemberProducer.java:167)
at org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:183)
at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)
at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:101)
at org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:761)
at org.jboss.weld.bean.builtin.InstanceImpl.getBeanInstance(InstanceImpl.java:179)
at org.jboss.weld.bean.builtin.InstanceImpl.get(InstanceImpl.java:99)
at org.apache.deltaspike.data.impl.handler.EntityManagerLookup.lookupFor(EntityManagerLookup.java:58)
at org.apache.deltaspike.data.impl.handler.QueryHandler.createContext(QueryHandler.java:104)
at org.apache.deltaspike.data.impl.handler.QueryHandler.invoke(QueryHandler.java:77)
I suspect I have missed something in the setting up of the persistence unit.
What more do I need to do to create a valid persistence unit backed by hibernate jpa linked to my datasource?

Spring MVC configuration problems

i have some problems with configuring Spring MVC. I made a maven multi module project with the following modules:
/api
/domain
/repositories
/webapp
I like to share the domain and the repositories between the api and the webapp (both web projects). First i want to configure the webapp to use the repositories module so i added the dependencies in the xml file like this:
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>domain</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>repositories</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
And my controller in the webapp module looks like this:
package com.mywebapp.webapp;
import com.mywebapp.domain.Person;
import com.mywebapp.repositories.services.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
#Configuration
#ComponentScan("com.mywebapp.repositories")
public class PersonController {
#Autowired
PersonService personservice;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
Person p = new Person();
p.age = 23;
p.firstName = "John";
p.lastName = "Doe";
personservice.createNewPerson(p);
model.addAttribute("message", "Hello world!");
return "index";
}
}
In my webapp module i try to load configuration files in my web.xml like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/META-INF/persistence-context.xml, classpath:/META-INF/service-context.xml</param-value>
</context-param>
These files cannot be found so i get the following error:
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [META-INF/persistence-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [META-INF/persistence-context.xml] cannot be opened because it does not exist
These files are in the repositories module so my first question is how can i make Spring to find these files?
I also have trouble Autowiring the PersonService to my Controller class did i forget to configure something in my XML?
Here is the error message:
[INFO] [talledLocalContainer] SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
[INFO] [talledLocalContainer] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mywebapp.repositories.repository.PersonRepository com.mywebapp.repositories.services.PersonServiceImpl.personRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mywebapp.repositories.repository.PersonRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
PersonServiceImple.java:
package com.mywebapp.repositories.services;
import com.mywebapp.domain.Person;
import com.mywebapp.repositories.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
#Service
public class PersonServiceImpl implements PersonService{
#Autowired
public PersonRepository personRepository;
#Autowired
public MongoTemplate personTemplate;
#Override
public Person createNewPerson(Person person) {
return personRepository.save(person);
}
}
PersonService.java
package com.mywebapp.repositories.services;
import com.mywebapp.domain.Person;
public interface PersonService {
Person createNewPerson(Person person);
}
PersonRepository.java:
package com.mywebapp.repositories.repository;
import com.mywebapp.domain.Person;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.math.BigInteger;
#Repository
public interface PersonRepository extends MongoRepository<Person, BigInteger> {
}
persistance-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:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation=
"http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<context:property-placeholder location="classpath:mongo.properties"/>
<mongo:mongo host="${mongo.host}" port="${mongo.port}" id="mongo">
<mongo:options
connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
auto-connect-retry="${mongo.autoConnectRetry}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}"
slave-ok="${mongo.slaveOk}"
write-number="1"
write-timeout="0"
write-fsync="true"/>
</mongo:mongo>
<mongo:db-factory dbname="person" mongo-ref="mongo" id="mongoDbFactory"/>
<bean id="personTemplate" name="personTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<mongo:repositories base-package="com.mywebapp.repositories.repository" mongo-template-ref="personTemplate">
<mongo:repository id="personRepository" repository-impl-postfix="PersonRepository" mongo-template-ref="personTemplate" create-query-indexes="true"/>
</mongo:repositories>
Thanks

Categories