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

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

Related

Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration Exception

I am learning Hibernate and tried a simple program. I used Hibernate 5.3 version and added all the Hibernate required .jar files to the build path. I can find the Configuration class in the ref libraries folder, still getting the exception. Is there anything wrong with the hibernate.cfg.xml? Is there any specific location it has to be saved? Please help me. Thanks in advance.
I am attaching my project layout and source code.
my HibernateUtil.java code
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory =
buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
System.out.println("hii");
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed."
+ ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
[Project layout]project layoutHibernate confg xml file

Spring batch with DB2 and MongoDB using Spring boot

I need to read the DB2 database and copy data to mongoDB using Spring Batch. As I am going to write the data to mongoDB, so I dont need the transaction. I would like to keep the metadata tables scripts in mongoDB only not in DB2 but I couldn't find the metadata tables scripts for mongoDB. In the server startup time, spring boot expect the batch_job_instance table in Db2 instead of mongoDB. I annotated mongoDB as primary but still it is throwing an error.
Someone can help me with this. Thanks in advance.
MongoConfig.java:
#Configuration
#EnableMongoRepositories("com.test.mongodb")
public class MongoConfig extends AbstractMongoConfiguration {
private final Logger log = LoggerFactory.getLogger(MongoConfig.class);
#Value("${spring.data.mongodb.host}")
private String host;
#Value("${spring.data.mongodb.port}")
private Integer port;
#Value("${spring.data.mongodb.username}")
private String username;
#Value("${spring.data.mongodb.database}")
private String database;
#Value("${spring.data.mongodb.password}")
private String password;
#Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
#Override
public String getDatabaseName() {
return database;
}
#Override
#Bean
public Mongo mongo() throws Exception {
return new MongoClient(singletonList(new ServerAddress(host, port)),
singletonList(MongoCredential.createCredential(username, database, password.toCharArray())));
}
#Override
#Bean
#Primary
#ConfigurationProperties(prefix = "spring.data.mongodb")
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongo(), database);
}
}
application.properties:
# DB2
spring.datasource.jndi-name=java:jboss/datasources/Db2XaDsn
# Mongo DB
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.username=admin
spring.data.mongodb.password=admin
spring.data.mongodb.database=test
Batch class:
#Configuration
#EnableBatchProcessing
public class ItemBatch {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Autowired
EntityManagerFactory entityManagerFactory;
#Autowired
MongoTemplate mongoTemplate;
#Bean
public Job readDB2() {
return jobBuilderFactory.get("readDB2").start(step1()).build();
}
#Bean
public Step step1() {
return stepBuilderFactory.get("step1").<com.model.db2.Item, Item>chunk(200).reader(reader())
.writer(writer()).build();
}
#Bean
public ItemReader<com.model.db2.Item> reader() {
JpaPagingItemReader<com.model.db2.Item> reader = new JpaPagingItemReader<>();
reader.setQueryString("select i from Item i");
reader.setEntityManagerFactory(entityManagerFactory);
return reader;
}
#Bean
public MongoItemWriter<Item> writer() {
MongoItemWriter<Item> writer = new MongoItemWriter<>();
try {
writer.setTemplate(mongoTemplate);
} catch (Exception e) {
e.printStackTrace();
}
writer.setCollection("item");
return writer;
}
}
Error:
00:44:39,484 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 72) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./itemapi: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./itemapi: java.lang.RuntimeException: java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:85)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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 org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.RuntimeException: java.lang.IllegalStateException: Failed to execute CommandLineRunner
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:231)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
... 6 more
Caused by: java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:735)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716)
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:304)
at org.springframework.boot.web.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:154)
at org.springframework.boot.web.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:134)
at org.springframework.boot.web.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:87)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:169)
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:184)
... 8 more
Caused by: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT JOB_INSTANCE_ID, JOB_NAME from BATCH_JOB_INSTANCE where JOB_NAME = ? order by JOB_INSTANCE_ID desc]; nested exception is com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=TEST.BATCH_JOB_INSTANCE, DRIVER=4.18.60
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:684)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:716)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:726)
at org.springframework.batch.core.repository.dao.JdbcJobInstanceDao.getJobInstances(JdbcJobInstanceDao.java:230)
at org.springframework.batch.core.explore.support.SimpleJobExplorer.getJobInstances(SimpleJobExplorer.java:173)
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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy302.getJobInstances(Unknown Source)
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.getNextJobParameters(JobLauncherCommandLineRunner.java:131)
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:212)
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:231)
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:123)
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:117)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732)
... 16 more
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=TEST.BATCH_JOB_INSTANCE, DRIVER=4.18.60
at com.ibm.db2.jcc.am.kd.a(kd.java:747)
at com.ibm.db2.jcc.am.kd.a(kd.java:66)
at com.ibm.db2.jcc.am.kd.a(kd.java:135)
at com.ibm.db2.jcc.am.bp.c(bp.java:2788)
at com.ibm.db2.jcc.am.bp.d(bp.java:2776)
at com.ibm.db2.jcc.am.bp.a(bp.java:2209)
at com.ibm.db2.jcc.am.cp.a(cp.java:7886)
at com.ibm.db2.jcc.t4.bb.h(bb.java:141)
at com.ibm.db2.jcc.t4.bb.b(bb.java:41)
at com.ibm.db2.jcc.t4.p.a(p.java:32)
at com.ibm.db2.jcc.t4.vb.i(vb.java:145)
at com.ibm.db2.jcc.am.bp.kb(bp.java:2178)
at com.ibm.db2.jcc.am.cp.xc(cp.java:3686)
at com.ibm.db2.jcc.am.cp.b(cp.java:4493)
at com.ibm.db2.jcc.am.cp.kc(cp.java:767)
at com.ibm.db2.jcc.am.cp.executeQuery(cp.java:732)
at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeQuery(WrappedPreparedStatement.java:504)
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:692)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
... 38 more
Answering my own question. I am able use spring batch without metadata tables using the below configuration:
#Configuration
public class SpringBatchInMemoryConfiguration {
#Bean
public ResourcelessTransactionManager transactionManager() {
return new ResourcelessTransactionManager();
}
#Bean
public MapJobRepositoryFactoryBean mapJobRepositoryFactory(ResourcelessTransactionManager txManager)
throws Exception {
MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(txManager);
factory.afterPropertiesSet();
return factory;
}
#Bean
public JobRepository jobRepository(MapJobRepositoryFactoryBean factory) throws Exception {
return factory.getObject();
}
#Bean
public JobExplorer jobExplorer(MapJobRepositoryFactoryBean factory) {
return new SimpleJobExplorer(factory.getJobInstanceDao(), factory.getJobExecutionDao(),
factory.getStepExecutionDao(), factory.getExecutionContextDao());
}
#Bean
public SimpleJobLauncher jobLauncher(JobRepository jobRepository) throws Exception {
SimpleJobLauncher launcher = new SimpleJobLauncher();
launcher.setJobRepository(jobRepository);
launcher.afterPropertiesSet();
return launcher;
}
}

