#Stateless bean accessing data of #Singleton's bean in EJB3 - singleton

I am new to EJB3.1 .Please bear with me if this is a trivial question. My requirement is to have a singleton class which will have certain data shared across
different beans. And to have different Threads accessing this singleton class's data . Let me try to explain using two different class called A and B .
#Singleton
//#Local?? ,#Remote?? or #LocalBean ?
class A {
private List<CommonDTO> commonDTOList = new ArrayList<CommonDTO>();
.
. //other member variables, EJB beans which implement Remote interfaces.
.
init(){
//initialise commonDTOList here.
}
//getter
List<SomeDTO> getCommonDTOList(){
return commonDTOList;
}
}
#Stateless
Class B implements Interface { //Interface is #Remote
//need to access singleton Class A's getter , so that all the threads have the same commonDTOList.
#EJB
private A classA;
.
.//other member variables
.
#OverRide //overriding Interface2's method
public void doSomething(){
.
.//do some database transactions here , which can be done parallely by multiple threads, since this is stateless.
.
//now retrieve Class A'S CommonDTOList.
//This List should be shared across multiple threads of this stateless bean.
List<SomeDTO> someDTOListInsideStatelessBean = classA.getCommonDTOList();
}
}
Question is what annotation I should on ClassA so that I can access its List in another Stateless bean.?
I have tried the following but in vain.
1) #Local I cannot use because like mentioned in the inline comments above .In classA that member variables has #EJB beans which implement #Remote interfaces.
2) #LocalBean looks to be the one used here in this scenario. However , once inside the method "doSomething()" of ClassB, the classA variable has all its
member variable as null .Although the List was initialised during start up.
I was under the impression that since its singleton , there will be only instance shared
across all beans.
3)#Remote I am not sure if I should be using here , however no luck with that too.
please help. Thanks in advance.

I have got the answer. The Class A can be annotated with just "Singleton" and Class B(Stateless) can access its methods just fine without any issue.You dont have to provide any view for Class A. By default it will be no-interface view. Below is the link which helped me understand.
EJB 3.1 #LocalBean vs no annotation

Related

Role of private & non-private initializers in (Dart) private & non-private class constructors?

I'm new to OOP currently with intermediate level of understanding. I'm constantly gaining ground by learning Dart and C#. I'm also exploring the design patterns to really understand how it all clicks together based on different scenarios. As for now I'm trying to make sense of following 4 scenarios related to class constructors. I understand the implications of underscore at constructor level and at initializer level. But I am looking for something that may seem quite obvious and clear to experienced programmers out there. Please share your valuable insights as I don't know what I'm missing here.
Scenario 1: Private Constructor with no initializer
I know this is different from Singleton. Singleton allows single instantiation, this below does not even once. Is there something more to it?
Real World Example:
class Firebase {
// Ensures end-users cannot initialize the class.
Firebase._();
...
}
Scenario 2: Private Constructor with optional public or non-private initializer
What's the use of this type of private constructor that has non-private initializer (this.app)? Why have a non-private initializer (this.app) in a private constructor? What is achieved through this?
Real World Example:
class FirebaseAuth extends FirebasePluginPlatform {
/// The [FirebaseApp] for this current Auth instance.
FirebaseApp app;
FirebaseAuth._({required this.app})
: super(app.name, 'plugins.flutter.io/firebase_auth');
/// Returns an instance using the default [FirebaseApp].
static FirebaseAuth get instance {
FirebaseApp defaultAppInstance = Firebase.app();
return FirebaseAuth.instanceFor(app: defaultAppInstance);
}
...
}
Scenario 3: public Constructor with private initializer
Why have a private property in a non-private constructor? What is achieved through this?
Fictitious Example:
class Constructify {
Map<String,dynamic> _property;
Constructify(this._property);
...
}
Scenario 4: Private Constructor with private initializer
Why have a private initializer at all when the constructor itself is private? What is achieved through this?
Real World Example:
class FirebaseApp {
/// A [FirebaseApp] instance can only be accessed from a call to `app()` [FirebaseCore].
///
/// This constructor ensures that the delegate instance it is constructed with is one which extends [FirebaseAppPlatform].
FirebaseApp._(this._delegate) {
FirebaseAppPlatform.verifyExtends(_delegate);
}
final FirebaseAppPlatform _delegate;
...
}
Scenario 1: _ in Dart means the variable/method/function/constructor is package private. So as long as we are inside the same package, we are allowed to use the field. So in Scenario 1 this actually means we can only create Firebase objects if we call the constructor from the package where Firebase has been declared. This will also prevent you from extending the class in another package since we cannot call the constructor on the Firebase class we are extending from.
Scenario 2: The package private constructor ensures that objects can only be created by code from the same package. The named app parameter is marked required so it is not optional. After the object has been created, you can in this case change the app variable. I don't know if this makes sense in this scenario but you can do it. I would properly in most cases mark app as final.
Scenario 3: The private field can be set to a value using the constructor but since the field is package private, we can ensure nobody outside our package can access the field afterwards.
Scenario 4: A package private constructor is used by some other code in the same package. If you want to ensure only your own package are allowed to create new objects of FirebaseApp and don't want code outside your package to get access to the field _delegate, you can do what this example does.

