ContainerRequestFilter is called twice - jax-rs

I have simple Apache Meecrowave 1.2.1 (OWB+CXF) application with ContainerRequestFilter:
#Singleton
#Provider
public class AppInstanceAndSecurityFilter implements ContainerRequestFilter {
...
#Inject
private AppInstanceService appInstanceService;
...
#Context
private ResourceInfo resourceInfo;
...
}
AppInstanceAndSecurityFilter class is returned in getClasses() method of Application subclass.
The problem is that filter is called twice and there are two instances of filter - one with all successfully resolved #Inject and #Context references and one with all #Inject references null and all #Context references successfully resolved.
Why there are two instances of filter, one with null #Inject references?

Related

Null controller when test with Mockito

I'm testing a controller that needs a Autowired Service.
I read in many place (example Mockito: How to test my Service with mocking?) I need to do it like this
#RunWith(JUnitPlatform.class)
public class AdminControllerTest {
#Mock
private AdminService service;
#InjectMocks
private AdminController adminController;
#Test
public void registerUser() {
Boolean resultReal = adminController.registerUser();
assertTrue(resultReal);
}
}
But it's fail and I see is because the adminController is null
Instead, if I create the controller like this
AdminController adminController = new AdminController();
It works, but then I can inject the mock.
Maybe I'm forgotten something
Per the documentation for InjectMocks:
MockitoAnnotations.openMocks(this) method has to be called to initialize annotated objects. In above example, openMocks() is called in #Before (JUnit4) method of test's base class. For JUnit3 openMocks() can go to setup() method of a base class. Instead you can also put openMocks() in your JUnit runner (#RunWith) or use the built-in MockitoJUnitRunner.
Thus, either:
call openMocks(this) somewhere before the test is run or
Use #RunWith(MockitoJUnitRunner.class) on the class

Dependency Injection with Database-Context. How to get Database-Context in a normal Class

I have configured my .net-core 2.1 service with a database-context in the start-up method.
services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString(nameof(DatabaseContext))));
Now i could do the following to get my database-context in my controller:
var context = serviceProvider.GetService<DatabaseContext>();
This works very well. But how could i access the Database-Context in a normal class something like this sould be done:
public class MyAccessClass{
public MyAccessClass(){
//Access the ServiceProvider or get the Database-Context class anywhere else
}
}
I don't want to pass the database-context object through the constructor or to initialize the DatbaseContext Class again.
Thanks for your help.
You should take your dependencies through the constructor, preferrably an interface, e.g. IDatabaseContext, but code sample below based on your code. If you add MyAccessClass as a service, e.g. services.AddTransient<MyAccessClass>(), and then use dependency injection in your controller, the database context would be automatically injected in the constructor by the default IoC container in ASP.NET Core.
You shouldn't have it rely on IServiceProvider, the reasoning is that your class wants to make no assumption of implementations, it just needs the database context. Having it rely on IServiceProvider would assume this context, and any possible future dependencies, comes from the IoC in ASP.NET Core which may not be the case (what if you just want to release this as a class library later on?). It would make the MyAccessClass class hard to test and use outside of a controller.
You say in your comment:
"...or get the Database-Context class anywhere else"
That anywhere else is completely flexible by simply accepting the context into the constructor since your class doesn't know where anywhere else is but whatever is creating your class does know!
Example of DI in ASP.NET Core
Take context as a dependency through constructor
public class MyAccessClass{
private readonly DatabaseContext databaseContext;
public MyAccessClass(DatabaseContext databaseContext) {
this.databaseContext = databaseContext;
}
}
Add as service
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MyAccessClass>();
}
Inject into a controller
public class MyController : Controller
{
private readonly MyAccessClass myAccessClass;
//Happily injected through DI
public MyController(MyAccessClass myAccessClass)
{
this.myAccessClass = myAccessClass;
}
}
Or inject straight into an action
public class MyController : Controller
{
public MyController()
{
}
public IActionResult MyAction([FromServices] MyAccessClass myAccessClass)
{
}
}

JPA Eclipselink TableGenerator in hierarchy - one generator per class

