Exception while connecting through Spring Data to MongoDB - mongodb

I am working on some test program for SpringData MongoDB, I have done it same as it's mentioned on http://static.springsource.org/spring-data/data-document/docs/1.0.0.M2/reference/html/#mongo.core. But it's showing exceptions:
package com.springMongo.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Criteria;
import com.springMongo.config.MongoConfig;
import com.springMongo.person.Person;
public class MongoApp {
private static final Log log = LogFactory.getLog(MongoApp.class);
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoConfig.class);
MongoOperations mongoOps = ctx.getBean(MongoOperations.class);
mongoOps.insert(new Person("1234", "Joe"));
log.info(mongoOps.findOne(new Query(Criteria.where("name").is("Joe")), Person.class));
}
}
package com.springMongo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import com.mongodb.Mongo;
/**
* Spring MongoDB configuration file
*
*/
#Configuration
public class MongoConfig extends AbstractMongoConfiguration {
#Override
public Mongo mongo() throws Exception {
return new Mongo("128.0.0.1",10001);
}
#Override
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongo() , "try_db");
}
#Override
public String getDatabaseName() {
// TODO Auto-generated method stub
return null;
}
}
package com.springMongo.person;
public class Person {
private String id;
private String name;
public Person(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}
But after running MongoApp.java, I am getting following exception:
Jan 3, 2012 12:41:28 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#7c64dc11: startup date [Tue Jan 03 12:41:28 IST 2012]; root of context hierarchy
Jan 3, 2012 12:41:29 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2b275d39: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,mongoConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0,mongo,mongoTemplate,mongoDbFactory,mongoMappingContext,mappingMongoConverter]; root of factory hierarchy
Jan 3, 2012 12:41:29 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2b275d39: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,mongoConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0,mongo,mongoTemplate,mongoDbFactory,mongoMappingContext,mappingMongoConverter]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class com.springMongo.config.MongoConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.mongodb.MongoDbFactory org.springframework.data.mongodb.config.AbstractMongoConfiguration.mongoDbFactory() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalArgumentException: Database name must not be empty
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1015)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:911)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:73)
at com.springMongo.core.MongoApp.main(MongoApp.java:21)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.mongodb.MongoDbFactory org.springframework.data.mongodb.config.AbstractMongoConfiguration.mongoDbFactory() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalArgumentException: Database name must not be empty
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:169)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:570)
... 13 more
Caused by: java.lang.IllegalArgumentException: Database name must not be empty
at org.springframework.util.Assert.hasText(Assert.java:162)
at org.springframework.data.mongodb.core.SimpleMongoDbFactory.<init>(SimpleMongoDbFactory.java:58)
at org.springframework.data.mongodb.config.AbstractMongoConfiguration.mongoDbFactory(AbstractMongoConfiguration.java:54)
at com.springMongo.config.MongoConfig$$EnhancerByCGLIB$$2129bffe.CGLIB$mongoDbFactory$3(<generated>)
at com.springMongo.config.MongoConfig$$EnhancerByCGLIB$$2129bffe$$FastClassByCGLIB$$7ac56fd1.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:215)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:280)
at com.springMongo.config.MongoConfig$$EnhancerByCGLIB$$2129bffe.mongoDbFactory(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:149)
... 14 more

Bad IP address? 128.0.0.1 should be 127.0.0.1
You need to specify database name via getDatabaseName()

Related

Spring data reactive Cassandra not creating keyspace on startup - InvalidQueryException: Keyspace 'xxx' does not exist

