I am a newbie to infinispan and would like to seek help about issue below.
I tried to start a infinispan cache on an ejb, such that it should be shared among several applications.
#Singleton
public class CSysAppCacheServiceImpl implements CSysAppCacheService {
private DefaultCacheManager cacheManager;
private Cache testingCache;
#EJB(name = "postService")
private CSysPostDao postService;
#EJB(name = "roleService")
private CSysRoleDao roleService;
protected Map<String, List<CSysRole>> sysRoleMap;
protected Map<String, List<CSysPost>> sysPostMap;
protected List<CSysRole> sysRoleList;
protected List<CSysPost> sysPostList;
#PostConstruct
public void init() {
// perform some initialization logic
try {
System.out.println("init CacheManager start");
cacheManager = new DefaultCacheManager("/demo-infinispan.xml");
System.out.println("init CacheManager end");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
testingCache = cacheManager.getCache("testingCache");
preloadCache();
}
// Pre-load cache when server startup
public void preloadCache() {
for (CacheKey ck : CacheKey.values()) {
resetCache(ck);
}
}
public void resetCache(CacheKey key) {
if (key == null) {
for (CacheKey ck : CacheKey.values()) {
resetCache(ck);
}
} else if (key.equals(CacheKey.SYS_ROLE_LIST)) {
this.sysRoleList = roleService.findAllRole();
setupCacheList(CacheKey.SYS_ROLE_LIST, sysRoleList);
} else if (key.equals(CacheKey.SYS_POST_LIST)) {
this.sysPostList = postService.findAllPost();
setupCacheList(CacheKey.SYS_POST_LIST, sysPostList);
}
}
protected <T> void setupCacheList(CacheKey key, List<T> list) {
testingCache.put(key, list);
}
public List<Object> getCacheList(CacheKey key) {
return (List<Object>) testingCache.get(key);
}
public List<Object> getCacheList(String keyString) {
return (List<Object>) testingCache.get(keyString);
}
#SuppressWarnings("unchecked")
public <K, V> Map<K, V> getCacheMap(CacheKey key) {
return (Map<K, V>) testingCache.get(key);
}
public Map<String, List<CSysRole>> getCSysRoleMap() {
sysRoleMap = getCacheMap(CacheKey.SYS_ROLE_LIST);
if (MapUtils.isEmpty(sysRoleMap)) {
resetCache(CacheKey.SYS_ROLE_LIST);
}
return sysRoleMap;
}
public Map<String, List<CSysPost>> getCSysPostMap() {
sysRoleMap = getCacheMap(CacheKey.SYS_POST_LIST);
if (MapUtils.isEmpty(sysPostMap)) {
resetCache(CacheKey.SYS_POST_LIST);
}
return sysPostMap;
}
}
The ejb is init via following class
#ViewScoped
#Named
public class CacheView implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LogManager.getLogger(CacheView.class);
public static final String FNCT_ID = "SAMPLCACH";
private List<String> cacheKeyList;
// private Map<K, V> selectedMap;
private CacheKey selectedKey;
private List<Object> selectedList;
#EJB CSysAppCacheService appScopeCache;
#PostConstruct
public void init() {
appScopeCache.init();
}
...
}}}}
But when the application start, following exception raised
Caused by: java.lang.NoClassDefFoundError: org/jboss/marshalling/ClassResolver
at org.infinispan.configuration.global.SerializationConfiguration.<clinit>(SerializationConfiguration.java:16)
at org.infinispan.configuration.global.SerializationConfigurationBuilder.<init>(SerializationConfigurationBuilder.java:27)
at org.infinispan.configuration.global.GlobalConfigurationBuilder.<init>(GlobalConfigurationBuilder.java:43)
at org.infinispan.configuration.parsing.ConfigurationBuilderHolder.<init>(ConfigurationBuilderHolder.java:25)
at org.infinispan.configuration.parsing.ParserRegistry.parse(ParserRegistry.java:122)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:311)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:286)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:274)
at CSysAppCacheServiceImpl.init(CSysAppCacheServiceImpl.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.as.ee.component.ManagedReferenceLifecycleMethodInterceptor.processInvocation(ManagedReferenceLifecycleMethodInterceptor.java:96)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.doLifecycleInterception(Jsr299BindingsInterceptor.java:122)
at org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:111)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:509)
at org.jboss.weld.module.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:72)
at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:89)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.injection.WeldInjectionInterceptor.processInvocation(WeldInjectionInterceptor.java:53)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.ManagedReferenceFieldInjectionInterceptorFactory$ManagedReferenceFieldInjectionInterceptor.processInvocation(ManagedReferenceFieldInjectionInterceptorFactory.java:112)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.ManagedReferenceFieldInjectionInterceptorFactory$ManagedReferenceFieldInjectionInterceptor.processInvocation(ManagedReferenceFieldInjectionInterceptorFactory.java:112)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.AroundConstructInterceptorFactory$1.processInvocation(AroundConstructInterceptorFactory.java:28)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.injection.WeldInterceptorInjectionInterceptor.processInvocation(WeldInterceptorInjectionInterceptor.java:56)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.interceptors.Jsr299BindingsCreateInterceptor.processInvocation(Jsr299BindingsCreateInterceptor.java:105)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:237)
... 150 more
The problem should be at line
cacheManager = new DefaultCacheManager("/demo-infinispan.xml");
the xml is just a simple standlone cache as below
<?xml version="1.0" encoding="UTF-8"?>
<infinispan
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:infinispan:config:9.0 http://www.infinispan.org/schemas/infinispan-config-9.0.xsd"
xmlns="urn:infinispan:config:9.0">
<cache-container name="testing" default-cache="default">
<local-cache name="default">
<eviction max-entries="5000" strategy="LIRS" />
</local-cache>
</cache-container>
</infinispan>
I tried to put the demo-infinispan.xml in either of the following path, but still exception raised
1) same folder of the java bean
2) src folder of the package
3) same folder of the view bean
Would anyone advise where the xml should I put?
Thanks.
Best Regards,
The issue is solved due to missing libraries
Related
I have a simple spring-data-cassandra project that tries to insert multiple entities using
<S extends T> Iterable<S> save(Iterable<S> entities)
of the CassandraRepository class.
However when I use version 2.0.0.M1 (works in previous versions), I get the following error,
Exception in thread "main" org.springframework.data.cassandra.mapping.VerifierMappingExceptions: java.util.ArrayList:
- Cassandra entities must be annotated with either #Persistent, #Table, #UserDefinedType or #PrimaryKeyClass
at org.springframework.data.cassandra.mapping.CompositeCassandraPersistentEntityMetadataVerifier$PersistentAnnotationVerifier.verify(CompositeCassandraPersistentEntityMetadataVerifier.java:92)
at org.springframework.data.cassandra.mapping.CompositeCassandraPersistentEntityMetadataVerifier.verify(CompositeCassandraPersistentEntityMetadataVerifier.java:70)
at org.springframework.data.cassandra.mapping.BasicCassandraPersistentEntity.verify(BasicCassandraPersistentEntity.java:160)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:332)
at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.addPersistentEntity(BasicCassandraMappingContext.java:381)
at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.addPersistentEntity(BasicCassandraMappingContext.java:65)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:185)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:145)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:70)
at org.springframework.data.cassandra.core.CassandraTemplate.getPersistentEntity(CassandraTemplate.java:427)
at org.springframework.data.cassandra.core.CassandraTemplate.getTableName(CassandraTemplate.java:443)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:314)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:302)
at org.springframework.data.cassandra.repository.support.SimpleCassandraRepository.save(SimpleCassandraRepository.java:66)
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.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.executeMethodOn(RepositoryFactorySupport.java:553)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:538)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:479)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy34.save(Unknown Source)
My main class, App.java
public class App
{
public static void main(String[] args) {
ApplicationContext context =new AnnotationConfigApplicationContext(CassandraConfig.class);
CustomerRepo repo=context.getBean(CustomerRepo.class);
List<Customer> customers=new ArrayList<Customer>();
Customer cust=new Customer();
cust.SetId("142");
cust.setName("Mayor");
cust.setAcc_type("new");
cust.setAcc_name("savings");
cust.setSegment("Normal");
customers.add(cust);
Customer cust1 = new Customer();
cust1.SetId("143");
cust1.setName("Final");
cust1.setAcc_type("new");
cust1.setAcc_name("savings");
cust1.setSegment("Normal");
customers.add(cust1);
repo.save(customers);
}
}
The entity class, Customer.java
#Table(value="Customer")
public class Customer {
#PrimaryKeyColumn(name = "id",ordinal = 1,type = PrimaryKeyType.PARTITIONED)
private String id;
#Column(value ="name")
private String name;
#Column(value = "acc_name")
private String acc_name;
#Column(value = "acc_type")
private String acc_type;
#Column(value = "segment")
private String segment;
public Customer(String id, String name, String acc_name, String acc_type,
String segment) {
this.id=id;
this.name=name;
this.acc_name=acc_name;
this.acc_type=acc_type;
this.segment=segment;
}
public Customer() {
}
public void SetId(String id)
{
this.id=id;
}
public void setName(String name)
{
this.name=name;
}
public void setAcc_name(String acc_name)
{
this.acc_name=acc_name;
}
public void setAcc_type(String acc_type)
{
this.acc_type=acc_type;
}
public void setSegment(String segment)
{
this.segment=segment;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getAcc_name() {
return acc_name;
}
public String getAcc_type() {
return acc_type;
}
public String getSegment() {
return segment;
}
}
And finally, the repository, CustomerRepo.java
import com.Entity.Customer;
public interface CustomerRepo extends CassandraRepository<Customer> {
}
Is this an issue (I haven't been able to find via Goolge or the site), or am I missing some annotations ?
For batch queries, use CassandraTemplate helps to insert batch of operations with multiple entities. This is available with Spring Data Cassandra.
example code:
CassandraBatchOperations batchOps = cassandraTemplate.batchOps();
batchOps(movieByGenre);
batchOps(movieByActor);
batchOps.insert(movie);
batchOps.execute();
This will use Cassandra native Batch operation internally.
I'm working on a JavaEE application with EJB.
I have an Entity called Medico which code is:
#Entity
public class Medico implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public Medico(String nome_medico, String morada_medico,
String esp, GregorianCalendar dnasc_medico, int tel_medico) { //construtor parametrico
super();
this.nome_medico = nome_medico;
this.morada_medico = morada_medico;
this.esp = esp;
this.dnasc_medico = dnasc_medico;
this.tel_medico = tel_medico;
}
#Id
#GeneratedValue
private int cod_medico; //bi
private String nome_medico;
private String morada_medico;
private String esp;
#Temporal(TemporalType.DATE)
private GregorianCalendar dnasc_medico;
private int tel_medico;
private ArrayList<GregorianCalendar> agenda_consultas;
private ArrayList<GregorianCalendar> agenda_atos;
private int total_atos;
private int total_presc;
public int getTotal_presc() {
return total_presc;
}
public void setTotal_presc(int total_presc) {
this.total_presc = total_presc;
}
public Medico(){ //construtor vazio
super();
}
public int getTotal_atos() {
return total_atos;
}
public void setTotal_atos(int total_atos) {
this.total_atos = total_atos;
}
public ArrayList<GregorianCalendar> getAgenda_consultas() {
return agenda_consultas;
}
public void setAgenda_consultas(ArrayList<GregorianCalendar> agenda_consultas) {
this.agenda_consultas = agenda_consultas;
}
public ArrayList<GregorianCalendar> getAgenda_atos() {
return agenda_atos;
}
public void setAgenda_atos(ArrayList<GregorianCalendar> agenda_atos) {
this.agenda_atos = agenda_atos;
}
public int getCod_medico() {
return cod_medico;
}
public void setCod_medico(int cod_medico) {
this.cod_medico = cod_medico;
}
public String getNome_medico() {
return nome_medico;
}
public void setNome_medico(String nome_medico) {
this.nome_medico = nome_medico;
}
public String getMorada_medico() {
return morada_medico;
}
public void setMorada_medico(String morada_medico) {
this.morada_medico = morada_medico;
}
public String getEsp() {
return esp;
}
public void setEsp(String esp) {
this.esp = esp;
}
public GregorianCalendar getDnasc_medico() {
return dnasc_medico;
}
public void setDnasc_medico(GregorianCalendar dnasc_medico) {
this.dnasc_medico = dnasc_medico;
}
public int getTel_medico() {
return tel_medico;
}
public void setTel_medico(int tel_medico) {
this.tel_medico = tel_medico;
}
#Override
public String toString() {
return "Medico [cod_medico=" + cod_medico + ", nome_medico="
+ nome_medico + ", morada_medico=" + morada_medico + ", esp="
+ esp + ", dnasc_medico=" + dnasc_medico + ", tel_medico="
+ tel_medico + "]";
}
}
Then I created a session bean implementation class:
#Stateless
public class HospitalManagement implements AdministradorSessionRemote,GestorSessionRemote {
/**
* Default constructor.
*/
#PersistenceContext(unitName="Hospital")
private EntityManager em;
public HospitalManagement() {
// TODO Auto-generated constructor stub
}
#Override
public String cria_medico(String nome_medico, String morada_medico,
String esp, GregorianCalendar dnasc_medico, int tel_medico) {
Medico md = new Medico (nome_medico, morada_medico, esp, dnasc_medico,tel_medico);
em.persist(md);
return "Medico "+Integer.toString(md.getCod_medico())+" criado!";
}
This class implements two interfaces, but the method above is only used in the following one:
#Remote
public interface GestorSessionRemote {
public String cria_medico(String nome_medico,String morada_medico,String esp,GregorianCalendar dnasc_medico, int tel_medico);
public String procura_nome_medico(String nome);
public String procura_cod_medico(int cod);
public String altera_morada_med(int cod, String morada);
public String altera_telemovel_med(int cod, int tel);
Then I created a client:
public class GestorClient {
public static void main(String[] args){
InitialContext ctx =new InitialContext();
GestorSessionRemote g=(GestorSessionRemote)ctx.lookup("java:global/HospitalEAR/Hospital/HospitalManagement!Sessions.GestorSessionRemote");
System.out.println(g.cria_medico(nomem, moradam, esp,cal,telm));
where the parameters of the method are obtained by scannig from the keyboard.
I've also created the following persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Hospital">
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
When I try to deploy the application, an error occurs. Here is the complete stacktrace:
Exception in thread "main" javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy236.cria_medico(Unknown Source)
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:483)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName Hospital
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:158)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:281)
at Sessions.HospitalManagement.cria_medico(HospitalManagement.java:45)
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:483)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:55)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
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:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
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:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:205)
... 19 more
Could someone help me understand the reason why this is happening?
The obvious problem is that you didn't specify a jta-data-source and the transaction-type in your persistence.xml.
A jta-data-source is specified like this:
<persistence-unit name="Hospital">
<jta-data-source>jdbc/sample</jta-data-source>
</persistence-unit>
You have to create the JDBC resource in your Glassfish instance. To do this open the Glassfish Admin GUI under http://localhost:4848 and create a Connection Pool under Resources -> JDBC Connection Pools. Then create a JDBC resource under Resources -> JDBC Resources named jdbc/sample and make it reference the new connection pool.
Further, it looks like the server somehow thinks that you want to use transaction-type RESOURCE_LOCAL which requires that you specify an EntityManagerFactory to get an instance of the EntityManager.
JTA should be the default transaction-type in a Java EE environment but you may have to explicitly specifiy the transaction-type in the persistence.xml like this:
<persistence-unit name="Hospital" transaction-type="JTA">
See also:
persistence.xml different transaction-type attributes
I'm trying to handle maximum upload size exception but all solutions i found failed, I tried implementing HandlerExceptionResolver, #ControllerAdvice and method annotated by #ExceptionHandler(MaxUploadSizeExceededException.class) but nothning helped.
Among the answers to similar questions i found out that it could be because the exception is thrown before the controller is even called but i don't have such insight into this issue so i can't solve it on my own.
Stack trace:
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size of 500000 bytes exceeded; nested exception is org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (1065736) exceeds the configured maximum (500000)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:160)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:139)
at org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:110)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (1065736) exceeds the configured maximum (500000)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:965)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:310)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:334)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
... 20 more
and some parts of my code that handle Multipart resolving and so on ...
SecurityWebAppInitializer.class - I suspect this MultipartFilter might be part of the problem but it has to be there because of this http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html#csrf-multipartfilter
#Order(1)
public class SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer {
#Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}
}
Multipart Configuration
#Configuration
public class MultipartConfig {
#Bean
public MultipartResolver filterMultipartResolver() {
CommonsMultipartResolver filterMultipartResolver = new CommonsMultipartResolver();
filterMultipartResolver.setMaxUploadSize(500000);
return filterMultipartResolver;
}
}
WebAppInitializer.class
#Order(2)
public class WebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {MultipartConfig.class, SecurityConfig.class, PersistenceConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { DispatcherConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
return new Filter[] { characterEncodingFilter};
}
}
If you need some other parts of webapp just ask.
Thanks in advance
if you do not know max upload size then don't set the max upload size.
If you want to restrict the MAX upload size then you need to consider otherwise comment it
Below I have commented the setter to set max upload size.
#Configuration
public class MultipartConfig {
#Bean
public MultipartResolver filterMultipartResolver() {
CommonsMultipartResolver filterMultipartResolver = new CommonsMultipartResolver();
//filterMultipartResolver.setMaxUploadSize(500000);
return filterMultipartResolver;
}
}
I captured it by this class:
#Controller
public class ExceptionHandlerController implements ErrorController, HandlerExceptionResolver{
private static final String PATH = "/error";
Logger log = LoggerFactory.getLogger(ExceptionHandlerController.class);
public String getErrorPath() {
return PATH;
}
#Override
public ModelAndView resolveException(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception exception) {
log.debug("Captured....");
Map<Object, Object> model = new HashMap<Object, Object>();
//all the exception is here and u can specified it by this exception: MaxUploadSizeExceededException
return new ModelAndView("Error", (Map) model);
}
}
I used SpringBoot, so it require me to implements ErrorController. If you don't then do not need to implement it.
Hope it help for someone looking for this situation.
I have 2 plugin projects - generator.ui and generator.core.
The generator.ui depends on generator.core plugin for processes and data manipulation. However wherever there is an API call on generator.core (through static method invocation), I get an exception mentioned below:
org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: de/upb/crc901/serge/generator/Generator
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:63)
at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:243)
at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:224)
at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:167)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.executeItem(HandledContributionItem.java:850).........
Caused by: java.lang.ClassNotFoundException: de.upb.crc901.serge.generator.Generator cannot be found by de.upb.crc901.serge.ui_1.0.0.qualifier
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:421)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:412)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
Now this NoClassDefFoundError always comes for the class which contains static method for object creation as the design pattern followed is "Singleton".
Any help would be greatly appreciated.
Here is the code, From the UI plugin; the configuration hub class:
public class ConfigurationHub implements IConfigurationHub {
private IGenerator generator;
private static IConfigurationHub configurationHub;
/*
* Constructor private to make Singleton
*/
private ConfigurationHub() {
generator = GeneratorFactory.createGenerator(Generator.class);
}
public static synchronized IConfigurationHub getInstance() {
if(null == configurationHub) {
configurationHub = new ConfigurationHub();
}
return configurationHub;
}
}
The GeneratorFactory class is in Generator plugin:
public class GeneratorFactory {
private GeneratorFactory() {}
public static <T extends IGenerator> T createGenerator(Class<T> type) {
try {
return (T) type.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
}
Regards,
Sid
My PujaController.java:
public class PujaController implements Serializable {
private Puja current;
private DataModel items = null;
#EJB
private jpa.sessions.PujaFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PujaController() {
}
public Puja getSelected() {
if (current == null) {
current = new Puja();
current.setPujaPK(new jpa.entities.PujaPK());
selectedItemIndex = -1;
}
return current;
}
private PujaFacade getFacade() {
return ejbFacade;
}
public String creaPuja(Subasta subasta) {
try {
current = new Puja();
current.setPujaPK(new jpa.entities.PujaPK());
selectedItemIndex = -1;
current.getPujaPK().setNroDePuja(0); //AUTO_INCREMENT
Postor postor = AuthenticationPhaseListener.getLoggedInPostor();
current.getPujaPK().setEmail(postor.getEmail());
current.getPujaPK().setSubastaId(subasta.getSubastaId());
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
current.setFechaDePuja(new java.sql.Timestamp(now.getTime()));
current.setMontoAPagar(BigDecimal.ONE);
current.setMontoDePuja(BigDecimal.TEN);
current.setNroDePujas(0);
current.setPagoAcumulado(BigDecimal.ONE);
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PujaCreated"));
return "Puja";
} catch (Exception e) {
System.out.println(e);
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareCreate() {
current = new Puja();
current.setPujaPK(new jpa.entities.PujaPK());
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
current.getPujaPK().setNroDePuja(0); //AUTO_INCREMENT
current.getPujaPK().setEmail(current.getPostor().getEmail());
current.getPujaPK().setSubastaId(current.getSubasta().getSubastaId());
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PujaCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
}
My SubastaController.java:
public class SubastaController implements Serializable {
private Subasta current;
private DataModel items = null;
#EJB
private jpa.sessions.SubastaFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public SubastaController() {
}
public Subasta getSelected() {
if (current == null) {
current = new Subasta();
selectedItemIndex = -1;
}
return current;
}
private SubastaFacade getFacade() {
return ejbFacade;
}
public String preparePuja() {
current = (Subasta) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Puja";
}
public String pujar() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SubastaUpdated"));
PujaController pc = new PujaController();
pc.creaPuja(current);
return "Puja";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareCreate() {
current = new Subasta();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SubastaCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
}
Hi, trying to learn some JSF, EntityManager API, I getting stuck here: When pujar() is executed, the subasta get updated successfully and then the creaPuja(current) in pujaController is executed. The creaPuja(current) is ok until getFacade().create(current); is execute and give me a NullPointerException. The current object is created and the key are set. I do not find the way to get the references to the Entity Manager to get successfully create puja. I include the Facade java file also. If you can provide some code to explain the problem would be great!!!
The pujaFacade.java:
public class PujaFacade extends AbstractFacade<Puja> {
#PersistenceContext(unitName = "subasta701WPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public PujaFacade() {
super(Puja.class);
}
}
The abstractFacade.java:
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
#PostConstruct
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
#PostConstruct
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Here is the Exception:
INFO: java.lang.NullPointerException
at jsf.PujaController.creaPuja(PujaController.java:146)
at jsf.SubastaController.pujar(SubastaController.java:96)
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:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
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:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
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)
Yes, the getFacade() in null. My question is how I move or assign the current object to getFacade(). There are a member ejbFacade of type PujaFacade, but I need ejbFacade get the value of current (Puja object) so getFacade will not be null. Thank you ...
What are the values of getFacade() and current at the point that the exception is thrown.
Also, can you please post the stack trace from the exception.
Note: In my experience NullPointerException are the result of accessing a method from a null object. In this case, that would mean getFacade() is returning null.
Update:
After reviewing your code I am not sure. You never set ejbFacade in PujaController or SubastaController, but are able to access it in SubastaController but not in PujaController.
Try comparing the jpa.sessions.SubastaFacade implementation with the jpa.sessions.PujaFacade implementation and see if you are missing anything.
For example, does PujaFacade need a #Stateless before the class definition? Should the unit name in #PersistenceContext(unitName = "subasta701WPU") be changed?
You may also want to read these:
Getting Started with Java EE 6 Applications
The Java Persistence API - A Simpler Programming Model for Entity Persistence
A Wikipedia page with some good samples
Let us know how it turns out.