Proper replacement of PreProcessInterceptor interface : RestEasy - authentication

In RestEasy 3.0.16.Final version PreProcessInterceptor interface is deprecated. So what is the proper replacement of this interface. In jboss eap 7 RestEasy version 3.0.16.Final is used.
Old code -
#Provider
#ServerInterceptor
#SecurityPrecedence
public class AbcInterceptor implements PreProcessInterceptor
{
public ServerResponse preProcess(final HttpRequest httpRequest, ResourceMethod resourceMethod) throws Failure,
WebApplicationException {
// auth logic
}
}
New code -
#Provider
#ServerInterceptor
#SecurityPrecedence
public class AuthenticationInterceptor
{
public ServerResponse preProcess(HttpRequest httpRequest, ResourceMethodInvoker method)
throws Failure, WebApplicationException {
// auth logic
}
}

The org.jboss.resteasy.spi.interception.PreProcessInterceptor interface is replaced by the javax.ws.rs.container.ContainerRequestFilter interface in RESTEasy 3.x.
So, you can can use the ContainerRequestFilter for the same.

Related

Quarkus 2.5: #Inject inside JAX-RS Application subclass not working anymore

After upgrading Quarkus from 1.6.1.Final to 2.5.Final the following #Inject fails inside javax.ws.rs.core.Application subclass:
#ApplicationScoped
public class MyBean {
public String foo() {
retun "bar";
}
}
#ApplicationPath("/")
public class MyApplication extends Application {
#Inject
MyBean myBean;
#Override
public Set<Class<?>> getClasses() {
myBean.foo(); // Causes NPE on Quarkus 2.5.Final, worked well with 1.6.1.Final
}
}
I tried with CDI.current().select(MyBean.class).get() but got Unable to locate CDIProvider.
Any other workaround I can try? Thanks.
#Inject in JAX-RS Application classes has been since disallowed. I was able to solve my issue (registering resource classes by config) using #IfBuildProperty annotation.

Jersey 2 and Spring Boot - Not able to inject using #Context on Provider

Using Jersey 2.3 on Spring Boot 2.4. I have 2 JAX-RS providers. One of them implements ContainerRequestFilter(PreMatching) and another one extends JacksonJaxbJsonProvider(from jackson-jaxrs-json-provider).
I am setting a property in ContainerRequestFilter onto ContainerRequestContext. Then I am trying to inject ContainerRequestContext onto another JAX-RS Provider using #Context. But this injection is always coming null.
If I inject same object onto a JAX-RS resource using #Context, Jersey does inject it. Not sure what I am missing here. Any help is greatly appretiated.
#PreMatching
#Provider
public class MyJaxRSContextProvider implements ContainerRequestFilter {
#Context
Providers providers;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.setProperty("myProperty", property);
}
}
#Provider
#Consumes(MediaType.WILDCARD)
#Produces(MediaType.WILDCARD)
public class MyJsonJaxRSProvider extends JacksonJaxbJsonProvider {
#Context
ContainerRequestContext requestContext;
#Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return true;
}
#Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
//requestcontext is always null
requestContext.getProperty("myProperty");
}
}
Things to consider:
In some cases, if you register the provider as an instance, then injection may not occur. Best thing to do is to register the provider as a class or just use scanning provided by Jersey.
Some injectables are not proxiable, which will prevent smaller scoped services to be injected into larger scoped serviced (example: request scoped object into a a singleton). In this case, you should wrap the injection in javax.inject.Provider
#Inject
private javax.inject.Provider<ContainerRequest> requestProvider;
...
ContainerRequest request = requestProvider.get();

ejb in session context is allways null