Controlling lifetime of objects created by factory generated by ToFactory()

I am using the following Ninject related nuget packages in an MVC 5 WebAPI application:
Ninject.MVC5
Ninject.Extensions.Factory
ninject.extensions.conventions
I have a simple repository and a corresponding factory class like so:
public interface ITaskRunner
{
void Run();
}
public interface IRepository<T> where T: class
{
T[] GetAll();
}
public interface IRepositoryFactory<T> where T: class
{
IRepository<T> CreateRepository();
}
I have setup the Ninject bindings using ToFactory() from Ninject.Extensions.Factory like so:
kernel.Bind<ITaskRunner>().To<TaskRunner>().InSingletonScope();
kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
kernel.Bind<IRepositoryFactory<Contact>>().ToFactory();
I am using the factory in the following class:
public class TaskRunner : ITaskRunner
{
//MyTask is a simple POCO class(not shown for brevity)
IRepositoryFactory<MyTask> repoFactory = null;
IRepository<MyTask> repo = null;
public TaskRunner(IRepositoryFactory<MyTask> repoFactory)
{
this.repoFactory = repoFactory;
repo = repoFactory.CreateRepository();
}
//implementation elided
}
I am noticing that the call to repoFactory.CreateRepository() always returns the same instance of the factory (dynamic proxy) that Ninject generates.
Question : Is there a way to change/control this behavior and set a "lifetime" such as Transient, PerThread etc. for the instance that "CreateRepository" returns?
In this particular case, tasks might be processed asynchronously on multiple threads and the repository is not thread safe and hence singleton behavior for the instance returned from "CreateRepository" is not desirable.
I'm not sure what you are trying to achieve, but results you are seeing are quite expected because your TaskRunner is bound as Singleton (so constructed once), and you retrieve your repository in the TaskRunner constructor, which again happens once, and so repo is always the same instance. Note this happens regardless of how you bind IRepository and IRepositoryFactory, see Captive Dependency post by Mark Seemann for details http://blog.ploeh.dk/2014/06/02/captive-dependency/.
In fact, if you need to create repo in the constructor, you could just inject IRepository itself. The power of the Factory extension lies in the fact that it allows to resolve instances at runtime, not construction time. For example, if your TaskRunner has Run() method, you can create repository in it, so each task to run can have its own instance.

c# how to select test or prod class from config file