I am using spring data reactive Cassandra. Given below is my configuration class. My expectation is that when the spring boot application loads it has to connect to Cassandra and create the keyspace. But my application is able to connect to Cassandra but it is not creating the keyspace. I am getting the below exception on startup. Please let me know if i am missing something.
import com.datastax.driver.core.PlainTextAuthProvider;
import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.AbstractReactiveCassandraConfiguration;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.core.cql.keyspace.CreateKeyspaceSpecification;
import org.springframework.data.cassandra.core.cql.keyspace.DropKeyspaceSpecification;
import org.springframework.data.cassandra.core.cql.keyspace.KeyspaceOption;
import org.springframework.data.cassandra.repository.config.EnableReactiveCassandraRepositories;
import java.util.Arrays;
import java.util.List;
#Configuration
#EnableReactiveCassandraRepositories
public class CassandraConfig extends AbstractReactiveCassandraConfiguration {
#Value("${spring.data.cassandra.contactpoints}") private String contactPoints;
#Value("${spring.data.cassandra.port}") private int port;
#Value("${spring.data.cassandra.keyspace-name}") private String keyspace;
#Value("${spring.data.cassandra.username}") private String userName;
#Value("${spring.data.cassandra.password}") private String password;
#Value("${cassandra.basepackages}") private String basePackages;
#Override protected String getKeyspaceName() {
return keyspace;
}
#Override protected String getContactPoints() {
return contactPoints;
}
#Override protected int getPort() {
return port;
}
#Override public SchemaAction getSchemaAction() {
return SchemaAction.CREATE_IF_NOT_EXISTS;
}
#Override public String[] getEntityBasePackages() {
return new String[] {
basePackages
};
}
#Override
public CassandraClusterFactoryBean cluster() {
PlainTextAuthProvider authProvider = new PlainTextAuthProvider(userName, password);
CassandraClusterFactoryBean cluster=new CassandraClusterFactoryBean();
cluster.setJmxReportingEnabled(false);
cluster.setContactPoints(contactPoints);
cluster.setPort(port);
cluster.setAuthProvider(authProvider);
cluster.setReconnectionPolicy(new ConstantReconnectionPolicy(1000));
return cluster;
}
#Override
protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
CreateKeyspaceSpecification specification = CreateKeyspaceSpecification.createKeyspace(keyspace)
.ifNotExists()
.with(KeyspaceOption.DURABLE_WRITES, true);
return Arrays.asList(specification);
}
#Override
protected List<DropKeyspaceSpecification> getKeyspaceDrops() {
return Arrays.asList(DropKeyspaceSpecification.dropKeyspace(keyspace));
}
}
Unsatisfied dependency expressed through constructor parameter 5; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘myRepository': Cannot resolve reference to bean 'reactiveCassandraTemplate' while setting bean property 'reactiveCassandraOperations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reactiveCassandraTemplate' defined in com.company.domain.CassandraConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.core.ReactiveCassandraTemplate]: Factory method 'reactiveCassandraTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reactiveSessionFactory' defined in com.company.domain.CassandraConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.ReactiveSessionFactory]: Factory method 'reactiveSessionFactory' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reactiveSession' defined in com.company.domain.CassandraConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.ReactiveSession]: Factory method 'reactiveSession' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in com.company.domain.CassandraConfig: Invocation of init method failed; nested exception is com.datastax.driver.core.exceptions.InvalidQueryException: Keyspace ‘mykeyspace’ does not exist
Finally got it fixed by the below code. We need to setKeyspaceCreations on CassandraClusterFactoryBean and also enable #ComponentScan.
import com.datastax.driver.core.PlainTextAuthProvider;
import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.*;
import org.springframework.data.cassandra.core.cql.keyspace.CreateKeyspaceSpecification;
import org.springframework.data.cassandra.core.cql.keyspace.DropKeyspaceSpecification;
import org.springframework.data.cassandra.core.cql.keyspace.KeyspaceOption;
import org.springframework.data.cassandra.repository.config.EnableReactiveCassandraRepositories;
import java.util.Arrays;
import java.util.List;
#Configuration
#EnableReactiveCassandraRepositories(basePackages = "com.company.domain.data")
public class CassandraConfig extends AbstractReactiveCassandraConfiguration{
#Value("${spring.data.cassandra.contactpoints}") private String contactPoints;
#Value("${spring.data.cassandra.port}") private int port;
#Value("${spring.data.cassandra.keyspace-name}") private String keyspace;
#Value("${spring.data.cassandra.username}") private String userName;
#Value("${spring.data.cassandra.password}") private String password;
#Value("${cassandra.basepackages}") private String basePackages;
#Override protected String getKeyspaceName() {
return keyspace;
}
#Override protected String getContactPoints() {
return contactPoints;
}
#Override protected int getPort() {
return port;
}
#Override public SchemaAction getSchemaAction() {
return SchemaAction.CREATE_IF_NOT_EXISTS;
}
#Override
public String[] getEntityBasePackages() {
return new String[]{"com.company.domain.data"};
}
#Override
public CassandraClusterFactoryBean cluster() {
PlainTextAuthProvider authProvider = new PlainTextAuthProvider(userName, password);
CassandraClusterFactoryBean cluster=new CassandraClusterFactoryBean();
cluster.setJmxReportingEnabled(false);
cluster.setContactPoints(contactPoints);
cluster.setPort(port);
cluster.setAuthProvider(authProvider);
cluster.setKeyspaceCreations(getKeyspaceCreations());
cluster.setReconnectionPolicy(new ConstantReconnectionPolicy(1000));
return cluster;
}
#Override
protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
CreateKeyspaceSpecification specification = CreateKeyspaceSpecification.createKeyspace(keyspace)
.ifNotExists()
.with(KeyspaceOption.DURABLE_WRITES, true);
return Arrays.asList(specification);
}
#Override
protected List<DropKeyspaceSpecification> getKeyspaceDrops() {
return Arrays.asList(DropKeyspaceSpecification.dropKeyspace(keyspace));
}
}

