Can I create a request-scoped object and access it from anywhere, and avoid passing it around as a parameter in JAX-RS? - 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.

Related

access ResourceInfo in Quarkus / Vertx HttpAuthenticationMechanism

In Quarkus (resteasy reactive), is there a way to get hold of the "ResourceInfo" in an HTTP Authentication Mechanism?
What I'm trying to do is read an annotation that is defined on the resource class or method, in order to choose an authentication mechanism based on it.
Injecting the ResourceInfo directly in the mechanism class does not work (and also, it is application scoped and not request scoped, so not sure it could work). I also couldn't find the info I need in the RoutingContext parameter.
I have also tried adding a ContainerRequestFilter, in which injecting the ResourceInfo with #Context works well, but I think perhaps the filters are called after the httpAuthenticationMechanism.authenticate(), because it's not called in my test when the endpoint requires authentication.
Is there another way to do this?
----> To clarify with code what I would like to do:
have different JAX-RS resources with a custom #Authorization annotations with different "api names" like this:
#Path("/jwttest")
#ApplicationScoped
#Authorization("jwttest")
public class JWTTestController {
...
}
#Path("/oidctest")
#ApplicationScoped
#Authorization("myoidc")
public class OIDCTestController {
...
}
and then different configs like this:
myframework.auth.jwttest.type=jwt
myframework.auth.jwttest.issuer=123
myframework.auth.jwttest.audience=456
myframework.auth.myoidc.type=oidc
myframework.auth.myoidc.auth-server-url=myurl
And in the HttpAuthenticationMechanism, find the value of #Authorization, and based on it, call another provider like suggested in https://quarkus.io/guides/security-customization#dealing-with-more-than-one-httpauthenticationmechanism with the right api name so that it can load the config.

Injected messages returning null in eclipse e4

In my plugin, I have created separate packages for maintaining the messages.properties.In that same package I have created my Mesages.java class as well. Following is my message class
#Message(contributionURI="platform:/plugin/com.chinna.test.properties.messages")
public class Messages {
public String test1;
public String test2;
}
Then injected the message in a different package of the same plugin. like follows. The class in which injected is singleton class.
#Inject
#Translation
Messages messages;
after I injected it I tried access messages.properties in the code like follows
messages.test1
But my application is throwing Null-Pointer exception. since the "messages" is null.
even though I injected, I do not know why "messages" is null.
Could any please help me?
You can only use this in classes which are injected.
Injection is only done on classes referenced in the Application.e4xmi, some extension points or created/injected using the ContextInjectionFactory make or inject methods.
For other classes the older style of messages file extending NLS and calling NLS.initializeMessages can be used.

Differences between Proxy and Decorator Pattern

