Adding beans to Injection Context in Embedded Undertow/CDI/RestEasy - jax-rs

Given an embedded Undertow instance with CDI:
SomeObject myObject = new SomeObject();
UndertowJaxrsServer server = new UndertowJaxrsServer();
Undertow.Builder builder = Undertow.builder().addHttpListener(port, "0.0.0.0");
server.start(builder);
ResteasyDeployment deployment = new ResteasyDeployment();
deployment.setApplication(new MyApplication(this));
deployment.setInjectorFactoryClass(CdiInjectorFactory.class.getName());
DeploymentInfo di = server.undertowDeployment(deployment, "/");
di.setClassLoader(getClass().getClassLoader())
.setContextPath("/")
.setDeploymentName("My deployment")
.addListeners(Servlets.listener(org.jboss.weld.environment.servlet.Listener.class));
server.deploy(di);
I would like to be able to inject things I've created outside of the container in the JAX-RS/CDI servlet context:
#Path
#Produces("application/json")
public class MyHandler {
#Inject
private SomeObject myObject;
#Inject
private UndertowJaxrsServer myServer;
}
How do I get arbitrary object instances into the CDI container?
Note: The use case is: I need to inject the class that the Undertow server instance is created in, inside of the CDI context. I cannot use JVM singletons, because I may need to spin up more than one.

Related

Can we access spring bean in Karate feature?

I have a class like below, can I access the myServer object or call handleOperation() method (which can use the injected bean) in Karate Feature file? If yes then may I know how?
#RunWith(SpringRunner.class)
#SpringBootTest(classes = {MyApiApp.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ContextConfiguration(classes = {AcceptanceTestConfiguration.class})
#ActiveProfiles("test")
#KarateOptions(features = "classpath:acceptanceTest/api/myapi.feature", tags = "#myapi")
public class MyAtddTest {
#Autowired
private MyServer myServer;
public void handleOperation() throws Exception {
myServer.handle();
}
}
There is no direct support for spring or the annotations. And not sure if you can mix the test annotations.
But take a look at the Spring MVC Dispatcher example here: https://github.com/intuit/karate/tree/master/karate-mock-servlet#mocking-your-servlet
Specifically how using Java interop you can do anything you want. I recommend getting the spring context using first-principles. For e.g:
ApplicationContext context = new AnnotationConfigApplicationContext(AcceptanceTestConfiguration.class);
And then getting beans out of it. Setting a test profile via System.setProperty() should be simple, search for it. You can do all this in even the karate-config.js and then it should be easy to use from all Scenario-s.
EDIT - also refer: https://github.com/Sdaas/hello-karate

Controlling lifetime of objects created by factory generated by ToFactory()

I am using the following Ninject related nuget packages in an MVC 5 WebAPI application:
Ninject.MVC5
Ninject.Extensions.Factory
ninject.extensions.conventions
I have a simple repository and a corresponding factory class like so:
public interface ITaskRunner
{
void Run();
}
public interface IRepository<T> where T: class
{
T[] GetAll();
}
public interface IRepositoryFactory<T> where T: class
{
IRepository<T> CreateRepository();
}
I have setup the Ninject bindings using ToFactory() from Ninject.Extensions.Factory like so:
kernel.Bind<ITaskRunner>().To<TaskRunner>().InSingletonScope();
kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
kernel.Bind<IRepositoryFactory<Contact>>().ToFactory();
I am using the factory in the following class:
public class TaskRunner : ITaskRunner
{
//MyTask is a simple POCO class(not shown for brevity)
IRepositoryFactory<MyTask> repoFactory = null;
IRepository<MyTask> repo = null;
public TaskRunner(IRepositoryFactory<MyTask> repoFactory)
{
this.repoFactory = repoFactory;
repo = repoFactory.CreateRepository();
}
//implementation elided
}
I am noticing that the call to repoFactory.CreateRepository() always returns the same instance of the factory (dynamic proxy) that Ninject generates.
Question : Is there a way to change/control this behavior and set a "lifetime" such as Transient, PerThread etc. for the instance that "CreateRepository" returns?
In this particular case, tasks might be processed asynchronously on multiple threads and the repository is not thread safe and hence singleton behavior for the instance returned from "CreateRepository" is not desirable.
I'm not sure what you are trying to achieve, but results you are seeing are quite expected because your TaskRunner is bound as Singleton (so constructed once), and you retrieve your repository in the TaskRunner constructor, which again happens once, and so repo is always the same instance. Note this happens regardless of how you bind IRepository and IRepositoryFactory, see Captive Dependency post by Mark Seemann for details http://blog.ploeh.dk/2014/06/02/captive-dependency/.
In fact, if you need to create repo in the constructor, you could just inject IRepository itself. The power of the Factory extension lies in the fact that it allows to resolve instances at runtime, not construction time. For example, if your TaskRunner has Run() method, you can create repository in it, so each task to run can have its own instance.