I have built a cloud project for a month. My problem is that:
I have 2 classes to connect with Ibm web service. First class is the main class and the second one is test class. I put a key-value to appSetting in Config File.
If value in configFile is "TEST", the project will use test class and if value is the "PROD", the project will use main class. When I change the value in config, I will not change everywhere.
My Manager gave me advice to use "interface" but I didn't understand.
How can I solve this problem basiclly?
Both your test class and prod class could implement the said interface. If you need to use the approach where you do the selection in the config file of which class to use you are probably better off creating a data factory class that returns the correct implementation of the interface. The data factory reads the config file and depending on the value in app settings returns the correct class that implements the interface.
Example of doing this in C# (the concept is the same in other oo languages as well):
From the calling class:
SomethingFactory factory = new SomethingFactory();
ISomething testOrProdObj = factory.GetCorrectImplementation();
var result = testOrProdObj.MyMethod();
And in the factory class:
public class SomethingFactory
{
public ISomething GetCorrectImplementation()
{
//Do a check in appsettings to decide which class (TESTSomething or PRODSomething) to instantiate and return
}
}
Implementation of the interface
public class TESTSomething : ISomething
or
public class PRODSomething : ISomething

Dozer BeanFactory: How to implement it?

I have looked at the Dozer's FAQs and docs, including the SourceForge forum, but I didn't see any good tutorial or even a simple example on how to implement a custom BeanFactory.
Everyone says, "Just implement a BeanFactory". How exactly do you implement it?
I've Googled and all I see are just jars and sources of jars.
Here is one of my BeanFactories, I hope it helps to explain the common pattern:
public class LineBeanFactory implements BeanFactory {
#Override
public Object createBean(final Object source, final Class<?> sourceClass, final String targetBeanId) {
final LineDto dto = (LineDto) source;
return new Line(dto.getCode(), dto.getElectrified(), dto.getName());
}
}
And the corresponding XML mapping:
<mapping>
<class-a bean-factory="com.floyd.nav.web.ws.mapping.dozer.LineBeanFactory">com.floyd.nav.core.model.Line</class-a>
<class-b>com.floyd.nav.web.contract.dto.LineDto</class-b>
</mapping>
This way I declare that when a new instance of Line is needed then it should create it with my BeanFactory. Here is a unit test, that can explain it:
#Test
public void Line_is_created_with_three_arg_constructor_from_LineDto() {
final LineDto dto = createTransientLineDto();
final Line line = (Line) this.lineBeanFactory.createBean(dto, LineDto.class, null);
assertEquals(dto.getCode(), line.getCode());
assertEquals(dto.getElectrified(), line.isElectrified());
assertEquals(dto.getName(), line.getName());
}
So Object source is the source bean that is mapped, Class sourceClass is the class of the source bean (I'm ignoring it, 'cause it will always be a LineDto instance). String targetBeanId is the ID of the destination bean (too ignored).
A custom bean factory is a class that has a method that creates a bean. There are two "flavours"
a) static create method
SomeBean x = SomeBeanFactory.createSomeBean();
b) instance create method
SomeBeanFactory sbf = new SomeBeanFactory();
SomeBean x = sbf.createSomeBean();
You would create a bean factory if creating and setting up your bean requires some tricky logic, like for example initial value of certain properties depend on external configuration file. A bean factory class allows you to centralize "knowledge" about how to create such a tricky bean. Other classes just call create method without worying how to correctly create such bean.
Here is an actual implementation. Obviously it does not make a lot of sense, since Dozer would do the same without the BeanFactory, but instead of just returning an object, you could initialized it somehow differently.
public class ComponentBeanFactory implements BeanFactory {
#Override
public Object createBean(Object source, Class<?> sourceClass,
String targetBeanId) {
return new ComponentDto();
}
}
Why do you need a BeanFactory anyways? Maybe that would help understanding your question.

"Unable to convert ejbRef for ejb" on CDI (Weld) injection of #Stateless EJB into #SessionScoped JSF2 bean in Glassfish