I'm working with EclipseLink 2.6.1-RC1, I have a class hierarchy that will illustrate below:
#MappedSuperclass
public abstract class AbstractEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
.... irrelevant code ....
}
#Entity
public class Coupon extends AbstractEntity {
---- irrelevant ...
}
#Entity
public class Sector extends AbstractEntity {
.... irrelevant ...
}
I need to use TableGenerator for id generation purpose. But what I need is that there was a record for each child class in the table of "Sequences". I allready search in different places, but nothing. I know that if i split the declaration of "id" field on every child class it works, but i have moooore of two childrens jaja.
Any help? thanks!!!
Well, after keep searching, i found other's questions similars to mine, but with no answers, and i found a bug in eclipselink due 2013 with this funtionality without further information of release version.
But, in this answer, tells that we can use "Customizer" to change several things of JPA descriptors, so, i change the sequence name in that form, and its works perfect!
public class SequenceCustomizer implements DescriptorCustomizer {
#Override
public void customize(ClassDescriptor descriptor) throws Exception {
descriptor.setSequenceNumberName(descriptor.getTableName());
}
}

Interceptor on super method in CDI 1.0/JEE6

In the following case,
public class Base {
#Transactional
public void doSave() {
// ...
}
}
public class Inherited extends Base {
public void someMethod() {
super.doSave();
}
#Override
public void doSave() {
super.doSave();
}
}
If I add the #Transactional annotation to Inherited.someMethod, the interceptor gets called without issue.
However, without the annotation on the inherited class, the interceptor does not get involved in the call to the super class from Inherited.someMethod().
Furthermore, calling Inherited.doSave() does not seem to get the interceptor invoked either. I would have expected the annotation on the superclass to be also valid on the subclass. Is this not the expected behaviour?
I am using Apache DeltaSpike for the #Transactional annotation and this is being deployed as a war in an ear (technically as a jar in a war in an ear). However, this may not be relevant as trying with a custom interceptor shows the same behaviour.
This is JBoss EAP 6.3.0 Alpha in case its relevant.
This is expected. Interceptors are only applied if the object is managed. When you you write it this way with inheritence, it's not applied as it's not part of a call stack that CDI is aware of. You would need to inject Base into your class and call Base.doSave

CDI injection not done in base class for jax-rs controller

I'm struggling with CDI and class inheritence.
I've a JAX-RS controller declared as :
#Path("/share")
public class ControllerShare extends BaseController {
#Inject
private ServiceShare serviceShare;
#PostConstruct
private void verifInit() throws ExceptionTechnique {
log.warn("Checking CDI injection");
if (serviceShare == null) {
log.error("serviceAccount not initialized. Check your EJB configuration");
throw new ExceptionTechnique("serviceShare not initialized. Check your EJB configuration.");
}
}
...
}
This controller extends a base controller declared as :
public abstract class BaseController {
private Logger log = LoggerFactory.getLogger(ControllerShare.class);
#Context protected HttpServletRequest request;
#Inject private ControlerSession ctrlSession;
public BaseController() {}
#PostConstruct
private void verifInit() throws ExceptionTechnique {
log.warn("Checking CDI injection");
if (ctrlSession == null) {
log.error("controllerSession not initialized. Check your CDI configuration");
throw new ExceptionTechnique("serviceAccount not initialized. Check your CDI configuration.");
}
}
...
}
The problem is that injection is correctly done in ControllerShare (I correctly see "Checking CDI injection"), but is not done in the BaseController class (ctrlSession is null).
I try #Named and others combination without success. Injection is just done in ControllerShare and not in BaseController.
EDIT:
One more thing : curiously the #Context is working fine. My request is set and the value is correct.
Thank's for any explanation and solution.
Actually, this should work according to
http://docs.jboss.org/cdi/spec/1.0/html/inheritance.html
4.2. Inheritance of member-level metadata
Suppose a class X is extended directly or indirectly by the bean class of a managed bean or session bean Y.
If X declares an injected field x then Y inherits x.
On a side note: #PostConstruct however is not inherited if you specify it anew. Therefore, in your sub-class your method must be named differently to have both initializers executed.
If X declares an initializer, non-static observer, #PostConstruct or #PreDestroy method x() then Y inherits x() if and only if neither Y nor any intermediate class that is a subclass of X and a superclass of Y overrides the method x().