Update #ViewScoped bean from JAX-RS service

I've got a mishmash of JAX-RS webservices and JSF/CDI beans. Usual display of my #Entitys is from a #ViewScoped JSF bean collecting relevant entities in a #PostConstruct method:
#Named #ViewScoped
public class Manager {
private List<MyEntity> entities; // + getter
private MyEntity instance; // + getter/setter
#PostConstruct
public void init() {
entities = collectEntities();
instance = new MyEntity();
}
public void save() {
instance = persistInstance();
entities.add(instance);
}
// additional methods like collectEntities, persistInstance
}
Normal operation can call manager.save to persist a new entity and display it alongside the old ones.
Now, a JAX-RS service can also create entities that should be in the collection managed by such a scoped bean:
#Path("/myentity")
public class MyEntityService {
#PersistenceContext EntityManager em;
#PUT
public Response save(#FormParam("name") String name) {
MyEntity entity = new MyEntity(name);
em.persist(entity);
return Response.ok(entity.getId()).build();
}
}
The service can be called on a page where there's also a manager instance.
My question is: how can I make the existing manager instance aware of the additional entity, so that a JSF ajax re-render of a manager.entities list will include the entity created by the webservice?
So far, I've tried a CDI event observed by the CDI bean. The event gets fired from the service but is never received by the bean.
As a workaround I can fire a JSF ajax function telling the manager to refresh it's entity list (leveraging <a4j:jsFunction action="#{manager.init()}">, for example). However I'm unsure about the implications: will this expose a timing problem when the user asks for the entity list to be displayed earlier than the initialization can complete (the list isn't shown by default)?
As a total hack I can probably grab the bean from the session in the service and punch my data in. I shudder just thinking about it.
View scope is something that is JSF specific, as a JSF specific CDI context. It is alive only within the scope of the given view. JAX-RS has no specific way that I can think of to access this scope. I don't believe view scope would even have access to the HTTP request.

Invoked Stateless EJB never change

I'm writing a course on EJBs on JBOSS AS 7 and I have some troubles.
I have a simple local stateless EJB :
#Stateless
public class CitationEJB {
String citation ="Hello Citation";
public String getCitation(){
System.out.println("getting citation from :"+this.toString());
return this.citation;
}
public void setCitation(String citation) {
System.out.println("changing citation to : "+citation);
this.citation = citation;
}
#PostConstruct
public void sayHello(){
System.out.println("Hello, I'm a new EJB");
}
}
Then I invoke a EJB via JNDI in a JSF ManagedBean :
#ManagedBean
#SessionScoped
public class CitationBean {
//#EJB trying this time with JNDI
CitationEJB ejb;
public String getCitation() throws NamingException{
ejb = lookupCitationEJB();
return ejb.getCitation();
}
public String getCitation2() throws NamingException{
ejb.setCitation("hello Toto");
CitationEJB ejb = lookupCitationEJB();
return ejb.getCitation();
}
private static CitationEJB lookupCitationEJB() throws NamingException {
Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = new InitialContext(jndiProperties);
String jndiName = "java:global/CitationsDyn/CitationEJB!com.citations.ejb.CitationEJB";
//jndiName = "java:app/CitationsDyn/CitationEJB"; // Works also
return (CitationEJB) context.lookup(jndiName);
}
}
Then I show up the CitationEJB.getCitation() with JSF. Everything works fine except that when I make F5, and so a new request, I always have the same object : when I use CitationEJB.setCitation("Hello toto"), then F5, I do have "Hello Toto" and not a brand new Object.
When I use the #EJB annotation to get the EJB, I have the expected behaviour with a new object for every request.
So what I learned is that the EJB is picked in a pool, but when is it destroyed ? I guess that the JNDI lookup is not bound to a Scope as is a JSF page. But how is it exactly specified ?
The lifecycle of a Stateless Session Bean is managed by the container. A number of instances will be created and placed in an instance pool when the EJB is deployed (for example JBoss 6 creates 10 instances by default). The number can scale up or down based on the demand. The EJBs are generally not destoryed after use, but rather put back in to the pool to be used again and again.
For your application where you want to keep state, a Stateful Session Bean would be the properly choice (or Single Session Bean if you wanted to share state between the instances). With a Stateful Session Bean, the application can cause the EJB to be destoryed by annotating a method with #Remove.

wicket and AtUnit

I've started playing with Wicket and I've chosen Guice as dependency injection framework. Now I'm trying to learn how to write a unit test for a WebPage object.
I googled a bit and I've found this post but it mentioned AtUnit so I decided to give it a try.
My WebPage class looks like this
public class MyWebPage extends WebPage
{
#Inject MyService service;
public MyWebPage()
{
//here I build my components and use injected object.
service.get(id);
....
}
}
I created mock to replace any production MyServiceImpl with it and I guess that Guice in hand with AtUnit should inject it.
Now the problems are:
AtUnit expects that I mark target object with #Unit - that is all right as I can pass already created object to WicketTester
#Unit MyWebPage page = new MyWebPage();
wicketTester.startPage(page);
but usually I would call startPage with class name.
I think AtUnit expects as well that a target object is market with #Inject so AtUnit can create and manage it - but I get an org.apache.wicket.WicketRuntimeException: There is no application attached to current thread main. Can I instruct AtUnit to use application from wicketTester?
Because I don't use #Inject at MyWebPage (I think) all object that should be injected by Guice are null (in my example the service reference is null)
I really can't find anything about AtUnit inside Wicket environment. Am I doing something wrong, am I missing something?
I don't know AtUnit but I use wicket with guice and TestNG. I imagine that AtUnit should work the same way. The important point is the creation of the web application with the use of guice.
Here how I bind all this stuff together for my tests.
I have an abstract base class for all my tests:
public abstract class TesterWicket<T extends Component> {
#BeforeClass
public void buildMockedTester() {
System.out.println("TesterWww.buildMockedTester");
injector = Guice.createInjector(buildModules());
CoachWebApplicationFactory instance =
injector.getInstance(CoachWebApplicationFactory.class);
WebApplication application = instance.buildWebApplication();
tester = new WicketTester(application);
}
protected abstract List<Module> buildModules();
The initialization is done for every test class. The subclass defines the necessary modules for the test in the buildModules method.
In my IWebApplicationFactory I add the GuiceComponentInjector. That way, after all component instantiation, the fields annotated with #Inject are filled by Guice:
public class CoachWebApplicationFactory implements IWebApplicationFactory {
private static Logger LOG = LoggerFactory.getLogger(CoachWebApplicationFactory.class);
private final Injector injector;
#Inject
public CoachWebApplicationFactory(Injector injector) {
this.injector = injector;
}
public WebApplication createApplication(WicketFilter filter) {
WebApplication app = injector.getInstance(WebApplication.class);
Application.set(app);
app.addComponentInstantiationListener(new GuiceComponentInjector(app, injector));
return app;
}
}