Weld cannot find CDI producer - wildfly

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 {
...
}

Related

How to create custom retry logic for Spring Datasource?

I'm connecting to an Azure SQL database and my next task is to create custom retry logic when a connection has failed. I would like the retry logic to run both on startup (if needed) as well as any time there's a connection failure while the app is running. I did a test where I removed the IP restrictions from my app and that then caused an exception in my application (as excepted). I'd like to handle when that exception is thrown so that I can trigger a job that verifies both the app and the server are configured correctly. I'm looking for a solution where I can handle these exceptions and retry the DB transaction?
DataSource Config
#Bean
#Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.username("username")
.password("password")
.url("jdbc:sqlserver://contoso.database.windows.net:1433;database=*********;user=******#*******;password=*****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;")
.driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
.build();
}
application.properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
spring.jpa.show-sql=true
logging.level.org.springframework.web: ERROR
logging.level.org.hibernate: ERROR
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=1
spring.datasource.tomcat.test-on-borrow=true
spring.jpa.hibernate.ddl-auto=update
The following code may help you create your retry logic for a data source on Spring Boot:
package com.example.demo;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.AbstractDataSource;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Retryable;
#SpringBootApplication
#EnableRetry
public class DemoApplication {
#Order(Ordered.HIGHEST_PRECEDENCE)
private class RetryableDataSourceBeanPostProcessor implements BeanPostProcessor {
#Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof DataSource) {
bean = new RetryableDataSource((DataSource)bean);
}
return bean;
}
#Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public BeanPostProcessor dataSouceWrapper() {
return new RetryableDataSourceBeanPostProcessor();
}
}
class RetryableDataSource extends AbstractDataSource {
private DataSource delegate;
public RetryableDataSource(DataSource delegate) {
this.delegate = delegate;
}
#Override
#Retryable(maxAttempts=10, backoff=#Backoff(multiplier=2.3, maxDelay=30000))
public Connection getConnection() throws SQLException {
return delegate.getConnection();
}
#Override
#Retryable(maxAttempts=10, backoff=#Backoff(multiplier=2.3, maxDelay=30000))
public Connection getConnection(String username, String password)
throws SQLException {
return delegate.getConnection(username, password);
}
}
Not sure what you deem custom but, there is an out-of-the-box option with Spring boot and Aspectj by leveraging the pom.xml in the mavern project, as spring-retry depends on Aspectj:
Add the following dependencies in your project pom.xml:
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>${version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${version}</version>
</dependency>
And then add the #EnableRetry annotation to your code:
package com.example.springretry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.retry.annotation.EnableRetry;
#EnableRetry
#SpringBootApplication
public class SpringRetryApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRetryApplication.class, args);
}
}
The Spring retry module example can be found here: https://howtodoinjava.com/spring-boot2/spring-retry-module/

error inject EJB in JSF project