Weld cannot find CDI producer

WildFly 10.1 used. In modules added single module that contains jar file with interface EzRegistryService.
Producer code:
package com.ejbtest;
import org.apache.log4j.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Produces;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class Resources {
private static final Logger log = Logger.getLogger(Resources.class);
public static final String jndiName = "java:global/ejbtest.main/EzRegistryServiceBean!com.ejbtest.EzRegistryService";
//also didn't work
//#Produces
//#EJB(lookup = jndiName)
//private EzRegistryService ezRegistryService;
// didn't work
#Produces
public EzRegistryService getEzRegistryService() {
log.info("getEzRegistryService called");
try {
InitialContext ctx = new InitialContext();
Object service = ctx.lookup(jndiName);
log.info("Found: " + service);
return (EzRegistryService) service;
} catch (NamingException e) {
log.error("Exception while getting EzRegistryService", e);
return null;
}
}
}
Singleton bean:
package com.ejbtest;
import org.apache.log4j.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
#Singleton
#Startup
public class MyGateStartup {
private static final Logger log = Logger.getLogger(MyGateStartup.class);
//#EJB(mappedName = Resources.jndiName) //works fine
#Inject
private EzRegistryService service;
#PostConstruct
public void start() {
log.info("MyGateStartup started");
//...
}
#PreDestroy
public void end() {
//...
log.info("MyGateStartup stopped");
}
}
beans.xml in WEB-INF folder:
<beans 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/beans_1_1.xsd"
version="1.1"
bean-discovery-mode="all">
</beans>
WildFly can't deploy resulting war-file:
2017-03-14 13:15:05,237 MSC service thread 1-8 INFO [org.jboss.weld.deployer] WFLYWELD0006: Starting Services for CDI deployment: ejbtest.gate-1.0-SNAPSHOT.war
2017-03-14 13:15:05,241 MSC service thread 1-8 INFO [org.jboss.weld.deployer] WFLYWELD0009: Starting weld service for deployment ejbtest.gate-1.0-SNAPSHOT.war
2017-03-14 13:15:05,299 MSC service thread 1-6 ERROR [org.jboss.msc.service.fail] MSC000001: Failed to start service jboss.deployment.unit."ejbtest.gate-1.0-SNAPSHOT.war".WeldStartService: org.jboss.msc.service.StartException in service jboss.deployment.unit."ejbtest.gate-1.0-SNAPSHOT.war".WeldStartService: Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.6.Final.jar:1.2.6.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_121]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_121]
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type EzRegistryService with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private com.ejbtest.MyGateStartup.service
at com.ejbtest.MyGateStartup.service(MyGateStartup.java:0)
Why CDI can't find producer in Resources class?
In CDI specification, it is written in section 2.5:
Producer methods (as defined in Producer methods) whose bean class does not have a bean defining annotation are not discovered....
The class where you have your #Produces annotated method must be a CDI bean. Try giving it a scope :)
Looks like CDI is not managing your Resources class.
Once it's just a factory bean, you can annotated it with #ApplicationScoped:
#ApplicationScoped
public class Resources {
...
}