Can you give any good explanation what is the difference between Proxy and Decorator?
The main difference I see is that when we assume that Proxy uses composition and Decorator uses aggregation then it seems to be clear that by using multiple (one or more) Decorators you can modify/ add functionalities to pre-existing instance (decorate), whereas Proxy has own inner instance of proxied class and delegates to it adding some additional features (proxy behaviour).
The question is - Does Proxy created with aggregation is still Proxy or rather Decorator? Is it allowed (by definition in GoF patterns) to create Proxy with aggregation?
The real difference is not ownership (composition versus aggregation), but rather type-information.
A Decorator is always passed its delegatee. A Proxy might create it himself, or he might have it injected.
But a Proxy always knows the (more) specific type of the delegatee. In other words, the Proxy and its delegatee will have the same base type, but the Proxy points to some derived type. A Decorator points to its own base type. Thus, the difference is in compile-time information about the type of the delegatee.
In a dynamic language, if the delegatee is injected and happens to have the same interface, then there is no difference.
The answer to your question is "Yes".
Decorator Pattern focuses on dynamically adding functions to an object, while Proxy Pattern focuses on controlling access to an object.
EDIT:-
Relationship between a Proxy and the real subject is typically set at compile time, Proxy instantiates it in some way, whereas Decorator is assigned to the subject at runtime, knowing only subject's interface.
Here is the direct quote from the GoF (page 216).
Although decorators can have similar implementations as proxies, decorators have a different purpose. A decorator adds one or more responsibilities to an object, whereas a proxy controls access to an object.
Proxies vary in the degree to which they are implemented like a decorator. A
protection proxy might be implemented exactly like a decorator. On the other
hand, a remote proxy will not contain a direct reference to its real subject but only
an indirect reference, such as "host ID and local address on host." A virtual proxy
will start off with an indirect reference such as a file name but will eventually
obtain and use a direct reference.
Popular answers indicate that a Proxy knows the concrete type of its delegate. From this quote we can see that is not always true.
The difference between Proxy and Decorator according to the GoF is that Proxy restricts the client. Decorator does not. Proxy may restrict what a client does by controlling access to functionality; or it may restrict what a client knows by performing actions that are invisible and unknown to the client. Decorator does the opposite: it enhances what its delegate does in a way that is visible to clients.
We might say that Proxy is a black box while Decorator is a white box.
The composition relationship between wrapper and delegate is the wrong relationship to focus on when contrasting Proxy with Decorator, because composition is the feature these two patterns have in common. The relationship between wrapper and client is what differentiates these two patterns.
Decorator informs and empowers its client.
Proxy restricts and disempowers its client.
Decorator get reference for decorated object (usually through constructor) while Proxy responsible to do that by himself.
Proxy may not instantiate wrapping object at all (like this do ORMs to prevent unnecessary access to DB if object fields/getters are not used) while Decorator always hold link to actual wrapped instance.
Proxy usually used by frameworks to add security or caching/lazing and constructed by framework (not by regular developer itself).
Decorator usually used to add new behavior to old or legacy classes by developer itself based on interface rather then actual class (so it work on wide range of interface instances, Proxy is around concrete class).
Key differences:
Proxy provides the same interface. Decorator provides an enhanced interface.
Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.
Decorator can be viewed as a degenerate Composite with only one component. However, a Decorator adds additional responsibilities - it isn't intended for object aggregation.
Decorator supports recursive composition
The Decorator class declares a composition relationship to the LCD (Lowest Class Denominator) interface, and this data member is initialized in its constructor.
Use Proxy for lazy initialization, performance improvement by caching the object and controlling access to the client/caller
Sourcemaking article quotes the similarities and differences in excellent way.
Related SE questions/links:
When to Use the Decorator Pattern?
What is the exact difference between Adapter and Proxy patterns?
Proxy and Decorator differ in purpose and where they focus on the internal implementation. Proxy is for using a remote, cross process, or cross-network object as if it were a local object. Decorator is for adding new behavior to the original interface.
While both patterns are similar in structure, the bulk of the complexity of Proxy lies in ensuring proper communications with the source object. Decorator, on the other hand, focuses on the implementation of the added behavior.
Took a while to figure out this answer and what it really means. A few examples should make it more clear.
Proxy first:
public interface Authorization {
String getToken();
}
And :
// goes to the DB and gets a token for example
public class DBAuthorization implements Authorization {
#Override
public String getToken() {
return "DB-Token";
}
}
And there is a caller of this Authorization, a pretty dumb one:
class Caller {
void authenticatedUserAction(Authorization authorization) {
System.out.println("doing some action with : " + authorization.getToken());
}
}
Nothing un-usual so far, right? Obtain a token from a certain service, use that token. Now comes one more requirement to the picture, add logging: meaning log the token every time. It's simple for this case, just create a Proxy:
public class LoggingDBAuthorization implements Authorization {
private final DBAuthorization dbAuthorization = new DBAuthorization();
#Override
public String getToken() {
String token = dbAuthorization.getToken();
System.out.println("Got token : " + token);
return token;
}
}
How would we use that?
public static void main(String[] args) {
LoggingDBAuthorization loggingDBAuthorization = new LoggingDBAuthorization();
Caller caller = new Caller();
caller.authenticatedUserAction(loggingDBAuthorization);
}
Notice that LoggingDBAuthorization holds an instance of DBAuthorization. Both LoggingDBAuthorization and DBAuthorization implement Authorization.
A proxy will hold some concrete implementation (DBAuthorization) of the base interface (Authorization). In other words a Proxy knows exactly what is being proxied.
Decorator:
It starts pretty much the same as Proxy, with an interface:
public interface JobSeeker {
int interviewScore();
}
and an implementation of it:
class Newbie implements JobSeeker {
#Override
public int interviewScore() {
return 10;
}
}
And now we want to add a more experienced candidate, that adds it's interview score plus the one from another JobSeeker:
#RequiredArgsConstructor
public class TwoYearsInTheIndustry implements JobSeeker {
private final JobSeeker jobSeeker;
#Override
public int interviewScore() {
return jobSeeker.interviewScore() + 20;
}
}
Notice how I said that plus the one from another JobSeeker, not Newbie. A Decorator does not know exactly what it is decorating, it knows just the contract of that decorated instance (it knows about JobSeeker). Take note here that this is unlike a Proxy; that, in contrast, knows exactly what it is decorating.
You might question if there is actually any difference between the two design patterns in this case? What if we tried to write the Decorator as a Proxy?
public class TwoYearsInTheIndustry implements JobSeeker {
private final Newbie newbie = new Newbie();
#Override
public int interviewScore() {
return newbie.interviewScore() + 20;
}
}
This is definitely an option and highlights how close these patterns are; they are still intended for different scenarios as explained in the other answers.
A Decorator adds extra responsibility to an object, while a proxy controls access to an object, they both use composition. If your wrapper class messes with the subject, it is obviously a proxy. Let me explain by a code example in PHP:
Code Example
Given is the following CarRepository:
interface CarRepositoryInterface
{
public function getById(int $id) : Car
}
class CarRepository implements CarRepositoryInterface
{
public function getById(int $id) : Car
{
sleep(3); //... fake some heavy db call
$car = new Car;
$car->setId($id);
$car->setName("Mercedes Benz");
return $car;
}
}
CarRepository-Proxy
A Proxy is often used as lazy loading or a cache proxy:
class CarRepositoryCacheProxy implements CarRepositoryInterface
{
private $carRepository;
private function getSubject() : CarRepositoryInterface
{
if($this->carRepository == null) {
$this->carRepository = new CarRepository();
}
return $this->carRepository;
}
/**
* This method controls the access to the subject
* based on if there is cache available
*/
public function getById(int $id) : Car
{
if($this->hasCache(__METHOD__)) {
return unserialize($this->getCache(__METHOD__));
}
$response = $this->getSubject()->getById($id);
$this->writeCache(__METHOD__, serialize($response));
return $response;
}
private function hasCache(string $key) : bool
{
//... implementation
}
private function getCache(string $key) : string
{
//... implementation
}
private function writeCache(string $key, string $result) : string
{
//... implementation
}
}
CarRepository-Decorator
A Decorator can be used as long as the added behavior does not "control" the subject:
class CarRepositoryEventManagerDecorator implements CarRepositoryInterface
{
private $subject, $eventManager;
/**
* Subjects in decorators are often passed in the constructor,
* where a proxy often takes control over the invocation behavior
* somewhere else
*/
public function __construct(CarRepositoryInterface $subject, EventManager $eventManager)
{
$this->subject = $subject;
$this->eventManager = $eventManager;
}
public function getById(int $id) : Car
{
$this->eventManager->trigger("pre.getById");
//this method takes no control over the subject
$result = $this->subject->getById($id);
$this->eventManager->trigger("post.getById");
return $result;
}
}
Proxy provides the same interface to the wrapped object, Decorator provides it with an enhanced interface, and Proxy usually manages the life cycle of its service object on its own, whereas the composition of Decorators is always controlled by the client.
Let me explain the patterns first and then come to you questions.
From the class diagram and meanings, they are very similar:
Both have the same interface as its delegatee has.
Both add/enhance the behavior of its delegatee.
Both ask the delegatee to perform operations(Should not work with null delegatee).
But they have some difference:
Different intents:
Proxy enhances the behavior of delegatee(passed object) with quite different domain knowledge from its delegatee. Eg, a security proxy adds security control of the delegatee. A proxy to send remote message needs to serialize/deserialize data and has knowlege on network interfacing, but has nothing to do with how to prepare source data.
Decorator helps on the same problem domain the delegatee works on. Eg, BufferedInputStreaman(an IO decorator) works on input, which is the same problem domain(IO) as its delegatee, but it cannot perform without a delegatee which provides IO data.
Dependency is strong or not:
Decorator relies on delegate to finish the behavior, and it cannot finish the behavior without delegatee(Strong). Thus we always use aggration over composition.
Proxy can perform faked behavior even it does not need a delegatee(Weak). Eg, mockito(unit test framework) could mock/spy a behavior just with its interface. Thus we use composition to indicate there's no strong dependency on real object.
Enhance multipletimes(as mentioned in question):
Proxy: we could utilize proxy to wrap real object once not several times.
Decorator: A decorator can wrap the real object several times or can wrap the object which is already wrapped by a decorator(which could be both a different decorator or the same decorator). Eg, for an order system, you can do discount with decorators.
PercentageDiscountDecorator is to cut 50% off, and DeductionAmountDiscountDecorator is to deduct 5$ directly if the amount is greater than 10$(). So,
1). When you want to cut 50% off and deduct 5$, you can do: new DeductionAmountDiscountDecorator(new PercentageDiscountDecorator(delegatee))
2). When you want to deduct 10$, you can do new DeductionAmountDiscountDecorator(new DeductionAmountDiscountDecorator(delegatee)).
The answer to the question has nothing to do with the difference between Proxy and Decorator. Why?
Design patterns just patterns for people who are not good at OO skills to make use of OO solutions. If you are familiar with OO, you don't need to know how many design patterns there(Before design patterns invented, with the same prolbem skilled people could figure out the same solution).
No two leaves are exactly the same, so as the problems you encount. People will always find their problems are different from the problems given by design patterns.
If your specified problem is really different from both problems that Proxy and Decorator work on, and really needs an aggregation, why not to use? I think to apply OO to your problem is much more important than you label it a Proxy or Decorator.

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.

