#Singleton vs #ApplicationScope - static

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.

Related

How to setup camel context and registry within java

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

Storing user data for a C-based Native Client instance

I have been working on C-based Native Client module for Google Chrome. Many of the module functions that are called by the NaCl system have a parameter of PP_Instance which uniquely identifies the module instance.
My question: Is there any way to associate user data with this instance handle?
The C API specifies that it is an opaque handle. It provides no functions for linking user data to the handle. Right now, I have to use a bunch of global variables within the module to share state among the functions. It doesn't feel like the right solution. I'm not sure if more than one instance will ever share the process space but I'm not making any assumptions here.
I suppose I could implement some sort of look up table to map instances to unique contexts that happen to live in the global scope. But that also seems like it should be unnecessary for a C-based API. The C++ API avoids this by virtue of its classes.
PP_Instance should be used as a key to lookup state / object associated with the plugin instance. More than one plugin instance may be instantiated in a module as per the API, when, for example, multiple embed tags are present in the containing frame. Currently the NaCl implementation of Pepper does not do this -- instead, multiple processes each containing a single module each instantiating a single pepper plugin instance is created. However, this is an implementation detail (or maybe bug?) that is subject to change, and it would be better to defensively program and be able to handle multiple DidCreate events.
Of course, if your NaCl module is guaranteed to never be used by anyone else and you know you won't ever have two embeds of the same module, then it might be okay to assume singleton instance and use global state, but doing things the "right" way isn't that hard, so why not?
See native-client-discuss thread for more discussion on this topic.

How does the Composite C1 architecture work?