[UPDATE: After discussion on the Glassfish forums/ML at http://forums.java.net/jive/thread.jspa?messageID=480532 a bug was filed against Glassfish https://glassfish.dev.java.net/issues/show_bug.cgi?id=13040 for this issue.]
I'm trying to inject a local no-interface view of a #Stateless EJB into a JSF2 #Named #javax.enterprise.context.SessionScoped backing bean. The EJB is one of several that extend an abstract generic base class. Injection of "#Inject TheEJBClass varName" fails with "Unable to convert ejbRef for ejb TheEJBClass to a business object of type class my.package.name.TheAbstractBase". [edit: Actually, it turns out that injection succeeds, but method resolution in the injected proxy for methods inherited from superclasses fails.] If I use "#EJB TheEJBClass varName" then varName remains null, ie nothing is injected.
Details:
I'm running Glassfish 3.0.1 on Linux (Ubuntu 10.04 in case it matters) and having real problems handling injection of my data model EJBs into my JSF2 session scoped models using CDI (Weld). And yes, before you ask, I have beans.xml in place and CDI is activating to perform injection.
If I inject it with an #EJB annotation, eg:
#EJB TheEJBClass memberName;
... the EJB isn't actually injected, leaving memberName null.
If I inject it with a CDI #Inject annotation:
#Inject TheEJBClass memberName;
... then CDI complains when I call a method of "memberName" that's implemented in a superclass of TheEJBClass and not overridden in TheEJBClass its self, reporting:
java.lang.IllegalStateException: Unable to convert ejbRef for ejb TheEJBClass to a business object of type class my.package.name.TheAbstractBase
at
com.sun.ejb.containers.EjbContainerServicesImpl.getBusinessObject(EjbContainerServicesImpl.java:104)
at
org.glassfish.weld.ejb.SessionObjectReferenceImpl.getBusinessObject(SessionObjectReferenceImpl.java:60)
....
I've tried converting the base to concrete class and de-generifying it, but encounter the same problem, so I don't think I'm hitting the Weld bugs with generic bases (https://jira.jboss.org/browse/WELD-305, https://jira.jboss.org/browse/WELD-381, https://jira.jboss.org/browse/WELD-518).
An outline of the code, with full package qualification on annotations added for clarity, is:
// JSF2 managed backing bean.
//
// Called via #{someJSF2Model.value} in a JSF2 page
//
#javax.inject.Named
#javax.enterprise.context.SessionScoped
public class SomeJSF2Model implements Serializable {
#javax.inject.Inject TheEJBClass member;
public Integer getValue() {
return member.getValue();
}
// blah blah
}
// One of several EJB classes that extend TheAbstractBase
#javax.ejb.Stateless
public class TheEJBClass extends TheAbstractBase {
// blah blah
// does **NOT** override "getValue()"
}
public abstract class TheAbstractBase {
// blah blah
public Integer getValue() {
return 1;
}
}
Note that injection does work if I override TheAbstractBase.getValue() in TheEJBClass, or if I call a method defined in TheEJBClass and not any superclass. It seems like the issue is something to do with inheritance.
Very similar code that used JSF2's built-in lifecycle and injection features worked, but given that this is a new project and CDI is where things are heading in the future, I thought it best to try to go for CDI. Here's what I started out with using JSF2/EJB injection, which worked:
// JSF2 managed backing bean. Using #ManagedBean and JSF2's #SessionScoped
// instead of CDI #Named and CDI #SessionScoped this time.
//
#javax.faces.bean.ManagedBean
#javax.faces.bean.SessionScoped
public class SomeJSF2Model implements Serializable {
#javax.ejb.EJB TheEJBClass member;
public Integer getValue() {
return member.getValue();
}
// blah blah
}
// One of several EJB classes that extend TheAbstractBase
// Unchanged from CDI version
#javax.ejb.Stateless
public class TheEJBClass extends TheAbstractBase {
// blah blah
// does **NOT** override "getValue()"
}
// Unchanged from CDI version
public abstract class TheAbstractBase {
// blah blah
public Integer getValue() {
return 1;
}
}
I'm currently working on putting together a self-contained test case, but thought I'd fire off the question now in case this is something where I'm just doing something silly or there's a well known solution my Google-fu isn't up to finding. Why did it work with JSF2/EJB injection, but fail with CDI injection?
( Since re-posted on the Glassfish forums as http://forums.java.net/jive/thread.jspa?threadID=152567 )
As noted above, it's a Weld/glassfish bug.
Fix: Give up on Glassfish and move to JBoss AS 7, which actually works most of the time.