How to setup camel context and registry within java - apache-camel

I am creating a stand alone camel application. I want to use only java (because the compiler tells whats wrong).
To make my code less coupled and reusable by tests i want to decouple the creation of context and registry to separate classes.
I just started to extend DefaultCamelContext - is this a good idea or should i extend/implement some other class?
Within this class i want to use my own registry (it binds some bean instances) class. I found method setRegistry(org.apache.camel.spi.Registry).
But how to implement such an registry? Is there also a "defaultRegistry"? (for tests there is an createRegistry(), is there something for outside the tests?)
At the end i want to use dependency injection (guice) to glue all stuff together: the registry will inject bean-instances, the registry is then injected in context and context is injected in my main-class than creates "main", sets context and "run()"s it.

Camel supports a pluggable registry strategy...so you should be able to implement the org.apache.camel.spi.Registry interface and call setRegistry(myImpl)...
there are several (Simple, Jndi, etc) registries that are supported that might meet your needs or serve as an example...
for example, here is the SimpleRegistry implementation class...
https://git-wip-us.apache.org/repos/asf?p=camel.git;a=blob_plain;f=camel-core/src/main/java/org/apache/camel/impl/SimpleRegistry.java;h=d2a4a21c9f9fbc70f45fd485d1c46c8a20b9afea;hb=HEAD

Related

Easymock with #TestSubject enhanced with CGLIB

Is there a way to make EasyMock's #TestSubject annottation to work when the test subject object is enhanced with CGLIB?
Scenario: the #TestSubject object is a Spring bean which was enhanced with CGLIB in order to apply some aspect (assuming that for some reason Spring couldn't use JDK-based proxy). In this case, simply using #TestSubject and EasyMockSupport.injectMocks(this) does not really work. EasyMock injects the mock, however during execution the mock is not actually used due to how the internals of a CGLIB enhanced class work. In the end it is used the original reference the object had, not the mock.
The only approach I know is to create a setter in the test subject, and to inject the mock manually calling the setter. However sometimes I do not have access/permission/time to change the subject code to include the setter.
cglib classes are always final what prevents the creation of another proxy. This is therefore not possible to do. Rather, you would need to discover that a class is a cglib proxy already and rather enhance its base class.

#Singleton vs #ApplicationScope

