Injecting Managed Bean into Webservice - nullpointerexception

I'm trying to inject a Managed Bean within a Webservice but the injected Bean is allways null. Does anybody knows why and if so could you provide some hints or a workaround?
#WebService(targetNamespace = "http://impl.soap.valueservice.drivelog.com/", endpointInterface = "com.drivelog.valueservice.soap.impl.ValueService", portName = "ValueServiceImplPort", serviceName = "ValueServiceImplService")
public class ValueServiceImpl implements ValueService {
#Inject
private ValueServiceFacade valueBean;
...
}
#ManagedBean
public class ValueServiceFacadeImpl implements ValueServiceFacade {
...
}

This is really embarrassing.
According to this blog post (https://weblogs.java.net/blog/jitu/archive/2010/02/19/jax-ws-cdi-java-ee-6-0) and this post (https://blogs.oracle.com/arungupta/entry/totd_124_using_cdi_jpa), this should work but I can't make it work using TomEE here.
There is also some discussion about JSRs here (https://bugzilla.redhat.com/show_bug.cgi?id=1001610) but I can't really tell you why it does not work.
For TomEE (openEJB) all I could find was a lot of issues closed (related to https://issues.apache.org/jira/browse/OPENEJB-1592) with a scary comment "All done for certification", and maybe, the JEE Web Profile does not need to make these work together, while Geronimo, that implements the full EJB Profile, may need to work with this.
Please also see Java EE 6 WebService and CDI injection
So I can't really answer this. At the same time, I'll ask you to provide us some more information about what container you're using, so we can help you better.

For TomEE, a working approach considering #Inject in a web-resource is providing a method that #Produces an entity with that interface.
For your example, this could be small factory:
public class ValueServiceFactory {
#Produces
public ValueServiceFacade getValueService() {
return new ValueServiceFacadeImpl();
}
}

Related

Autofac how to pass configuration settings to base class

Currently I am using Autofac as IoC.
I would like to pass configuration (appsettings) to my base class through I am calling rest services.
current structure is
class baseclass{
public baseclass(logger){}
}
class derivedclass : baseclass{
public derivedclass(IService service):base(logger)
{
}
}
there are more than 50 classed where i am refering baseclass so dont want to pass configuration for each one.
Can you please help to find solution.
Thanks
I assume that you don't want to change derived constructors to pass through your configuration. So you have some options:
Inject your configuration to your base class by property
Live without dependency injection (directly access to ConfigurationManager or some Service Locator pattern).
Although both options are bad practices and I recommend you to inject your configuration through constructors.

How to use a #FeignClient to map a HAL JSON _embedded collection

We're trying to use a spring-cloud #FeignClient to call the HAL-JSON REST API of a microservice from another microservice. The service is implemented with Spring Data Rest, Spring Boot 1.4, with Hateoas enabled by default.
Using a dedicated DTO on the client side, all the simple properties are properly mapped, but the HAL-specific _embedded collection is ignored.
As taken primarly from this post, we implemented a custom Feign Decoder with a corresponding ObjectMapper, using the often mentioned Jackson2HalModule, but this still does not solve our issue.
You can reproduce the issue with this sample project, where the problem is described in more detail.
We appreciate any help or hints on this problem! Thanks in advance
I think the key to understanding how to deserialize this is that your Customer is the Resources class that is embedding the relations. So you need to deserialize it as Resources in order for the HalResourcesDeserializer to pick it up.
I got it to work this way.
#Getter
#Setter
public class Customer extends Resources<Resource<Relation>> {
public static enum Type {
PERSON, INSTITUTION
}
private String displayName;
private Integer rating;
private Type type;
public Collection<Resource<Relation>> getRelations() {
return this.getContent();
}
}
This still looks a little odd and I am not sure if this is the best solution.
I know I am responding to an old question, but in my experience, I had to add #EnableHyperMediaSupport to my main/any configuration class to resolve this issue. You can try that and verify if it works for you.

Can I create a request-scoped object and access it from anywhere, and avoid passing it around as a parameter in JAX-RS?

Say I have a web service / a REST resource that is called with some HTTP header parameters. The resource method builds a complex data object (currently a POJO) and eventually returns it to the client (via Gson as JSON, but that doesn't matter).
So I have this call hierarchy:
#Path(foo) ProjectResource #GET getProject()
-> new Project()
-> new List<Participant> which contains lots of new Participant()s
-> new Affiliation()
If I want the Affiliation object to be e.g. populated in English or German depending on a header parameter, I have to pass that as a parameter down the chain. I want to avoid having to do that. Maybe this is just fundamentally impossible, but it feels so wrong. All these objects only live inside the request, so wouldn't it be convenient to be able to access information tied to the request from anywhere?
I was hoping I could e.g. define a CDI #RequestScoped object that initialized itself (or gets populated by some WebFilter) and that I can then inject where I might need it.
But obviously that doesn't work from inside the POJOs, and I also had trouble getting hold of the headers from inside the request-scoped object.
I've read many SO questions/answers about EJBs and JAX-RS Context and CDI but I can't wrap my head around it.
Am I expecting too much? Is passing down the parameter really the preferred option?
If I understand what you need, you can try the following (just wrote this solution from the top of my head, but it should work):
Defining a class to store the data you need
Define a class annotated with #RequestScoped which will store the data you need:
#RequestScoped
public class RequestMetadata {
private Locale language;
// Default constructor, getters and setters ommited
}
Ensure you are using the #RequestScoped annotation from the javax.enterprise.context package.
Creating a request filter
Create a ContainerRequestFilter to populate the RequestMetadata:
#Provider
#PreMatching
public class RequestMetadataFilter implements ContainerRequestFilter {
#Inject
private RequestMetadata requestMetadata;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestMetadata.setLanguage(requestContext.getLanguage());
}
}
Performing the injection
And then you can finally perform the injection of the RequestMetadata using #Inject:
#Stateless
public class Foo {
#Inject
private RequestMetadata requestMetadata;
...
}
Please, be aware that anywhere is too broad: The injection will work into beans managed by the container, such as servlets, JAX-RS classes, EJB and CDI beans, for example.
You won't be able to perform injections into beans created by yourself neither into JPA entities.

How to properly construct dependent objects manually?

I'm using Ninject.Web.Common and I really like Ninject so far. I'm not used to dependency injection yet so I've got a pretty lame question I can't however google and answer to so far.
Suppose I have a Message Handler which depends on my IUnitOfWork implementation. I need to construct an instance of my handler to add it to Web API config. I've managed to achieve this using the following code:
var resolver = GlobalConfiguration.Configuration.DependencyResolver;
config.MessageHandlers.Add((myproject.Filters.ApiAuthHandler)resolver.GetService(typeof(myproject.Filters.ApiAuthHandler)));
I really dislike typing this kind of stuff so I'm wondering if I'm doing it right. What's the common way of constructing dependent objects manually?
Well I use dependency injection in real world projects only half a year ago, so I'm a pretty new to this stuff. I would really recommend the Dependency Injection in .NET book, where all the concepts are described pretty well and I learned a lot from it.
So far for me what worked the best is overwriting the default controller factory like this:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel _kernel;
public NinjectControllerFactory()
{
_kernel= new StandardKernel();
ConfigureBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{
return controllerType == null
? null
: (IController)_kernel.Get(controllerType);
}
private void ConfigureBindings()
{
_kernel.Bind<IUnitOfWork>().To<MessageHandler>();
}
}
And in the Global.asax in the Application_Start function you just have to add this line:
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
This approach is called the composition root pattern and considered the "good" way for dependency injection.
What I would recommend as well that if you have multiple endpoints like services and other workers as well you should create an Application.CompositionRoot project and handle there the different binding configuration for the different endpoints for your application.

lifecycle callbacks for JAX-RS resources?

suppose i have a jax-rs resource class that looks like this:
#Path("/nodes")
public class NodeResource {
//Temp - those injections should work
#EJB
ListNodesLocal nodeList;
//stuff
}
and i want some sort of lifecycle callback so i can manually lookup that field via JNDI because injection isnt working for me yet (using jboss 6 m5. see this issue : https://jira.jboss.org/browse/JBAS-8575).
ideally im looking for something like
#PostConstruct
private void init() {
//manual JNDI to come here
}
can i do this somehow ? i've tried javax.annotation.PostConstruct to no avail. is there something that works?
Since you linked to jboss in your question this answer assumes you're using the Resteasy implementation of JAX-RS. You can register interceptors to hook into the lifecycle. See here. That's how I was able to use Shiro annotations to authorize clients who want to invoke my API.