Question

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)) ;

    }    
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top