For a project I need to have a unique ID generator. So I thought about a Singleton with synchronized methods.
Since a Singleton following the traditional Singleton pattern (private static instance) is shared accross Sessions, I'm wondering if the #Singleton Annotation is working the same way?
The documentation says: Identifies a type that the injector only instantiates once.
Does it mean, that a #Singleton will be independent per User Session (which is bad for an id-generator)? Should I prefer an old school Singleton with Class.getInstance() over an Injection of an #Singleton-Bean?
Or should I use neither nor and provide the Service within an #ApplicationScoped bean?
it musst be guaranteed that only ONE thread, independent of the user session can access the method to generate the next id. (It's not solvable with auto-increment database ids)
Edit: JSF 2.2, CDI and javax.inject.* i'm talking about :)
All those kinds of singletons (static, #javax.inject.Singleton, #javax.ejb.Singleton and #javax.enterprise.context.ApplicationScoped) are created once per JVM.
An object that is created once per user session must be annotated with #javax.enterprise.context.SessionScoped so no, singletons will not be instantiated per user session.
Notice that there are two #Singleton annotations, one in javax.inject and the other in the javax.ejb package. I'm referring to them by their fully-qualified names to avoid confusion.
The differences between all those singletons are subtle and I'm not sure I know all the implications, but a few come to mind:
#javax.ejb.Singleton is managed by the EJB container and so it can handle transactions (#javax.ejb.TransactionAttribute), read/write locking and time-outs (#javax.ejb.Lock, #javax.ejb.AccessTimeout), application startup (#javax.ejb.Startup, #javax.ejb.DependsOn) and so on.
#javax.enterprise.context.ApplicationScoped is managed by the CDI container, so you won't have the transaction and locking features that EJB has (unless you use a post-1.0 CDI that has added transactions), but you still have lots of nice things such as #javax.enterprise.inject.Produces, #javax.annotation.PostConstruct, #javax.inject.Named, #javax.enterprise.inject.Disposes (but many of these features are available to EJBs too).
#javax.inject.Singleton is similar to #ApplicationScoped, except that there is no proxy object (clients will have a reference to the object directly). There will be less indirection to reach the real object, but this might cause some issues related to serialization (see this: http://docs.jboss.org/weld/reference/latest-2.2/en-US/html_single/#_the_singleton_pseudo_scope)
A plain static field is simple and just works, but it's controlled by the class loader so in order to understand how/when they are instantiated and garbage collected (if ever), you will need to understand how class loaders work and how your application server manages its class loaders (when restarting, redeploying, etc.). See this question for more details.
javax.inject.Singleton - When used on your bean, you have to implement writeResolve() and readReplace to avoid any serialization issues. Use it judiciously based on what your bean actually has in it.
javax.enterprise.context.ApplicationScoped - Allows the container to proxy the bean and take care of serialization process automatically. This is recommended to avoid unprecedented issues.
For More information refer this page number 45.

What is the correct way to solve the ambiguous reference issue in WCF services?

Project Structure
I have a silverlight project SLProj, that references a silverlight class library project called ServiceClients. ServiceClients has two wcf service references, Svc1.svc and Svc2.svc. Both Svc1.svc and Svc2.svc are in two different WCF projects which use the same set of DataContracts which are again in a different class library project called MyDataContracts.dll.
Problem description
Now in my ServiceClients project I get an ambiguous reference issue when I need to use a datacontract class which is present in both the service references. If this were a winforms or webforms project, I could reference the MyDataContracts.dll and reuse the common types. But since, this MyDataContracts.dll was built using a non silverlight class library, it can't be referenced in the silverlight project
Workaround...
I am not sure if this below is the best method to go about taking care of this issue. Can anybody let me know if there is a cleaner way to solve this problem, or is this the best way we have so far?
create a single service reference.
click the 'show all files' button in the solution explorer
drill into the service reference and find Reference.svcmap and open it
find the MetadataSources section
add a second line to include the address to your second service. for example:
MetadataSource Address="http://address1.svc" Protocol="http" SourceId="1"
MetadataSource Address="http://address2.svc" Protocol="http" SourceId="2"
save, close, and update service reference.
Use Automapper
Map the DataContracts with AutoMapper.
You will have to invest some time in understanding AutoMapper and reworking your application. Also AutoMapper adds overhead because all data objects will be mapped. But first you will have a clean solution without hacks and second you gain a decoupled and simple data object layer just for your client. Once done you can forget the mapping but you stay flexible for future changes.
If you never have worked with Automapper it's important to play around with it before starting. Automapper is special and needs some time to familiarise with it.
So there. These are the rough steps:
1. Create a subdirectory and sub-namespace Data and copy the DataContracts. Remove the attributes and properties your client doesn't need because these mapped classes live only in your client. You can also change some types or flatten some complex properties.
2. Create an AutoMapperInit.cs like described at Automapper (read the Getting Started Guide). Use the conflicting references like this:
using ref1 = YourProjectServiceReference1;
using ref2 = YourProjectServiceReference2;
3. Wrap the service client like this:
Example GetExample() {
return AutoMapper.Map<ref1.Example, Example>(ref1.YourService.GetExample());
}
The wrapper also needs the same using directives as in step 2.
4. In this wrapper add a static initializer like this (assuming your wrapper class is called Wrapper):
static Wrapper() {
AutoMapperInit.CreateMaps();
}
5. Omit service references in the client and use using YourClient.Data;, the namespace you created in step 1.
Your client is now decoupled from the service and you don't have conflicts anymore.
Disclaimer: I am not affiliated with AutoMapper. I just used it in a project with a similar problem and am happy with it and wanted to share my experience.
Your workaround is actually quite OK. We've used it in several projects like this with 3 service references. It is actually a workaround for the IDE which for some reason only allows to select one service to create a service reference at a time.
Another thing you could try-out is to multi-target your shared contract to .NET and Silverlight, using the same codebase. Details on how to do such thing is described in http://10rem.net/blog/2009/07/13/sharing-entities-between-wcf-and-silverlight. Might be more work but feel less hacky.

Generate Silverlight service proxies with same namespace

I need to generate service proxies for multiple WCF services within the same namespace, which is not possible when using the Add Service Reference function of Visual Studio.
How can I do this in an automated way? I've considered using SLsvcUtil, but that would require that I make sure that I have my WCF services accessible, and, assuming I'm using the ASP.NET Development Server, I'd need to manually check the URL.
Ideally, I'd have some way of specifying an assembly, a service type, the configuration (web|app.config) and a target namespace, and then my code would be generated. Any Ideas?
Edit
To clarify, I'm trying to solve the same problem that is outlined in this connect issue:
http://connect.microsoft.com/VisualStudio/feedback/details/426791/adding-multiple-service-references-from-same-application-should-not-require-multiple-namespaces
I want a no-hassle, automated way to generate service proxies within a single namespace. It's unacceptable for me to have to specify a unique namespace for each service reference. Using SLsvcUtil is an option, but it requires that I have my service up-and-running so it can read the metadata - which is a problem because I don't always have the latest version of the service running at any given point in time.
The "Add Service Reference" functionality in VS handles this well - it automatically hosts the service just long enough to grab the metadata, and then generates the service contract interfaces and proxies. Once again, it requires that each service be code-gen'd in its own, unique namespace, which I don't want.
All I need is a way to generate the service proxies with a single, shared namespace, without having to go through the hassle of manually hosting and firing up an instance of my services. Ideally, I'd just double click a script file.
What I normally do is to inform a composite namespace. When the "Add Service Reference" dialog pops up, I put in the namespace something like Services.ServiceA or Services.ServiceB. Then all service namespaces share the common root Services.*.
If I'm understanding the question correctly, you're concerned because the way Add Service Reference functions, the ServiceContract interfaces are not exactly the same as the ones you define in your source assembly.
The only real difference is that the ServiceContract interface that Add Service Reference generates for SL has asynchronous operations defined (since SL doesn't support synchronous WCF calls). The rest of it (the XXXClient : ClientBase class) can be completely bypassed if you just use the ChannelFactory<TServiceContractInterface> directly.
I personally ended up sharing the synchronous ServiceContract interface, but creating a service contract with asynchronous operations using a System.Reflection.Emit.TypeBuilder. Then using a custom ChannelFactory, I created a wrapper around the dynamically generated asynchronous ServiceContract interface.
I hope that helps.

Application Variable in WPF While Maintaining Testability

I am working on a WPF application, using the MVVM Pattern.
Each ViewModel will need access to a security object, that essentially provides information about the rights the user has. Because this object only needs to be populated once at start up, and because populating it is (at least potentially) expensive, I want to keep it in state for the lifetime of the application.
I can make it a static variable in App, which would make it available to the whole application (at least that's my understanding). This would make my ViewModel implementations very difficult to test, since the App.SecurityObject call would be inline in each ViewModel. I would have to make sure App was available for each test and mock the App.SecurityObject call (I'm not even sure this would work, actually).
We are using StructureMap, so I could create a SecurityObjectProvider and configure a it with a Singleton lifecycle in the container, and simply make it part of every ViewModel constructor. The downside would be that (as I said) the provider would have to be part of every View Model constructor.
There are other, hacky workarounds I can think of, but they would involve creating methods (perhaps in the View Model base class) that would allow injecting the security object after instantiation for testing purpose only. I usually try to avoid this kind "for testing only" code.
It seems like this would be a common problem , but I can't find any SO questions that are completely on point.
Security concerns are often best adressed by Thread.CurrentPrincipal. If it's at all possible to fit your security concerns into that model (calling Principal.IsInRole and so on) that is by far the desirable solution.
It's pretty easy to unit test because you just need to set Thread.CurrentPrincipal before invoking the SUT and then make sure you revert it to its original value in the Fixture Teardown phase.
If Thread.CurrentPrincipal doesn't suit your need, I would suggest either an injected dependency or a Decorator that handles security. Security is often a Cross-Cutting Concern, so it is often preferable to handle it as declaratively as possible. In other words, if you can model it by Guards and Assertions, you don't need to actively call it, and you would be able to use a more AOP-like approach (such as a Decorator).
If that's not possible either, you can model it as an Ambient Context. This may look a bit like the Service Locator anti-pattern, but the difference is that it's strongly typed and has a Local Default that ensures that it never throws NullReferenceExceptions or their like because it protects its invariants.
The service locator pattern might help you out. You still implement the functionality as a service, but you have your VMs go through a static class to obtain the service, rather than have it injected:
var securityService = ServiceLocator.Resolve<ISecurityService>();
When running unit tests, you can configure your service locator to return mocks/stubs.
I think I would use some kind of Service Locator to get object. And in tests I would mock it out.

Resources