error inject EJB in JSF project - eclipse

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!

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/

Why #Autowired not working all the time?

Im trying to setup mongodb with SpringBoot and im not using context.xml but trying to configure with configuration class and annotations.
package com.configuration;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#Configuration
#EnableMongoRepositories(basePackages = "com.mongo")
public class MongoConfig extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "mongodbname";
}
#Override
public Mongo mongo() throws Exception {
return new MongoClient("127.0.0.1", 27017);
}
#Override
protected String getMappingBasePackage() {
return "com.mongo";
}
}
My repository looks like this :
package com.mongo.repositories;
import com.mongo.documents.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository("sequenceRepository")
public class SequenceRepository{
#Autowired
private MongoTemplate mongoTemplate;
public Sequence findOne(Query query){
return this.mongoTemplate.findOne(query,Sequence.class);
}
public List<Sequence> find(Query query){
return this.mongoTemplate.find(query,Sequence.class);
}
public void save(Sequence object){
this.mongoTemplate.save(object);
}
public void delete(Sequence object){
this.mongoTemplate.remove(object);
}
}
If i use like this in the rest controller it is working properly :
package com.controllers;
import com.mongo.documents.Sequence;
import com.mongo.repositories.SequenceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class IndexController {
#Autowired
private SequenceRepository sequenceRepository;
#RequestMapping("/")
public String index(){
Sequence sequence = new Sequence();
sequence.setClassName("class.Test");
sequence.setActual(1);
sequenceRepository.save(sequence);
return "index";
}
}
But if i want to use the SequenceRepository inside the Sequence document like this :
package com.mongo.documents;
import com.mongo.repositories.SequenceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class Sequence {
#Autowired
private SequenceRepository sequenceRepository;
#Id
private String id;
private String className;
private int actual;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public int getActual() {
return actual;
}
public void setActual(int actual) {
this.actual = actual;
}
public void save(){
this.sequenceRepository.save(this);
}
public void delete(){
this.sequenceRepository.delete(this);
}
}
After that I change the code in the controller to :
package com.controllers;
import com.mongo.documents.Sequence;
import com.mongo.repositories.SequenceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class IndexController {
#Autowired
private SequenceRepository sequenceRepository;
#RequestMapping("/")
public String index(){
Sequence sequence = new Sequence();
sequence.setClassName("class.Test");
sequence.setActual(1);
sequence.save();
return "index";
}
}
I got a nullPointerExceeption at this point in the save() method.
There is no need to inject your Repository inside your Domain object Sequence as it is really bad design to have a dependency between the domain objects and your repository classes.
To follow some good practices, your Service classes or if you don't need a Service layer, your Controller classes should inject your Repository beans.
In your last code snippet your are already doing it, but the .save() method should be called on your repository SequenceRepository and not on the domain object Sequence.
An example could be the following:
#RestController
public class IndexController {
#Autowired
private SequenceRepository sequenceRepository;
#RequestMapping("/")
public String index(){
Sequence sequence = new Sequence();
sequence.setClassName("class.Test");
sequence.setActual(1);
// now let's save it
sequenceRepository.save(sequence);
return "index";
}
}
You can only autowire Spring-managed components into other Spring-managed components. Your sequence object is not a component (not annotated with #Component, #Service, #Repository or #Controller etc.)
I suggest you follow rieckpil's advice.

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.

External #EJB injection return null with RESTeasy and JBoss

I'm developing a RESTful Web Service on JBoss 6 Final with RESTeasy.
I have an external EJB and I want inject EJB on Web Service.
This is the code of EJB
BeanLocalInterface.java
#Local
public interface BeanLocalInterface {
public String sayHello();
}
Bean.java
#Stateless
#LocalBinding(jndiBinding = "BeanLocal")
public class Bean implements BeanLocalInterface {
#Override
public String sayHello() {
return "Hello!";
}
}
In another project I have a WS:
#Path("/ws")
public class HelloWorldResource {
#EJB(mappedName="BeanLocal")
private BeanLocalInterface bean;
#GET
#Path("/hello")
#Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
return bean.sayHello();
}
}
MyRESTApplication.java
public class MyRESTApplication extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public MyRESTApplication(){
singletons.add(new HelloWorldResource());
}
#Override
public Set<Class<?>> getClasses() {
return empty;
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
bean is alwasy null!
I have tried this solution:
I have put #Stateless on HelloWorldResources
I have create beans.xml in WEB-INF
I have change MyRESTApplication with
#ApplicationPath("wsapp")
public class MyRESTApplication extends Application {
}
Can you help me?
PS: I don't have EAR e I don't want use it
I have managed to solve this. Firstly, remove all settings from web.xml regarding RESTeasy. You only need one adnotation --> #ApplicationPath
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("api")
public class MyRESTApplication extends Application {
//nothing required here, leave this empty
}
This is your session bean interface.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("MyEJB")
public interface BeanInterface {
#Path("{username}")
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayHello(#PathParam("username") String username);
}
This is your session bean.
import javax.ejb.Stateless;
#Stateless
public class EJB implements BeanInterface{
#Override
public String sayHello(String username) {
return "Hello, "+username;
}
}
With JBOSS 7.1
Usage: http:// localhost:8080 /YOURAPPNAME/api/MyEJB/Fabio
Output:Hello, Fabio
Hope this helps.

Passivation issue with Stateful Session Bean

I'm using JBoss 6.1 Final, and get the following error message after my web application is running for a while (note the application doesn't crash), followed by a very long stack trace. I notice that this problem only occurs with stateful session beans that have other stateful session beans injected into them.
16:10:59,769 ERROR [org.jboss.ejb3.cache.simple.SimpleStatefulCache.UutSerialNumberServiceBean] problem passivation thread: javax.ejb.EJBException: Could not passivate; failed to save state
Here is the offending stateful session bean...
package com.ray.TEI.ejb;
import java.io.Serializable;
import javax.ejb.Stateful;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import com.ray.TEI.model.TestProcedure;
import com.ray.TEI.model.Uut;
import com.ray.TEI.model.UutSerialNumber;
#Stateful
public class UutSerialNumberServiceBean implements Serializable {
private static final long serialVersionUID = 1L;
#PersistenceContext(unitName="jasoni", type=PersistenceContextType.EXTENDED)
protected EntityManager em;
#Inject private ExecProcedureServiceBean execProcedureServiceBean;
public boolean isDuplicateSerialNumber(Uut uut, String serialNumber) {
return ((Number)em.createNamedQuery("UutSerialNumber.getCountByUutIdAndSerialNumber")
.setParameter("uut", uut)
.setParameter("serialNumber", serialNumber)
.getSingleResult()).intValue() > 0;
}
public UutSerialNumber findUutSerialNumberByUutSerialNumberId(Integer uutSerialNumberId) {
return em.find(UutSerialNumber.class, uutSerialNumberId);
}
public UutSerialNumber editSerialNumber(Integer uutSerialNumberId, String serialNumber) {
UutSerialNumber uutSerialNumber = findUutSerialNumberByUutSerialNumberId(uutSerialNumberId);
uutSerialNumber.setSerialNumber(serialNumber);
return uutSerialNumber;
}
public UutSerialNumber createSerialNumber(Uut uut, String serialNumber) {
UutSerialNumber uutSerialNumber = new UutSerialNumber();
uutSerialNumber.setSerialNumber(serialNumber);
uutSerialNumber.setUut(uut);
uut.getSerialNumbers().add(uutSerialNumber);
em.persist(uutSerialNumber);
for (TestProcedure testProcedure : uut.getTestProcedures()) {
execProcedureServiceBean.createExecProcedure(uutSerialNumber, testProcedure);
}
return uutSerialNumber;
}
}
Here is the injected stateful session bean...
package com.ray.TEI.ejb;
import java.io.Serializable;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import com.ray.TEI.model.ExecProcedure;
import com.ray.TEI.model.TestProcedure;
import com.ray.TEI.model.UutSerialNumber;
#Stateful
public class ExecProcedureServiceBean implements Serializable {
private static final long serialVersionUID = 1L;
#PersistenceContext(unitName="jasoni", type=PersistenceContextType.EXTENDED)
protected EntityManager em;
public ExecProcedure createExecProcedure(UutSerialNumber uutSerialNumber, TestProcedure testProcedure) {
ExecProcedure execProcedure = new ExecProcedure();
execProcedure.setUutSerialNumber(uutSerialNumber);
execProcedure.setTestProcedure(testProcedure);
execProcedure.setIterationCount(0);
em.persist(execProcedure);
return execProcedure;
}
}
anyone know what's wrong with this?
Thanks,
Jason
EntityManager is not serializable, I guess that's why it fails.
Couple of options from here:
deactivate passivation (easiest option in case you don't need that mechanism)
remove persistence-context from SFSB (this will most likely kill your EXTENDED mode)
replace EntityManager with Hibernate-Session, which is serializable (consider that experimental, I've never tried it out myself)