CONCURRENT_MAP_PUT failed at Address 192.168.11.208

I am trying to store data synchronously in cache and mongoDB. I am getting this exception
Exception in thread "main" com.hazelcast.core.HazelcastException: CONCURRENT_MAP_PUT failed at Address[192.168.11.208]:5702 because of an exception thrown at Address[192.168.11.208]:5701
at com.hazelcast.impl.BaseManager.rethrowException(BaseManager.java:188)
at com.hazelcast.impl.ConcurrentMapManager$MPut.txnalPut(ConcurrentMapManager.java:1902)
at com.hazelcast.impl.ConcurrentMapManager$MPut.txnalPut(ConcurrentMapManager.java:1818)
at com.hazelcast.impl.ConcurrentMapManager$MPut.put(ConcurrentMapManager.java:1682)
at com.hazelcast.impl.MProxyImpl$MProxyReal.put(MProxyImpl.java:632)
at com.hazelcast.impl.MProxyImpl$MProxyReal.put(MProxyImpl.java:606)
at com.hazelcast.impl.MProxyImpl.put(MProxyImpl.java:173)
at com.hazelcast.impl.MProxyImpl.put(MProxyImpl.java:124)
at mypackage.dao.EmployeeDAO.createNewEmployee(EmployeeDAO.java:52)
at mypackage.services.EmployeeManager.createNewEmployee(EmployeeManager.java:25)
at mypackage.controllers.EmployeeController.createNewEmployee(EmployeeController.java:24)
at mypackage.hazelcastspring.App.main(App.java:29)
Caused by: java.lang.NullPointerException
at mypackage.services.EmployeeMapstore.store(EmployeeMapstore.java:61)
at mypackage.services.EmployeeMapstore.store(EmployeeMapstore.java:1)
at com.hazelcast.impl.concurrentmap.MapStoreWrapper.store(MapStoreWrapper.java:114)
at com.hazelcast.impl.ConcurrentMapManager$PutOperationHandler$PutStorer.doMapStoreOperation(ConcurrentMapManager.java:3091)
at com.hazelcast.impl.ConcurrentMapManager$AbstractMapStoreOperation.run(ConcurrentMapManager.java:3795)
at com.hazelcast.impl.executor.ParallelExecutorService$ParallelExecutorImpl$ExecutionSegment.run(ParallelExecutorService.java:212)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at com.hazelcast.impl.ExecutorThreadFactory$1.run(ExecutorThreadFactory.java:38
I am having POJO class contains two String and i am using com.hazlecast.core.Mapstore library
Mainclass
public static void main(String[] args) {
CacheTesting testObj = new CacheTesting();
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
EmployeeController obj = (EmployeeController) context.getBean("employeeController");
obj.createNewEmployee();
testObj.cacheMembers();
testObj.clearCacheMembers();
testObj.cacheSize();
testObj.deleteCache(2);
testObj.getCacheMember(1);}
/////Dao class
public EmployeeDTO createNewEmployee() {
System.out.println("----Create new employee of DAO class called----");
getEmployeeDTO.setFirstName("Name");
getEmployeeDTO.setLastName("lastName");
System.out.println("DAO object: "+getEmployeeDTO);
getEmployeeMap().put(3,getEmployeeDTO);
return getEmployeeDTO;
}
////MapStore class
public class EmployeeMapstore implements MapStore<Integer, EmployeeDTO> {
#Autowired
EmployeeDTO getEmployeeDTO;
#Autowired
MongoOperations mongoOperations;
public synchronized void store(Integer key, EmployeeDTO geEmployeeDTO) {
System.out.println("----Store method of mapstore called----");
System.out.println("Before put method/Store method object: "+getEmployeeDTO);
mongoOperations.save(getEmployeeDTO);

CommunicationException- failed to unmarshel Remote business interface looking up ejb3 in weblogic

My ejb 3 classes and remote interface are as follows :
package com.myeclipse.ejb3;
import java.io.Serializable;
public interface IMyBean extends Serializable
{
public void doSomething();
}
Remote interface:
package com.myeclipse.ejb3;
import javax.ejb.Remote;
#Remote
public interface MyBeanRemote extends IMyBean {
}
Stateless ejb:
package com.myeclipse.ejb3;
import javax.ejb.Stateless;
#Stateless(mappedName="ejb/MyBean")
public class MyBean implements MyBeanRemote
{
public void doSomething()
{
System.out.println("Hello world");
}
}
Project is successully deployed as a jar file in weblogic. I developed
a standalone client to call ejb. But this is failing. Kindly help.
I've included all the weblogic server libraries to connect to jndi and
remote business interface for complilation.
Client Code :
package Ejb3_Client;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class MyBeanClient {
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
try {
Properties p = new Properties();
p.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
p.put("java.naming.provider.url", "t3://172.21.123.70:8001");
InitialContext ctx = new InitialContext(p);
MyBeanRemote bean = (MyBeanRemote) ctx.lookup("ejb/MyBean#com.myeclipse.ejb3.MyBeanRemote");
System.out.println("bean instance "+ bean);
bean.doSomething();
System.out.println("bean worked");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
But I am getting this exception:
javax.naming.CommunicationException [Root exception is
java.rmi.UnmarshalException: failed to unmarshal class
java.lang.Object; nested exception is:
java.lang.ClassNotFoundException: com.myeclipse.ejb3.MyBeanRemote]
at
weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:74)
at
weblogic.jndi.internal.WLContextImpl.translateException(WLContextImpl.java:439)
at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:395)
at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:380)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
Ejb3_Client.MyBeanClient.main(MyBeanClient.java:33) Caused by:
java.rmi.UnmarshalException: failed to unmarshal class
java.lang.Object; nested exception is:
java.lang.ClassNotFoundException: com.myeclipse.ejb3.MyBeanRemote at
weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:244) at
weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:348)
at
weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:259)
at weblogic.jndi.internal.ServerNamingNode_1030_WLStub.lookup(Unknown
Source) at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:392)
... 3 more Caused by: java.lang.ClassNotFoundException:
com.myeclipse.ejb3.MyBeanRemote at
java.net.URLClassLoader$1.run(URLClassLoader.java:200) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:188) at
java.lang.ClassLoader.loadClass(ClassLoader.java:307) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
java.lang.ClassLoader.loadClass(ClassLoader.java:252) at
weblogic.ejb.container.internal.RemoteBusinessIntfProxy.readObject(RemoteBusinessIntfProxy.java:200)
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
java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
at
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at
weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:197)
at
weblogic.rjvm.MsgAbbrevInputStream.readObject(MsgAbbrevInputStream.java:564)
at
weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:193)
at weblogic.rmi.internal.ObjectIO.readObject(ObjectIO.java:62) at
weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:240) ...
7 more
I searched a lot but din find the problem why it can't unmarshel remote interface.
the reason for above error mainly because in some java file which implements Serializable interface has been changed you can revert those files to previous version