Can't get Feign Client to work for a basic example

Can't get Feign Client to work. First tried with POST. Kept running into errors related to Encoder/Decoder saying type is not right.
Then found an example on github to call simple GET API finally and decided to give it a shot.
Still fails
On Github and online, I am seeing multiple versions of Feign Client
Spring-Cloud, OpenFeign, Netflix.feign having different versions.
Could anyone describe what's the best and stable Feign client one should use for production?
package com.paa.controllers;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#FeignClient (name="test-service",url="https://www.reddit.com/r")
public interface GetFeignClient {
#RequestMapping(method = RequestMethod.GET, value = "/java.json")
public String posts();
}
Controller:
#RestController
#RequestMapping("/some/api")
public class TestWLCController {
#Autowired
private GetFeignClient getFeignClient;
.. some stuff
#RequestMapping(value="/postSomething",method = RequestMethod.POST)
#ApiOperation(value = "Configures something",
notes = "basic rest controller for testing feign")
public ResponseEntity<SomeResponse> feignPost(
UriComponentsBuilder builder,
#ApiParam(name = "myRequest",
value = "request for configuring something",
required = true)
#Valid #RequestBody SomeRequest someRequest) {
String resp = null;
try {
resp = getFeignClient.posts();
} catch (Exception er) {
er.printStackTrace();
}
}
}
Application:
Tried all possible permutations of annotations thinking it would resolve AutoWire stuff but still fails
#Configuration
#ComponentScan
#EnableAutoConfiguration
//#EnableEurekaClient
#EnableFeignClients
//#SpringBootApplication
//#EnableFeignClients
//#EnableFeignClients(basePackages = {"com.paa.xenia.controllers", "com.paa.xenia.services"})
public class ServiceApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(XeniaServiceApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
2016-07-20 18:15:42.406[0;39m [31mERROR[0;39m [35m32749[0;39m
[2m---[0;39m [2m[ main][0;39m
[36mo.s.boot.SpringApplication [0;39m [2m:[0;39m
Application startup failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'testWLCController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.paa.controllers.GetFeignClient
com.paa.controllers.TestWLCController.gfClient; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'com.aa..controllers.GetFeignClient':
FactoryBean threw exception on object creation; nested exception is
java.lang.NullPointerException at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
~[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1191)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1180)
[spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at
com.paa.ServiceApplication.main(ServiceApplication.java:44) [bin/:na]
Caused by: org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.paa.controllers.GetFeignClient
com.paa.controllers.TestWLCController.gfClient; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'com.paa.controllers.GetFeignClient':
FactoryBean threw exception on object creation; nested exception is
java.lang.NullPointerException at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] ... 17 com.n frames
omitted
I'm not sure if you eventually figured it out yourself, but for the sake of others who might stumble across this thread, below is a working example of what you were trying to do. I'll first point out a few things that are incorrect, or at least, not desired in your code, then show my code that works.
You should try not to use the url attribute. Instead, set up a list of servers using <feign client name>.ribbon.listOfServers in bootstrap.yml (or bootstrap.properties). This allows for client side load balancing because listOfServers can be a comma-separated list.
Using Ribbon for HTTPS connections, you need to specify two things that you don't need for HTTP connections. The port, which is part of the listOfServers and <feign client name>.ribbon.IsSecure: true. Without the port, the connection is made to port 80 and without the IsSecure, HTTP is used.
Testing using curl, I found that Reddit takes a very long time to respond. See this SO post for details of how to break down the total time taken by the request-response cycle.
$ curl -v -H "User-Agent: Mozilla/5.0" -w "#curl-format.txt" -o /dev/null -s "https://www.reddit.com/r/java/top.json?count=1"
{ [2759 bytes data]
* Connection #0 to host www.reddit.com left intact
time_namelookup: 0.527
time_connect: 0.577
time_appconnect: 0.758
time_pretransfer: 0.758
time_redirect: 0.000
time_starttransfer: 11.189
----------
time_total: 11.218
According the Netflix Wiki, the default read and connect timeouts are 3000 milliseconds, so you will always timeout unless you change those.
You may have noticed that I specified a User-Agent header in the curl request. That's because Reddis seems to be very picky about that and if not specified, returns a HTTP 429 "Too many requests" most of the times. They don't return a Retry-After header in the response so there's no telling how long you need to wait before making another request.
Spring Cloud Netflix as well as Netflix Feign is open source, so some (a lot of) patience and debugging skills come really handy.
"Talk is cheap. Show me the code." (Torvalds, Linus (2000-08-25)).
I generated a Gradle app using the excellent Spring Initializr site. Here's a snippet from the build.gradle file.
dependencies {
compile('org.springframework.cloud:spring-cloud-starter-feign')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Camden.SR3"
}
}
Feign client:
#FeignClient(name = "reddit")
public interface RedditClient {
#RequestMapping(method = GET, value = "/r/java/top.json?count=1",
headers = {USER_AGENT + "=Mozilla/5.0", ACCEPT + "=" + APPLICATION_JSON_VALUE})
public String posts();
}
Boot Application:
#SpringBootApplication
#EnableFeignClients
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#RestController
static class DemoController {
#Autowired
private RedditClient redditClient;
#GetMapping("/posts")
public String posts() {
return redditClient.posts();
}
}
}
bootstrap.yml:
reddit:
ribbon:
listOfServers: www.reddit.com:443
ConnectTimeout: 20000
ReadTimeout: 20000
IsSecure: true
hystrix.command.default.execution:
timeout.enabled: true
isolation.thread.timeoutInMilliseconds: 50000
Integration test:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoApplicationTest {
#Autowired
private TestRestTemplate restTemplate;
#Test
public void testGetPosts() {
ResponseEntity<String> responseEntity = restTemplate.getForEntity("/posts", String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
assertThat(String.format("Actual status code: %d, reason: %s.",
statusCode.value(), statusCode.getReasonPhrase()),
statusCode.is2xxSuccessful(), equalTo(true));
}
}
Dependencies:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Greenwich.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
App:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.test.cloud.bookservice.models.Book;
#SpringBootApplication
#RestController
#RequestMapping("/books")
#EnableFeignClients
public class BookServiceApplication {
Logger logger = LogManager.getLogger(BookServiceApplication.class);
#Autowired
private StoreClient storeClient;
public static void main(String[] args) {
SpringApplication.run(BookServiceApplication.class, args);
}
#GetMapping("/book")
public Book findBook() {
return this.restTemplate.getForObject("http://stores/book", Book.class);
}
#FeignClient(name = "StoreClient", url = "127.0.0.1:8089")
interface StoreClient {
#RequestMapping(method = RequestMethod.GET, value = "/stores/book", consumes = "application/json")
Book getBook();
}
}
Someone was interested to find out how did we do it so posting answer for their benefit.
Parent Module
package com.hitech.module.base;
#EnableFeignClients
public abstract class BaseApplication extends SpringBootServletInitializer {
...
..
}
build.gradle:
buildscript {
ext {
springBootVersion = '1.3.5.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("io.spring.gradle:dependency-management-plugin:0.5.6.RELEASE")
}
}
...
...
dependencies {
compile('io.springfox:springfox-swagger-ui:2.5.0')
compile('io.springfox:springfox-swagger2:2.5.0')
compile('org.springframework.cloud:spring-cloud-starter-feign')
Child Module
package com.hitech.module.app;
import com.hitech.module.base.BaseApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
#SpringBootApplication(exclude = {MongoDataAutoConfiguration.class, MongoAutoConfiguration.class},
scanBasePackages = {"com.hitech.module.base", "com.hitech.module.app", })
#EnableFeignClients("com.hitech.module.app.clients")
public class MyServiceApplication extends BaseApplication {
private static final Logger LOG = LoggerFactory.getLogger(MyServiceApplication.class);
public static void main(String[] args) {
String s1 = "google";
LOG.info ("=== Started Orchestration Service ===");
SpringApplication.run(MyServiceApplication.class, args);
}
}
bootstrap.yml
feign:
hystrix:
enabled: false
datasource:
audit:
mongodb:
host: localhost
port: 27019
database: audit

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