hi everyone im new in java EE and i want to developpe an application with EJB and JSF and when i want to inject my JAR in web dynamique project i have this error and i dont understood anything please anyone can help me
17:54:06,324 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC000001: Failed to start service jboss.deployment.unit."PGestion.war".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.unit."PGestion.war".INSTALL: WFLYSRV0153: Failed to process phase INSTALL of deployment "PGestion.war"
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:172)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:2032)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1955)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEJB0406: No EJB found with interface of type 'com.bestofgeeks.gestion.dao.Implement.GestionDAOBean' for binding com.bestofgeeks.gestion.services.ImplService.ImplServiceProduct/product
at org.jboss.as.ejb3.deployment.processors.EjbInjectionSource.getResourceValue(EjbInjectionSource.java:90)
at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.addJndiBinding(ModuleJndiBindingProcessor.java:211)
at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor$1.handle(ModuleJndiBindingProcessor.java:182)
at org.jboss.as.ee.component.ClassDescriptionTraversal.run(ClassDescriptionTraversal.java:54)
at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.processClassConfigurations(ModuleJndiBindingProcessor.java:186)
at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.deploy(ModuleJndiBindingProcessor.java:143)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:165)
... 5 more
17:54:06,341 INFO [org.infinispan.factories.GlobalComponentRegistry] (MSC service thread 1-2) ISPN000128: Infinispan version: Infinispan 'Chakra' 8.2.8.Final
17:54:06,696 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 62) WFLYCLINF0002: Started client-mappings cache from ejb container
17:54:06,777 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "PGestion.war")]) - failure description: {
"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"PGestion.war\".INSTALL" => "WFLYSRV0153: Failed to process phase INSTALL of deployment \"PGestion.war\"
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEJB0406: No EJB found with interface of type 'com.bestofgeeks.gestion.dao.Implement.GestionDAOBean' for binding com.bestofgeeks.gestion.services.ImplService.ImplServiceProduct/product"},
"WFLYCTL0412: Required services that are not installed:" => ["jboss.deployment.unit.\"PGestion.war\".beanmanager"],
"WFLYCTL0180: Services with missing/unavailable dependencies" => [
"jboss.deployment.unit.\"PGestion.war\".weld.weldClassIntrospector is missing [jboss.deployment.unit.\"PGestion.war\".beanmanager]",
"jboss.deployment.unit.\"PGestion.war\".batch.artifact.factory is missing [jboss.deployment.unit.\"PGestion.war\".beanmanager]"
]
}
This is the interface DAO:
package com.bestofgeeks.gestion.dao;
import java.util.List;
import javax.ejb.Local;
import com.bestofgeeks.gestion.entity.products;
#Local
public interface IGestion {
public void delete(products p);
public products persiste(products p);
public List<products> selectAll();
}
interface DAO
package com.bestofgeeks.gestion.dao;
import java.util.List;
import javax.ejb.Local;
import com.bestofgeeks.gestion.entity.products;
#Local
public interface IGestion {
public void delete(products p);
public products persiste(products p);
public List<products> selectAll();
}
implement DAO
package com.bestofgeeks.gestion.dao.Implement;
import java.util.List;
import javax.ejb.Stateless;
import javax.management.Query;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.bestofgeeks.gestion.dao.IGestion;
import com.bestofgeeks.gestion.entity.products;
#Stateless
public class GestionDAOBean implements IGestion{
#PersistenceContext(unitName = "Gestion_PU")
EntityManager entityManager;
#Override
public void delete(products p) {
// TODO Auto-generated method stub
entityManager.remove(p);
}
#Override
public products persiste(products p){
// TODO Auto-generated method stub
entityManager.persist(p);
return p;
}
#Override
public List<products> selectAll() {
// TODO Auto-generated method stub
Query query = (Query) entityManager.createQuery("SELECT o from products o");
return ((javax.persistence.Query) query).getResultList();
}
}
and this is package service of my project
this service have interface Iservice and a package of implement class name ImplServiceProduct
for Iservice this is the code
package com.bestofgeeks.gestion.services;
import java.util.List;
import javax.ejb.Local;
import com.bestofgeeks.gestion.entity.products;
#Local
public interface Iservices {
public List<products> selectAll();
public void delete(products p);
public products persiste(products p);
}
for implement service
package com.bestofgeeks.gestion.services.ImplService;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import com.bestofgeeks.gestion.dao.Implement.GestionDAOBean;
import com.bestofgeeks.gestion.entity.products;
import com.bestofgeeks.gestion.services.Iservices;
#Stateless
public class ImplServiceProduct implements Iservices{
#EJB
GestionDAOBean product;
#Override
public List<products> selectAll() {
return product.selectAll();
}
#Override
public void delete(products p) {
// TODO Auto-generated method stub
product.delete(p);
}
#Override
public products persiste(products p) {
// TODO Auto-generated method stub
return product.persiste(p);
}
}
for the entity
package com.bestofgeeks.gestion.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table
public class products {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Column
private String nameproduct;
#Column
private String reference;
#Column
private Date dateposte;
public products(String nameproduct, String reference, Date dateposte) {
super();
this.nameproduct = nameproduct;
this.reference = reference;
this.dateposte = dateposte;
}
public products() {
super();
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNameproduct() {
return nameproduct;
}
public void setNameproduct(String nameproduct) {
this.nameproduct = nameproduct;
}
public String getRefence() {
return reference;
}
public void setRefences(String reference) {
this.reference = reference;
}
public Date getDateposte() {
return dateposte;
}
public void setDateposte(Date dateposte) {
this.dateposte = dateposte;
}
}
and for my jsf project
i create a controller
this is the code
package com.bestofgeeks.gestion.controllers;
import javax.annotation.ManagedBean;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import com.bestofgeeks.gestion.services.Iservices;
#RequestScoped #ManagedBean
public class myProduct {
#EJB
public String name = "noredine";
Iservices service;
}
You must inject the local interface not the bean:
#EJB
IGestion product;
As #kukeltje says in the comment:
Read the error: (emphasis mine) "No EJB found with interface of type
'com.bestofgeeks.gestion.dao.Implement.GestionDAOBean" and what it
references is a impl, not
an interface!

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

WELD-001408 Unsatisfied dependencies

I have a very famous error, but I can't solve it.
I'm trying to run arqullian test for my application.
I've done everything according to the official documentation.
The long search for solution to the problem given nothing.
16:49:42,713 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.deployment.unit."test.war".WeldService: org.jboss.msc.service.StartException in service jboss.deployment.unit."test.war".WeldService: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Sender] with qualifiers [#Default] at injection point [[field] #Inject com.test.test2.ejb.AppManagerBean.sender]
at org.jboss.as.weld.services.WeldService.start(WeldService.java:83)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_13]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_13]
at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_13]
Caused by: org.jboss.weld.exceptions.DeploymentException:
WELD-001408 Unsatisfied dependencies for type [Sender] with qualifiers [#Default]
at injection point [[field] #Inject com.test.test2.ejb.AppManagerBean.sender]
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:275)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:244)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:107)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:127)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:346)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:331)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:366)
at org.jboss.as.weld.WeldContainer.start(WeldContainer.java:83)
at org.jboss.as.weld.services.WeldService.start(WeldService.java:76)
... 5 more
My test class:
package com.highstreetlabs.wlcome.rest;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import com.test.test2.ejb.AppManager;
import com.test.test2.ejb.Storage;
import com.test.test2model.Customer;
import com.test.test2.rest.model.ProximityModel;
import com.test.test2.util.EntityManagerProducer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.json.simple.parser.ParseException;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.ejb.EJB;
import javax.inject.Inject;
#RunWith(Arquillian.class)
public class CustomerCollectionResourceTest {
#Deployment
public static WebArchive createTestArchive() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(CustomerCollectionResource.class, EntityManagerProducer.class,
AppManager.class, Storage.class,
ParseException.class, Sender.class)
.addPackage(Customer.class.getPackage())
.addPackage(Result.class.getPackage())
.addPackage(NotFoundException.class.getPackage())
.addPackage(CustomerPhotoResource.class.getPackage())
.addPackage(ProximityModel.class.getPackage())
.addAsResource("import.sql")
.addAsManifestResource(EmptyAsset.INSTANCE, "META-INF/beans.xml")
.addAsManifestResource("test-ds.xml", "test-ds.xml");
}
#Inject
CustomerCollectionResource resource;
#EJB
AppManager manager;
#Test
public void testList() throws Exception {
resource = new CustomerCollectionResource();
resource.list(null);
}
}
AppManagerBean.java
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import com.google.common.base.Strings;
import com.test.test2.json.JacksonObjectMapperProvider;
import com.test.test2.model.*;
import com.test.test2.rest.HttpStatusException;
import com.test.test2.rest.NotFoundException;
import com.test.test2.rest.model.ProximityModel;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.Asynchronous;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.*;
import javax.persistence.criteria.*;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.List;
/**
* Stateless EJB bean containing entire business logic implementation
*/
#Local(AppManager.class)
#Stateless
public class AppManagerBean implements AppManager {
public static final String
GCM_ENTER_ACTION = "enter",
GCM_EXIT_ACTION = "exit",
PARAM_DATA_JSON = "proximityModel",
PARAM_CUSTOMER_ID = "customerId",
PARAM_ACTION = "action";
#Inject
EntityManager em;
#Inject
Sender sender;
....
}
And finally class for test CustomerCollectionResource
#Path("customer/")
#RequestScoped
public class CustomerCollectionResource {
final static int CACHEABLE_SECONDS = 0;
#EJB
private AppManager manager;
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response list(#QueryParam("email") String email) {
final List<Customer> entities = manager.listCustomers(email);
if(entities.size() == 0)
throw new NotFoundException("There is no any customer");
ListModel<ListItem> result = new ListModel<ListItem>(entities.size());
result.itemType = ListItem.MEDIA_TYPE;
final UriBuilder itemLink = UriBuilder.fromResource(CustomerResource.class);
for (Customer entity : entities) {
result.add(new ListItem(entity.getName(), itemLink.build(entity.getId())));
}
CacheControl cc = new CacheControl();
cc.setMaxAge(CACHEABLE_SECONDS);
cc.setPrivate(true);
return Response.ok(result).cacheControl(cc).build();
}
}
Sender Producer
public class GcmSenderProducer {
#Resource String senderId;
#Produces public Sender getSender() {
return new Sender(senderId);
}
}
Yes, I also think the GcmSenderProducer is missing so the Sender class cannot be injected propperly since it looks like it has no no-arg constructor and I guess the constructor.

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