hibernate.cfg.xml not found on the JBoss server on OpenShift

Friends'm trying to connect my application in openshift through hibernate orm.
But the deployment is failing. You can check the error message in the server log:
2013/01/03 14:02:59,296 ERROR [com.wavetech_st.util.HibernateUtil] (MSC service thread 1-4) Falha na criação do objeto SessionFactory: org.hibernate.HibernateException: hibernate.cfg.xml not found
2013/01/03 14:02:59,298 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/testehome]] (MSC service thread 1-4) Exception starting filter conexaoFilter: java.lang.ExceptionInInitializerError
at com.wavetech_st.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:26) [classes:]
at com.wavetech_st.util.HibernateUtil.(HibernateUtil.java:12) [classes:]
at com.wavetech_st.web.filter.ConexaoHibernateFilter.init(ConexaoHibernateFilter.java:31) [classes:]
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:447) [jbossweb-7.0.10.Final.jar:]
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3269) [jbossweb-7.0.10.Final.jar:]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3865) [jbossweb-7.0.10.Final.jar:]
at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90) [jboss-as-web-7.1.0.Final.jar:7.1.0.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.7.0_09-icedtea]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.7.0_09-icedtea]
at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_09-icedtea]
Caused by: org.hibernate.HibernateException: resources/hibernate.cfg.xml not found
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173) [hibernate-core-4.1.1.Final.jar:4.1.1.Final]
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1943) [hibernate-core-4.1.1.Final.jar:4.1.1.Final]
at org.hibernate.cfg.Configuration.configure(Configuration.java:1924) [hibernate-core-4.1.1.Final.jar:4.1.1.Final]
at com.wavetech_st.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) [classes:]
... 11 more
I am creating this application in Eclipse. I have tested it on the local server JBoss 7.1 and it works. However when I try remote gives the error. I set the file hibernate.cfg the datasource before you deploy to OpenShift:
<property name="connection.datasource">java:jboss/datasources/MysqlDS</property>
This is my directory structure:
This is my WebFilter:
package com.wavetech_st.web.filter;
import java.io.IOException;
import javax.servlet.*;
import org.hibernate.SessionFactory;
import com.wavetech_st.util.HibernateUtil;
public class ConexaoHibernateFilter implements Filter {
private SessionFactory sf;
#Override
public void init(FilterConfig config) throws ServletException {// executado quando o aplicativo web e colocado no ar
this.sf = HibernateUtil.getSessionFactory();
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
try {
this.sf.getCurrentSession().beginTransaction();
chain.doFilter(servletRequest, servletResponse);
this.sf.getCurrentSession().getTransaction().commit();
this.sf.getCurrentSession().close();
} catch (Throwable ex) {
try {
if(this.sf.getCurrentSession().getTransaction().isActive())
this.sf.getCurrentSession().getTransaction().rollback();
} catch (Throwable t) {
t.printStackTrace();
}
throw new ServletException(ex);
}
}
#Override
public void destroy() {}
}
This is my HibernateUtil:
<pre>
package com.wavetech_st.util;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
static final Logger logger = Logger.getLogger(HibernateUtil.class);
private static final SessionFactory sessionFactory = buildSessionFactory();
private static ServiceRegistry serviceRegistry;
private static SessionFactory buildSessionFactory() {
try {
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
return cfg.buildSessionFactory(serviceRegistry);
} catch (Throwable e) {
logger.error("Falha na criação do objeto SessionFactory: " + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Please, help :-/
I solved my problem by following the hint of these guys:
stackoverflow.com/questions/4934330/org-hibernate-hibernateexception-hibernate-cfg-xml-not-found
shaunabram.com/tag/hibernate/
My problem was to put the hibernate.cfg.xml file in the wrong location. How to use Maven I should not put in the root directory but in the src directory root resouces.
Thanks mate, I had the same problem in jBoss-Openshift and Mybatis but with your answer you help me, I attached a picture where I put Mybatis config file who is similar file as hibernate

Morphia-MongoDB - "Please override this method for user marked Id field entity"

I am following a tutorial mention on code.google, but my example fails giving the following trace :
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.google.code.morphia.mapping.MappedClass.callLifecycleMethods(MappedClass.java:323)
at com.google.code.morphia.mapping.Mapper.toDBObject(Mapper.java:371)
at com.google.code.morphia.DatastoreImpl.entityToDBObj(DatastoreImpl.java:674)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:722)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:802)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:796)
at models.com.vlist.activity.classes.TestMongoData.testUserData(TestMongoData.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.reflect.InvocationTargetException
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.google.code.morphia.mapping.MappedClass.callLifecycleMethods(MappedClass.java:304)
... 28 more
Caused by: java.lang.UnsupportedOperationException: Please override this method for user marked Id field entity: models.com.vlist.activity.classes.User
at play.modules.morphia.Model.setId_(Model.java:284)
at play.modules.morphia.Model.generateId_(Model.java:299)
... 33 more
My example is as following:
import javax.persistence.Entity;
import org.bson.types.ObjectId;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.annotations.Id;
import play.modules.morphia.Model;
#Entity
public class User extends Model {
#Id ObjectId id;
private String firstName;
private String lastName;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
and
import static org.junit.Assert.*;
import org.junit.Test;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
public class TestMongoData {
#Test
public void testUserData() {
User user = new User();
user.setFirstName("first");
user.setLastName("last");
Morphia morphia = new Morphia();
Datastore ds = morphia.createDatastore("testData");
ds.save(user);
}
}
What could be wrong?
Update:
When I use play test, i see the following:
08:01:55,783 ERROR ~
#66h1bm10d
Internal Server Error (500) for request GET /#tests
Compilation error (In {module:morphia}/app/morphia/Filter.java around line 8)
The file {module:morphia}/app/morphia/Filter.java could not be compiled. Error raised is : The type Filter is already defined
play.exceptions.CompilationException: The type Filter is already defined
at play.classloading.ApplicationCompiler$2.acceptResult(ApplicationCompiler.java:246)
at org.eclipse.jdt.internal.compiler.Compiler.handleInternalException(Compiler.java:672)
at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:516)
at play.classloading.ApplicationCompiler.compile(ApplicationCompiler.java:278)
at play.classloading.ApplicationClassloader.getAllClasses(ApplicationClassloader.java:406)
at play.Play.start(Play.java:453)
at play.Play.detectChanges(Play.java:574)
at play.Invoker$Invocation.init(Invoker.java:186)
at Invocation.HTTP Request(Play!)
The problem comes from your #Entity definition. You're using JPA annotation while you should use the Morphia ones.
On startup, the Morphia plugin will retrieve all classes marked with the morphia Entity annotation and enhance them with various injected model methods. You're receiving this exception because your model class hasn't been enhanced.
If you annotate #Id then play morphia won't enhance your model by providing right implementation for void setId_(Object id) method. Try defining one yourself like this.
#Entity
class User extends Model {
#Id String email;
protected void setId_(Object id) {
}
}
Try removing the #Id ObjectId id; from your model. The Morphia Module for Play Framework will add the id for you.
Then make the fields public and remove the getter/setter methods.
public String firstName;
public String lastName;
Also, your Entity import is incorrect. Try this
import com.google.code.morphia.annotations.Entity;
Try this for a test case:
import static org.junit.Assert.*;
import org.junit.Test;
import play.test.UnitTest;
public class TestMongoData extends UnitTest {
#Test
public void testUserData() {
User user = new User();
user.setFirstName("first");
user.setLastName("last");
user.save();
}
}
It's seems that you have defined the morphia module in the dependency file and in the application conf file.
In the dependencies file : - play -> morphia [1.2.1beta6,)
In the application conf file : module.morphia=${play.path}/modules/morphia
You must removed one of this declaration otherwise the morphia module is loaded twice ...