Can anyone give a high level description of what is going on in the Composite C1 core? In particular I am interested in knowing how the plugin architecture works and what the core components are of the system i.e. when a request arrives what is happening in the architecture. The description doesn't have to be too verbose just a list of steps and the classes involved.
Hopefully one of the core development team would enlighten me... and maybe publish some more API (hint hint more class documentation please).
From request to rendered page
The concrete path a request takes depends on the version of C1 you're using, since it was changed to use Routing in version 2.1.2. So lets see
< 2.1.2
Composite.Core.WebClient.Renderings.RequestInterceptorHttpModule will intercept all incoming requests and figure out if the requested path correspond to a valid C1 page. If it does, the url will be rewritten to the C1 page handler ~/Rendererings/Page.aspx
2.1.1
Composite.Core.Routing.Routes.Register() adds a C1 page route (Composite.Core.Routing.Pages.C1PageRoute) to the Routes-collection that looks at the incoming path, figures out if its a valid C1 page. If it is, it returns an instance of ~/Rendererings/Page.aspx ready to be executed.
Okay, so now we have an instance of a IHttpHandler ready to make up the page to be returned to the client. The actual code for the IHttpHandler is easy to see since its located in ~/Renderers/Page.aspx.cs.
OnPreInit
Here we're figuring out which Page Id and which language that was requested and looking at whether we're in preview mode or not, which datascope etc.
OnInit
Now we're fetching the content from each Content Placeholder of our page, and excuting its functions it may contain. Its done by calling Composite.Core.WebClient.Renderings.Page.PageRenderer.Render passing the current page and our placeholders. Internally it will call the method ExecuteFunctions which will run through the content and recursively resolve C1 function elements (<f:function />), execute them and replace the element with the functions output. This will be done until there are no more function elements in the content in case functions them selves output other functions.
Now the whole content is wrapped in a Asp.Net WebForms control, and inserted into our WebForms page. Since C1 functions can return WebForms controls like UserControl etc., this is necessary for them to work correctly and trigger the Event Lifecycle of WebForms.
And, that's basically it. Rendering of a requested page is very simple and very extendable. For instance is there an extension that enables the usage of MasterPages which simply hooks into this rendering flow very elegantly. And because we're using Routing to map which handler to use, its also possible to forget about ~/Rendering/Page.aspx and just return a MvcHandler if your a Mvc fanatic.
API
Now, when it comes to the more core API's there are many, depending on what you want to do. But you can be pretty sure, no matter what there is the necessary ones to get the job done.
At the deep end we have the Data Layer which most other API's and facades are centered around. This means you can do most things working with the raw data, instead of going through facades all the time. This is possible since most configuration of C1 is done by using its own data layer to store configuration.
The Composite C1 core group have yet to validate/refactor and document all the API's in the system and hence operate with the concept of 'a public API' and what can become an API when the demand is there. The latter is a pretty darn stable API, but without guarantees.
The public API documentation is online at http://api.composite.net/
Functions
Functions is a fundamental part of C1 and is a technique to abstract logic from execution. Basically everything that either performs a action or returns some data/string/values can be candidates for functions. At the lowest level a function is a .Net class implementing the IFunction interface, but luckily there are many easier ways to work with it. Out of the box C1 supports functions defined as XSLT templates, C# methods or Sql. There are also community support for writing functions using Razor or having ASP.Net UserControls (.ascx files) to be functions.
Since all functions are registered in C1 during system startup, we use the Composite.Functions.FunctionFacade to execute whatever function we know the name of. Use the GetFunction to get a reference to a function, and then Execute to execute it and get a return value. Functions can take parameters which are passed as real .Net objects when executing a function. There is also full support for calling functions with Xml markup using the <f:function /> element, meaning that editors, designers, template makers etc. easily can access a wealth of functionality without having to know how to write .Net code.
Read more about functions here http://users.composite.net/C1/Functions.aspx and how to use ie Razor to make functions here http://docs.composite.net/C1/ASP-NET/Razor-Functions.aspx
Globalization and Localization
C1 has full multi-language support in the core. Composite.Core.Localization.LocalizationFacade is used for managing the installed locales in the system; querying, adding and removing. Locales can be whatever CultureInfo object is known by your system.
Composite.Core.ResourceSystem.StringResourceSystemFacade is used for getting strings at runtime that matches the CultureInfo your request is running in. Use this, instead of hardcoding strings on your pages or in your templates.
Read more about Localization here http://docs.composite.net/C1/HTML/C1-Localization.aspx
Global events
Composite.C1Console.Events.GlobalEventSystemFacade is important to know if you need to keep track on when the system is shutting down so you can make last-minute changes. Since C1 is highly multithreaded its easy to write extensions and modules for C1 that are multithreaded as well, taking advantage of multi core systems and parallelization and therefor its also crucial to shut down ones threads in a proper manner. The GlobalEventSystemFacade helps you do that.
Startup events
If you write plug-ins these can have a custom factory. Other code can use the ApplicationStartupAttribute attribute to get called by the Composite C1 core when the web app start up.
Data events
You can subscribe to data add, edit and delete events (pre and post) using the static methods on Composite.Data.DataEvents<T>. To attach to these events when the system start up, use the ApplicationStartupAttribute attribute.
Data
Composite.Core.Threading.ThreadDataManager is important if your accessing the Data Layer outside of a corresponding C1 Page request. This could be a custom handler that just has to feed all newest news as a Rss feed, or your maybe writing a console application. In these cases, always remember to wrap your code that accesses the data like this
using(Composite.Core.Threading.ThreadDataManager.EnsureInitialize())
{
// Code that works with C1 data layer goes here
}
For accessing and manipulating data its recommended NOT to use the DataFacade class, but wrap all code that gets or updates or deletes or adds data like this
using(var data = new DataConnection())
{
// Do things with data
}
IO
When working with files and directories its important to use the C1 equivalent classes Composite.Core.IO.C1File and Composite.Core.IO.C1Directory to .Net's File and Directory. This is due to the nature where C1 can be hosted on Azure, where you might not have access to the filesystem in the same way as you have on a normal Windows Server. By using the C1's File and Directory wrappers you can be sure that code you write will be able to run on Azure as well.
C1 Console
The console is a whole subject on itself and has many many API's.
You can create your own trees using Composite.C1Console.Trees.TreeFacade or Composite.C1Console.Elements.ElementFacade and implementing a Composite.C1Console.Elements.Plugins.ElementProvider.IElementProvider.
You can use the Composite.C1Console.Events.ConsoleMessageQueueFacade to send messages from the server to the client to make it do things like open a message box, refreshing a tree, set focus on a specific element, open a new tab etc. etc.
Composite.C1Console.Workflow.WorkflowFacade is used for getting instances of specific workflows and interacting with them. Workflows is a very fundamental part of C1 and is the way multi-step operations are defined and executed. This makes it possible to save state of operation so ie. a 10 step wizard is persisted even if the server restarts or anything else unexpected happens. Workflows are build using Windows Workflow Foundation, so are you familiar with this, you should be feeling at home
There is also a wealth of javascript facades and methods you can hook into when writing extensions to the Console. Much more than i could ever cover here so i will refrain myself from even getting started on that subject here.
composite.config
A fundamental part of C1 is providers, almost everything is made up of providers, even much of the core functionality. Everything in the console from Perspectives to Trees and elements and actions are feeded into C1 with providers. All the standard functions, the datalayer and all the widgets for use with the Function Call editor is feeded into C1 with providers. All the localisation strings for use with the Resources, users and permissions, url formatters etc. is all providers.
Composite.Data.Plugins.DataProviderConfiguration
Here all providers that can respond to the methods on DataFacade, Get, Update, Delete, Add etc. are registered. Every provider informs the system which interfaces it can interact with and C1 makes sure to route all requests for specific interfaces to their respective dataproviders.
Composite.C1Console.Elements.Plugins.ElementProviderConfiguration
Here we're defining the perspectives and the trees inside the Console. All the standard perspectives you see when you start the Console the first time are configured here, no magic or black box involved.
Composite.C1Console.Elements.Plugins.ElementActionProviderConfiguration
Action providers are able to add new menuitems to all elements in the system, based on their EntityToken. This is very powerful when you want to add new functionality to existing content like versioning, extranet security, custom cut/paste and the list goes on.
Composite.C1Console.Security.Plugins.LoginProviderConfiguration
A LoginProvider is what the C1 console will use to authenticate a user and let you log in or not. Unfortunately this isn't very open but with some reflection you should be all set.
Composite.Functions.Plugins.FunctionProviderConfiguration
Composite C1 will use all the registered FunctionProviders to populate its internal list of functions on system startup.
Composite.Functions.Plugins.WidgetFunctionProviderConfiguration
WidgetProviders are used in things like the Function Call Editor or in Forms Markup to render custom UI for selecting data.
Composite.Functions.Plugins.XslExtensionsProviderConfiguration
Custom extensions for use in XSLT templates are registered here
And then we have a few sections for pure configuration, like caching or what to to parallelize but its not as interesting as the providers.
Defining and using sections
Sections in composite.config, and other related .config files are completely standard .Net configuration and obeys the rules thereof. That means that to be able to use a custom element, like ie. Composite.Functions.Plugins.WidgetFunctionProviderConfiguration it has to be defined as a section. A section has a name and refers to a type that would inherit from System.Configuration.ConfigurationSection. Composite uses the Microsoft Enterprise Libraries for handling most of these common things like configuration and logging and validation and therefor all Composites sections inherit from Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SerializableConfigurationSection. Now, this type just has to have properties for all the elements we want to be able to define in the .config-file, and .Net will automatically make sure to wire things up for us.
If you want to access configuration for a particular section you would call Composite.Core.Configuration.ConfigurationServices.ConfigurationSource.GetSection(".. section name") and cast it to your specific type and your good to go.
Adding extra properties to already defined sections
Normally .Net would complain if you write elements or attributes in the .config files that aren't recognized by the type responsible for the section or for the element. This makes it hard to write a truly flexible module-system where external authors can add specific configuration options to their providers, and therefor we have the notion of a Assembler. Its a ConfigurationElement class with a Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.AssemblerAttribute attribute assigned to it that in turns takes a Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.IAssembler interface as argument that is responsible for getting these custom attributes and values from the element in the .config file and emit usable object from it. This way .Net won't complain about an invalid .config file, since we inject a ConfigurationElement object that has properties for all our custom attributes, and we can get hold of them when reading the configuration through the IAssembler
Slides
Some overview slides can be found on these lins
Overview
Extensibility points
Page request handling
Function system
Data system
Data type system
Inspiration and examples
The C1Contrib project on GitHub is a very good introduction how to interact with the different parts of C1. Its a collection of small packages, that can be used as it is, or for inspiration. There are packages that manipulates with dynamic types to enable interface inheritance. Other packages uses the javascript api in the console, while others show how to make Function Providers, Trees and hook commands unto existing elements. There is even examples of how to manipulate with the Soap webservice communication going on between client and server so you can make it do things the way you want it. And the list goes on.

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