This is similar to How to deserialize from a file to different class. But, I'm developing micro-services using Dropwizard.
I have two services, service A and service B. I have a message queue (RabbitMQ) setup between the two services.
I am trying to send an object of type Class A (defined in service A) from service A to service B. I have not imported class A in service B. However in service B i have Class B defined which is exactly same as Class A.
I am getting a ClassNotFoundException: Class A in service B when service B tries to deserialize and typecast the object to Class B.
I want the two jars to be as independent as possible.
Is there a way to do this.
You can use Apache Avro for serializing (predefined avro schema) your objects between two service or if you want to use a queue bewteen them. On top you will lower the needed network bytes, because apache avro serialization is really good.
You can also use CatainProto or ProtoBuffer, but I like the apache avro method.
Related
Let's admit I want to map an object A to an object B with Orika.
One field of the object B is constructed by a call to an external webservice with a parameter I have in object A.
Is it a good practice to create an Orika custom-mapper which uses a service that makes a call to an external service, or should I separate this behaviour in an external class ?
External service
^
|
[A]-----> Custom Mapper ------> [B]
Custom mappers in Orika can be regular Spring Beans there is already a lot of example on how to create Spring based Orika mapper
Take a look of this example:
https://github.com/dlizarra/orika-spring-integration
UPDATE
Yes absolutely.
I'm trying to create an application using multiples modules. I had an application with a single module but we just decide to split up.
We created two containers, the first one is moduleAContainer and the second one for moduleBContainer, I mean IOC contailers (Castle).
We have too an IoCWorker class that is responsible for keep an specific container static and provide some methods to resolve.
My problem is that, using ControllerFactory of Asp.net MVC for example, how can I decide with one should resolve my dependency?
Should be something like, IocWorker.Resolve("containername") but per web request? What is my parameter to decide it?
Can I do it using child containers?
Thank you so much.
Let me try to come up with a solution on your situation of two modules(Module A and B, by the way they both run same service interface ISaleAppService) having same interface (IUnitOfWork) with different implementation details solid classes.
So let's say it's a delivery app.
Module A uses Motorcycle to deliver
DeliveryServiceA : IUnitOfWork { // deliver asap using motorcycle }
Module B uses Truck to deliver
DeliverServiceB : IUnitOfWork { // deliver as loaded as possible using truck }
and the consumer, let's say ISaleAppService, buys the service and now, let's say it is not a concern of the consumer which service being used, Service(Module) A or B..
If that is the case, you need another service with implementation detail to make that decision for the user, mediator.. IMediator.
Consumer request => IMediator determines which service to use => choose between Service A or B (Module A or B).
If consumer needs to choose which service (which module), then probably you can provide key to distinguish such as input argument arg1.
Consumer request with key(arg1 or enum) via IUnitOfWork => IUnitOfWork determines which implementation block to choose (Module A or Module B) to send request, based on the key (or enum).
Whichever you design, I think there needs to be intermediate step no matter how you abstract using IUnitOfWork because there is implementation done differently behind the scene.
I have a service that interacts with a brokerage account's API. It works fine, but now I need to interact with two different accounts at the same brokerage.
It seems like the best way to handle this is to make it possible to configure the service to specify the target account and then instantiate two different instances, one for each account.
I'm not sure if this is supported in Grails or how to go about it.
Two questions:
Is there a better way to do this?
If not, how can I instantiate and configure two different service instances?
ADDITIONAL INFORMATION:
Both answers are near misses. Let me try to clarify:
I didn't want to get into the details, but it may help to explain what I'm after. I'm using the Interactive Brokers trading API, and they don't let you talk directly to their servers the way other brokerages do. You have to talk over a socket to their IB Gateway, which is a piece of software they provide that essentially proxies their servers. So your app talks to IB Gateway, and IB Gateway talks to Interactive Brokers' servers on your app's behalf.
The catch is that IB Gateway has to be logged in to an account as part of its configuration. So, in order to trade two different accounts, you have no choice but to configure two different IB Gateways, since each can only access the account that it is configured for.
So my Grails code for placing trades must select the right IB Gateway to talk to. That means it needs to know the IP address and port of the IB Gateway that corresponds to each account. Other than this setting for IP address and port, there is no difference between the two Grails services that communicate with IB Gateway.
What I want is to reuse the same service class, each being instantiated as a singleton, simply having a different IP address and port on which to communicate.
So making two different services is undesirable, since the code is otherwise identical. (And if I add a third or fourth IB Gateway, this becomes fairly smelly code.)
And this setting should exist for the life of the application, so I don't think a change in scope is really the answer, either.
I really want two instances of the same service, simply having different configurations.
I hope that helps explain the situation. What do you suggest? Thank you!
If the same business logic is applicable for both accounts but taking into consideration that you cannot have a single service class talking to the API for both accounts, then yes you can have 2 service classes (which are nothing but 2 different spring beans) with the default singleton scope.
class Account1Service{
}
class Account2Service{
}
I would also try if I can use inheritance here in this case, if I have common logic that can be shared across. But keep in mind, if you are inheriting a service class from an abstract class then the abstract class has to be placed in src/groovy that is, outside /grails-app/ to defy Dependency Injection. In that case you might end up with (untested, but you can adhere to DRY concept)
// src/groovy
abstract class BrokerageService {
def populateAccountDetails(Long accountId)
def checkAccountStatus(Long accountId)
}
//grails-app/services
class Account1Service extends BrokerageService {
//Implement methods + add logic particular to Account1
//By default transacitonal
}
class Account2Service extends BrokerageService {
//Implement methods + add logic particular to Account2
//By default transacitonal
}
Also keep a note that the scope is singleton, you would take extra care (better avoid) maintaining global scoped properties in Service class. Try to make as stateless as possible. Unless otherwise the situation or the business logic demands to use service level scopes like session, flow or request, I would always stick to the default singleton scope.
To answer your second question, you do not need to instantiate any of the grails service class. The container injects appropriate service class (using Spring IoC) when an appropriate nomenclature is used. In the above example, the service classes will automatically be injected if you follow this naming convention in classes where you wan tto use the services:
//camelCase lower initial
def account1Service
def account2Service
UPDATE
This is in response to the additional information provided by OP.
Referring to the above scenario, there can be only one service class in the default singleton scope to handle things perfectly. The best part, since you are going out of your network and not really worried about own database transactions the service class can be set to non-transactional. But again it depends on the situations need. Here is how the service class would look like.
//grails-app/service
class BrokerageService{
//Service method to be called from controller or any endpoint
def callServiceMethod(Long accountId){
.......
doSomethingCommonToAllAccounts()
.........
def _ibConfig = [:] << lookupIBGatewayConfigForAccount(accountId)
........
//Configure an IB Gateway according to the credentials
//Call IB Gateway for Account using data got from _ibConfig map
//Call goes here
}
def doSomethingCommonToAllAccounts(){
........
........
}
def lookupIBGatewayConfigForAccount(accountId){
def configMap = [:]
//Here lookup the required IP, account credentials for the provided account
//If required lookup from database, if you think the list of accounts would grow
//For example, if account is JPMorgan, get credentials related to JPMorgan
//put everything in map
configMap << [ip: "xxx.xx.xx.xxx", port: 80, userName: "Dummy"] //etc
return configMap
}
}
The scope of the service class is singleton which means there will be only one instance of the class in the heap, which also means that any class level property (other than methods) will be stateful. In this case, you only deal with methods which will be stateless and would suffice the purpose. You would get what you need without spending heap or without creating new instances of BrokerageService every time a trading happens.
Each trade (with an account assciated) will eventually call the service, lookup the credentials from db (or config properties, or flat files, or properties files) and subsequently configure the IB Gateway and call/talk to the gateway.
Grails services are supposed to be singletons by default, not having any state associated to what it is doing and usually only one instance. Namely, you wouldn't have instance fields in them, normally.
But if you override the default scope, you can have them. For example, you can make your service to be session scoped, adding this static variable:
static scope = "session"
Then you'll have one instance for each user session.
For your particular case, you may want to take a look at the prototype scope, which will give you a new instance of the service each time you need it injected. You just will have to make sure to always use that instance after it is injected, if you want them to act on the same data.
Take a look at the docs about Scoped Services.
This seems like a fundamental Web Services problem. However an elegant solution is elusive based on some research I have been able to do. I guess I am missing something here
I am using a WCF client to connect to a External web service of which I have no control. The external WS is java based. There are a bunch of assemblies which are provided to call the methods in web service. These assemblies have base classes and derived classes. The web service methods can take Base class as param whereas from the WCF Client I instantiate a Derived class and pass it to the method.
To simulate this scenario, I created a small project with one ClassLibrary which has a BaseClass and a DerivedClass with one method.
Then I create an asmx web service and add a HelloWorld method inside it. I add a reference to the ClassLibrary. This method takes a BaseClass type param.
Then I create a Service Reference to the ASMX web service. In the proxy class, I add a XmlSerializerFormatAttribute to the method if it is already not there.
From the WCF client, I call the ASMX web method
BaseClass bc = new Derived();
ServiceReference1.TestService ts = new WCFTest.ServiceReference1.TestService();
lbl1.Text = (c1.HelloWorld(bc));
The call fails with error
The type ClassLib.Derived was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
The only way I could call this web service method was by adding XmlInclude attribute to the BaseClass in the ClassLibrary.
In my scenario, this library is a dll provided by an external vendor. I cannot add attributes to its classes. I have looked a DataContractSerializer and KnownTypes and XmlSerializer ctor. However those solutions do not seem to be applicable in my scenario.
How can I make XMLSerializer see the Derived classes in the assemblies I have referencing in the WCF Client? Is there an elegant solution?
Thanks,
Hem
Including your own type mapping for an XmlSerializerOperationBehavior may just work, but I haven't tried this (see GetXmlMappings).
http://msdn.microsoft.com/en-us/library/system.servicemodel.description.xmlserializeroperationbehavior.aspx
Alternatively, forcing use of the DataContractSerializer via a DataContractSerializerOperationBehavior (as opposed to the XmlSerializerOperationBehavior it's using now) may work too, if you specify your own known types
http://msdn.microsoft.com/en-us/library/ms576751%28v=vs.85%29.aspx
Finally, as a last resort, you can force use of the DataContractSerializer using the DataContractSerializerOperationBehavior, then specify your own DataContractSurrogate to force use of the XmlSerializer where you can pass custom types to its constructor (which circumvents the requirement for the XmlInclude attribute).
http://msdn.microsoft.com/en-us/library/ms751540.aspx
Hope that helps.
In simple terms and/or in high-level pseudo-code, how does a DI container work and how is it used?
At its core a DI Container creates objects based on mappings between interfaces and concrete types.
This will allow you to request an abstract type from the container:
IFoo f = container.Resolve<IFoo>();
This requires that you have previously configured the container to map from IFoo to a concrete class that implements IFoo (for example Foo).
This in itself would not be particularly impressive, but DI Containers do more:
They use Auto-Wiring which means that they can automatically figure out that if IFoo maps to Foo and IBar maps to Bar, but Foo has a dependency on IBar, it will create a Foo instance with a Bar when you request IFoo.
They manage the lifetime of components. You many want a new instance of Foo every time, but in other cases you might want the same instance. You may even want new instances of Foo every time, but the injected Bar should remain the same instance.
Once you start trying to manually manage composition and lifetimes you should start appreciating the services provided by a DI Container :)
Many DI Containers can do much more than the above, but those are the core services. Most containers offer options for configuring via either code or XML.
When it comes to proper usage of containers, Krzysztof Kozmic just published a good overview.
"It's nothing more than a fancy hash
table of objects."
While the above is a massive understatement that's the easy way of thinking about them. Given the collection, if you ask for the same instance of an class - the DI container will decide whether to give you a cached version or a new one, or so on.
Their usage makes it easier and cleaner when it comes to wiring up dependencies. Imagine you have the following pseudo classes.
class House(Kitchen, Bedroom)
// Use kitchen and bedroom.
end
class Kitchen()
// Code...
end
class Bedroom()
// Code...
end
Constructing a house is a pain without a DI container, you would need to create an instance of a bedroom, followed by an instance of a kitchen. If those objects had dependencies too, you would need to wire them up. In turn, you can spend many lines of code just wiring up objects. Only then could you create a valid house. Using a DI/IOC (Inversion of Control) container you say you want a house object, the DI container will recursively create each of its dependencies and return you a house.
Without DI/IOC Container:
house = new House(new Kitchen(), new Bedroom());
With DI/IOC Container:
house = // some method of getting the house
At the end of the day they make code easy to follow, easier to write and shift the responsibility of wiring objects together away from the problem at hand.
You configure a DI container so it knows about your interfaces and types - how each interface maps to a type.
When you call Resolve on it, it looks at the mapping and returns the mapped object you have requested.
Some DI containers use conventions over configuration, where for example, if you define an interface ISomething, it will look for a concrete Something type to instantiate and return.