IQueryable Repository with StructureMap (IoC) - How do i Implement IDisposable?

If i have the following Repository:
public IQueryable<User> Users()
{
var db = new SqlDataContext();
return db.Users;
}
I understand that the connection is opened only when the query is fired:
public class ServiceLayer
{
public IRepository repo;
public ServiceLayer(IRepository injectedRepo)
{
this.repo = injectedRepo;
}
public List<User> GetUsers()
{
return repo.Users().ToList(); // connection opened, query fired, connection closed. (or is it??)
}
}
If this is the case, do i still need to make my Repository implement IDisposable?
The Visual Studio Code Metrics certainly think i should.
I'm using IQueryable because i give control of the queries to my service layer (filters, paging, etc), so please no architectural discussions over the fact that im using it.
BTW - SqlDataContext is my custom class which extends Entity Framework's ObjectContext class (so i can have POCO parties).
So the question - do i really HAVE to implement IDisposable?
If so, i have no idea how this is possible, as each method shares the same repository instance.
EDIT
I'm using Depedency Injection (StructureMap) to inject the concrete repository into the service layer. This pattern is followed down the app stack - i'm using ASP.NET MVC and the concrete service is injected into the Controllers.
In other words:
User requests URL
Controller instance is created, which receives a new ServiceLayer instance, which is created with a new Repository instance.
Controller calls methods on service (all calls use same Repository instance)
Once request is served, controller is gone.
I am using Hybrid mode to inject dependencies into my controllers, which according to the StructureMap documentation cause the instances to be stored in the HttpContext.Current.Items.
So, i can't do this:
using (var repo = new Repository())
{
return repo.Users().ToList();
}
As this defeats the whole point of DI.
A common approach used with nhibernate is to create your session (ObjectContext) in begin_request (or some other similar lifecycle event) and then dispose it in end_request. You can put that code in an HttpModule.
You would need to change your Repository so that it has the ObjectContext injected. Your Repository should get out of the business of managing the ObjectContext lifecycle.
I would say you definitely should. Unless Entity Framework handles connections very differently than LinqToSql (which is what I've been using), you should implement IDisposable whenever you are working with connections. It might be true that the connection automatically closes after your transaction successfully completes. But what happens if it doesn't complete successfully? Implementing IDisposable is a good safeguard for making sure you don't have any connections left open after your done with them. A simpler reason is that it's a best practice to implement IDisposable.
Implementation could be as simple as putting this in your repository class:
public void Dispose()
{
SqlDataContext.Dispose();
}
Then, whenever you do anything with your repository (e.g., with your service layer), you just need to wrap everything in a using clause. You could do several "CRUD" operations within a single using clause, too, so you only dispose when you're all done.
Update
In my service layer (which I designed to work with LinqToSql, but hopefully this would apply to your situation), I do new up a new repository each time. To allow for testability, I have the dependency injector pass in a repository provider (instead of a repository instance). Each time I need a new repository, I wrap the call in a using statement, like this.
using (var repository = GetNewRepository())
{
...
}
public Repository<TDataContext, TEntity> GetNewRepository()
{
return _repositoryProvider.GetNew<TDataContext, TEntity>();
}
If you do it this way, you can mock everything (so you can test your service layer in isolation), yet still make sure you are disposing of your connections properly.
If you really need to do multiple operations with a single repository, you can put something like this in your base service class:
public void ExecuteAndSave(Action<Repository<TDataContext, TEntity>> action)
{
using (var repository = GetNewRepository())
{
action(repository);
repository.Save();
}
}
action can be a series of CRUD actions or a complex query, but you know if you call ExecuteAndSave(), when it's all done, you're repository will be disposed properly.
EDIT - Advice Received From Ayende Rahien
Got an email reply from Ayende Rahien (of Rhino Mocks, Raven, Hibernating Rhinos fame).
This is what he said:
You problem is that you initialize
your context like this:
_genericSqlServerContext = new GenericSqlServerContext(new
EntityConnection("name=EFProfDemoEntities"));
That means that the context doesn't
own the entity connection, which means
that it doesn't dispose it. In
general, it is vastly preferable to
have the context create the
connection. You can do that by using:
_genericSqlServerContext = new GenericSqlServerContext("name=EFProfDemoEntities");
Which definetely makes sense - however i would have thought that Disposing of a SqlServerContext would also dispose of the underlying connection, guess i was wrong.
Anyway, that is the solution - now everything is getting disposed of properly.
So i no longer need to do using on the repository:
public ICollection<T> FindAll<T>(Expression<Func<T, bool>> predicate, int maxRows) where T : Foo
{
// dont need this anymore
//using (var cr = ObjectFactory.GetInstance<IContentRepository>())
return _fooRepository.Find().OfType<T>().Where(predicate).Take(maxRows).ToList();
And in my base repository, i implement IDisposable and simply do this:
Context.Dispose(); // Context is an instance of my custom sql context.
Hope that helps others out.