i have created sigleton session bean which keeps one connection to my mongo database. It works well in jax-rs class when using #EJB annotation - after controller is contructed and bean is injected it calls init method anotated with #PostConstruct.
Then i created similar class, which is implementing SecurityContext. I used same pattern as in controller, but it is not working properly. init() method is never called and EJB instance is always null.
So is there a way to inject EJB to my SecurityContext implemetation ? it works well unless i try to inject and use MongoConnection
my singleton session bean I use to connect mongo database:
#Singleton
#Startup
public class MongoConnection {
#PostConstruct
public void init() {
// initialize properties
}
I use it in JAX-RS controller. it works here, also in classes inherited from EntityController.
Produces(MediaType.APPLICATION_JSON)
public class EntityController extends Application {
#Context
private UriInfo context;
**#EJB
protected MongoConnection connection;**
public EntityController() {
#PostConstruct
void init() {
...
connection.getMongo();
connection.getDatabaseName();
...
}
}
I implemented my own security context, which is looking for loged user roles in mongo database.
public class MongoSecurityContext implements SecurityContext {
**#EJB
private MongoConnection connection;**
public MongoSecurityContext() {
}
#PostConstruct
void init() {
...
connection.getMongo();
connection.getDatabaseName();
...
}
public MongoSecurityContext(ContainerRequestContext requestContext) {
token = requestContext.getHeaderString("token");
}
#Override
public boolean isUserInRole(String roleName) {
//**connection is allways null**, so it returns false;
if (connection == null)
return false;
}
}
EDIT:
I forget, i also have this warning in glassfish 4 console:
A provider extremeteacher.mongo.connection.MongoConnectionEjb registered in SERVER runtime does not implement any provider interfaces applicable in the SERVER runtime. Due to constraint configuration problems the provider extremeteacher.mongo.connection.MongoConnectionEjb will be ignored
EDIT2:
#Provider
#Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext requestContext) {
requestContext.setSecurityContext(new MongoSecurityContext(requestContext)) ;
}
}
Injection does not work for objects created with new because the container is never given control to perform the injection. I recommend moving the #EJB to the filter and passing it to the MongoSecurityContext constructor.

Failed to create EJB in REST service

I have a problem with injecting EJB inside of a REST service (using jersey on glassfish 3.2 server) and I'm puzzled.
I have an EJB interface declared as:
import javax.ejb.Local;
#Local
public interface TestServiceLocal {
public String getText();
}
and the class bean that implements it:
import javax.ejb.Local;
import javax.ejb.Stateless;
/**
* Session Bean implementation class TestService
*/
#Stateless
#Local(TestServiceLocal.class)
public class TestService implements Serializable, TestServiceLocal {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TestService() {
// TODO Auto-generated constructor stub
}
#Override
public String getText() {
return this.getClass().getName();
}
}
The REST service looks like:
#Path("/service")
#Stateless
public class TestRestService {
#EJB(beanName="TestService")
private TestServiceLocal testService;
public TestRestService () {
}
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/events")
public String getText() {
return testService.getText();
}
}
The problem is that when the REST service is called the bean cannot be created:
SEVERE: EJB5070: Exception creating stateless session bean : [TestRestService]
WARNING: EJB5184:A system exception occurred during an invocation on EJB TestRestService, method: public java.lang.String TestRestService.getText()
WARNING: javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:454)
at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2547)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1899)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy839.getText(Unknown Source)
I had already took a look at the answers posted here but none of them seemed to work for me. Any help will be appreciated. Thank you!
PS: I forgot to mentioned (don't know if it's relevant). My project is created under eclipse Juno as Dynamic Web Project.

EJB 3.1 : Singleton bean not getting injected inside another stateless bean though both beans are getting registered

Here is my bean that is trying to inject a singleton bean InformationService :
#Path("/information/{name}")
#Stateless (name="InformationResource")
public class InformationResource {
#EJB
private InformationService appService;
#GET
#Produces(MediaType.APPLICATION_XML)
public Information getInfo(#PathParam("name") String name){
return appService.getMap().get(name);
}
#PUT
#POST
#Consumes(MediaType.APPLICATION_XML)
public Information putInfo(#PathParam("name") String name, Information info){
return appService.getMap().put(name,info);
}
#DELETE
public void deleteInfo(#PathParam("name") String name){
appService.getMap().remove(name);
}
}
This is the InformationService class
#Singleton
public class InformationService {
private Map<String,Information> map;
#PostConstruct
public void init(){
map = new HashMap<String,Information>();
map.put("daud", new Information("B.Tech","Lucknow"));
map.put("anuragh", new Information("M.Sc","Delhi"));
}
public Map<String,Information> getMap(){
return map;
}
}
Its part of a very simple JAX-RS implementation and I am deploying as war in JBoss 6.1 Final. The problem is that InformationService throwing a NullPointerException when I make the proper get request. If I initialize appService explicitly, everything works fine. Why is #EJB annotation not working ?
Are you using Jersey as REST implementation? If so, EJB injection is not supported out of the box.
This link provides more information on this and also a solution.
Check that your #Singleton is javax.ejb.Singleton.
Any other exceptions before NPE ?