How to consume multiple services using ServiceTracker efficiently? - osgi

I would like to use ServiceTracker in order to consume the services published by our company.
Instead of creating new ServiceTracker for each service I want to consume I thought it would be better to create just one with a filter and then get the services from it:
Filter filter = ctx.createFilter("(" + Constants.OBJECTCLASS + "=com.mycomp*)");
tracker = new ServiceTracker(ctx, filter, null);
The problem with this approach is that I then need to iterate over the service references the tracker had found examine their objectClass property and see if I can assign it to the service object which is very cumbersome and error prone due to casting that is required.
Any other ideas how to cunsume multiple services using more elegant way?

I think it is the wrong question :-) From the question I infer that you have a method that takes a service from your company and you want that method called. That is, somewhere in your code you need to be informed about a specific type com.mycomp.X, that is, you're not interested in general services from your company, you have a clear type dependency. In your question you assume that they need to be dispatched centrally which is usually not robust, error prone, and a maintenance hotspot; every time you have a new company service you need to update the dispatch method.
A MUCH better solution seems to be to use Declarative services and use bndtools with annotations. In that model, each place where you need service:
#Component public class SomeMyCompComponent {
...
#Reference
void foo( com.mycomp.X x ) { ... }
...
}
In this model, you do not need to centrally maintain a dispatcher, any class can get the services it needs when they need it. This model also accurately handles multiple dependencies and lots more goodies.
Maybe I do not understand the problem correctly because I inferred the problem from the solution you required. However, I think you try to abuse the Service Tracker for a task it was not intended to do.
Unfortunately, DS is not build into the framework as we should have done :-(

You could subclass ServiceTracker and add methods to provide direct access to the service types in which you are interested. For example, you could store the services in a typesafe heterogeneous container [1]. Then you would be able to call method on your ServiceTracker subclass which take the type of the service you are interested in and they could be easily looked up in the typesafe heterogeneous container.
[1] Effective Java, 2nd Ed., Item 29.

Related

Is Spring more suitable for business-logic-focused apps?

After reading the official doc of Spring, I got this impression:
"Spring, specifically its IoC container, suits better for apps that requires only one instance of most classes".
For example we have an online shopping app. Its business logic is divided into
Order process
Payment process
and encapsulating these two parts into classes is for better code organisation rather than for implementing any functionalities, and Spring makes it easier to inject the same instance to whichever object needs it, to avoid frequent and redundant new.
However, in a Mario-like game, we might have a class Coin that requires hundreds of individual instances, and hence Spring can't be applied in this case ('cause I think #qualifier makes more mess than the good part brought by IoC).
Is the above correct?
You're correct in thinking that you wouldn't inject an object that only applies in a narrow scope.
I could see objects with Request scope that are not Singleton. Spring has supported that from the beginning.
Method scope variables should not be under Spring's control. There's nothing wrong with calling new.
You should understand Spring better before you make judgements about its efficacy.

Where it is necessary to keep the DTO object when interacting with several services

A little background of my problem. I have a set of the following services:
AdapterService - intended for loading certain products from an external system
ApiGateway - accepts requests from UI. In particular, now there is only one request that receives product data to display product in UI from Product Service
ProductService - data storage service for various products. The service itself does not specifically know what kind of product it specifically stores. All types of products are created dynamically by other services that are responsible for these products. Product data is stored as a key-value map (technically it is a json string in DB column)
There is a schema for service interations
So, services in BLUE zone are mine (they can be changed in any way). RED zone describes services of another team (they can't be changed).
Whats the problem
To load product from external system I want to use SpecialProductDto which will store product data. I can use some validation features like Spring annotations and so on. Then to load the product from Adapter Service to ProductService I must transform SpecialProductDto to Map<String, Object> because ProductSerivcie requires it via API.
When I would get product info for UI through ApiGateway, I will need to call ProductService api for getting product that return attribues in Map<String, Object> and then transform this data to some UIReponse which contains some part of product data (because I dont need all product information, just only name and price for example).
But I also want to use SpecialProductDto in my ApiGateway service, because it seems working with Map<String, Object> is error prone... I practically need to fetch data blindly from Map to construct UIResponse. And what if some attribute names will be changed? With Map I only will know it when the request would be made from UI but using special DTO I get such exception in compilation time.
Question
So, what is the best practiсe or maybe patterт should I use in such situation? At the moment I see the following solutions:
Duplicate DTOs in both AdapterService and ApiGateway services. So, any changes in one class must be supported in another
Use Map<String, Object> at my own peril and risk, hoping that nothing will change there
Share SpecialProductDTO between ApiGateway and AdapterSerivce in some separate library and service (seems to be antipattern because of sharing someting can make a lot of problems)
Сan anyone help?
In my opinion, there's nothing wrong on duplicating DTOs.
Also, there's nothing wrong on providing the DTO in a separate library to be imported on each project, you will only be sharing the ProductService's contract and that's it. It does not cause any tight coupling between the Api Gateway and the Adapter. If the contract changes, then it must be changed on all of it's consumers (api gateway and adapter), simple as that.
About using Maps: usually I don't recommend this, because, like you said, you will not be able to take advantages of the built-in Bean Validations that Spring (and other frameworks) provides, but not only that, you'll also, depending on the situation, be using lots of casts and type conversions, which is not good and can be prevented by using DTOs.
Also, be aware that a DTO, in my opinion, should not be named with the suffix of 'DTO'. That's because a name like SpecialProductDTO doesn't clearly states where this object is being used or should be used.
Instead, prefer a something like CreateSpecialProductRequest - this indicates that this object is used when creating a Special Product. Another example is CreateSpecialProductResponse which just represents the response (if needed) after a Special Product creation. Take a look at this StackOverflow answer: Java data transfer object naming convention?

Creational adapter

I have a lot of code like this
additional_params = {
date_issued: pending.present? ? pending.date_issued : Time.current,
gift_status: status,
date_played: status == "Opened" ? Chronic.parse("now") : (opened.present? ? opened.date_played : nil),
email_template: service&.email_template,
email_text: service&.email_text,
email_subject: service&.email_subject,
label: service&.label,
vendor_confirmation_code: service&.vendor_confirmation_code
}
SomeService.new(reward, employee: employee, **additional_params).create
The same pattern applies to many models and services.
What is the name of this pattern?
How to refactor the current solution?
Is there a gem to solve this kind of solution? Like draper or something else
To me, that looks a bit like a god object for every type of entity. You expect your service to take care of everything related to your entity. The entity itself just acts as a data container and isn't responsible for its data. That's called an anemic model.
First of all, you need to understand that there can be several representations of the same entity. You can have several different classes that represent a user. On the "List user" page, the class contains just a subset of the information, maybe combined with information from the account system (last login, login attempt etc). On the user registration page, you have another class as it's not valid to supply all information for the user.
Those classes are called data transfer objects. Their purpose is to provide the information required for a specific use case and to decouple the internal entity from the external API (i.e. the web page).
Once you have done that, your service classes will start to shrink and you need fewer custom parameters for every method call.
Now your service class has two responsibilities: To manage all entities and to be responsible for their business rules.
To solve that, you should start to only modify your entities through behaviors (methods) and never update the fields directly. When you do so, you will automatically move logic from your service class to your entity class.
Once that is done, your service classes will be even cleaner.
You can read about Domain Driven Design to get inspired (no need to use DDD, but get inspired by how the application layer is structured in it).
You can try the builder pattern. I am not familiar with a ruby gem, but you can find information here: https://en.wikipedia.org/wiki/Builder_pattern and https://en.wikipedia.org/wiki/Fluent_interface

How to make afterInsert / afterUpdate GORM method an async methods

Grails users know that Data access layer of this framework offer an AOP programming via seperation cross-layer from other soft layers : afterInsert, afterUpdate,beforeInsert .... methods .
class Person{
def afterInsert(){
//... Will be executed after inserting record into Person table
}
}
I search on the type of this methods vis-a-vis Constructor(instantiation ): Asynchronous or not . And i don't find the answer .
My question : if not, Does GORM will be breaked if we force those methods to be asynchronous.
UPDATE :
Indeed, we want send mails without using a ready plugin as we have our own API.
There are a great number of ways to accomplish what you are looking for, and without knowing all your requirements it's difficult to give you a solution that meets all of them. However, based on your question and the comments provided you could use the built in Asynchronous features in Grails to accomplish this.
This is just a sketch/example of something I came up with off the top of my head.
import static grails.async.Promises.*
class Person {
...
def afterUpdate() {
def task1 = task {
// whatever code you need to run goes here.
}
onComplete([task1]) {
// anything you want to run after the task completes, or nothing at all.
}
}
...
}
This is just one option. Again, there are a lot of options available to you. You could send a JMS message instead and have it processed on a different machine. You could use some type of eventing system, you could even use Spring AOP and Thread pools and abstract this even further. It depends on what your requirements are, and what your capabilities are as well.

symfony domain event

I'm trying to implement Domain Driven Design in my Symfony2 project and experience some problems.
After reading some articles on Domain Models I found, that
I should put all the business logic into my domain models(entities).
Application level stuff, that needs to be done and doesn't belong to domain logic is fired with Domain Events(sending emails, putting some messages to the queue, etc.)
Luckily, Symfony provides Events, but here is a problem - I can't raise event from my entity.
Symfony documentation suggects to use DI to inject the dispatcher into the class, that raises Event
http://symfony.com/doc/current/book/internals.html#passing-along-the-event-dispatcher-object
But Symfony Entities are newable, not injectable.
Right now I can see two ways:
1) Provide Event Dispather to Entity like this
class FooEntity
{
protected $dispatcher = null;
public function setEventDispatcher(EventDispatcher $dispatcher)
{
$this->dispatcher = $dispatcher;
}
}
2) Raise Events from the service(not from the Entity).
None of this options look pretty, because it seems to me that they break Domain Model ideology.
Can you point me in the right direction, please.
The idea of this here is to give paths to attain the DDD paradygm.
I do not want to shadow over #magnusnordlander answer, I will apply what he says.
Here is some of observations on the matter:
I think that the Entity itself should not have everything. It is sure not what the DDD people would say anyway. The [Doctrine2] Entity should only take care of the relationships (an entity with different variation too <= This is actually a thing that I was stuck for a while) and the aggregate root.
The Doctrine entity should only know about how to work with itself.
But, to Get Data or work with it, there is other stuff that you can use:
Repository
Is the thing that provides helpers to get your more sophisticated finders than what a quick findBy(array('id'=>$idvalue)) would do (and that the Entity/Assocation/Annotation cannot cover) and is indeed a great thing to have handy.
I personally tried to build all queries, and realized the EntityManager is already very good, out of the box. In most case, to my opinion: If you can /not/ use query or query builder, the better.
Business logic in all that...
Last thing on note, what you would be searching for must be to basically thin the Controller.
FooManager (for example) is where (if I am not mistaken) the business logic go.
I found a goldmine of information on that matter on this blog that covers:
Controllers and application logic revisited
Putting controllers in a diet, and mix it with some custom Event with
Leveraging the Symfony2 Event dispatcher
If you have any ideas, to augument, I set this answer as a Community Wiki
By Symfony entities, do you mean Doctrine 2 entities? If so, you can set services on both new objects and old objects that are loaded from the database in the following manner:
Prototype scoped service
Services in the prototype scope are always recreated when you get them. Instead of doing new FooEntity you would do $container->get('foo_entity').
In the YAML syntax you would define the service as follows:
foo_entity:
class: FooEntity
calls:
- [setEventDispatcher, [#event_dispatcher]]
scope: prototype
This will take care of new entities. For existing entities you need a...
Post load event listener
Create an event listener, in the manner described here:
http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html
Have the listener listen for the postLoad-event. Inject the event dispatcher into the listener service, and use the listener service to set the event dispatcher on the entity.
Bear in mind that the listener service will fire after loading any entity, not just the FooEntity, so you'll need to do a type check.

Resources