OSGI two instance of the same service - java

I do have a service "A" this service will be consumed from 11 other components. If I check all available services via the osgi console I do see only one instance and all 11 components consuming this service.
But for some strange reason, I don't understand, two of the components don't use the same service instance. If I debug I see two different IDs. How can this happen?
And I am not doing anything mentioned here.
I solved the problem by setting "This component is immediately activated" within eclipse. But as I red here, this is not the purpose of this checkbox. So maybe someone can explain how this happened in the first place and why it was fixed with this enabled.

When you use Declarative Services, the DS runtime may under certain circumstances re-instantiate your service, usually because some services it depends on have appeared/changed/got removed and the references are static. Check to see that all sites where service A is used are either static, or dynamic with both bind/unbind methods.

Related

How to do many simultaneous jsoup sessions (Spring boot project and concurrancy)

Maybe this is a very basic Java question. Forgive me if it is.
I have this Spring Boot project that needs to, for every registered user, automatically (in the background) connect periodically to a website and download many documents and/or check for changes.
The "download/check" system was externally developed. Every method was static.
Am I right thinking that it IS a problem when I want to have more than one simultaneous execution?
Even if it has all specific connection parameters through parameters?
Thinking of that, I removed the static annotation on almost every method. Now I need to create a new instance for every execution.
When I began adding it to my Spring boot project, I realized there are a bunch of services that make simultaneous connections to a web service, and there I didn't even care about concurrency.
AFAIK, each service is a singleton. Right? So there is no new instance for every connection. Right?
My question is: If I happen to have 100's of users... How should I integrate the jsoup code?
Should I create a new instance from a service?
Should I convert it to a Service itself and just #Autowire it to the service where the process is triggered?
Is it better to make it static? (this one I don't think so, but maybe I'm wrong)
Any other option?
If possible, please add a reason why I should follow your suggestion.
Thank you all for your help.
First of all I'd say if your classes are not maintaining any state then it is actually a good thing if everything is static cause this gets you rather close to functional programming. If you are then passing everything as an parameter to a method and don't have any state in the class (not the method) then everything is kept on the stack which is not shared amongst threads. Long story short: thread-safe.
If you maintain any type of state in your classes – be it services or components – then you have to make sure that they are executing in a thread safe way. One of the easiest ways is to change the #Scope of that particular bean to prototype or for instance request as you are running this as a web app.

OSGi User Admin Service User Objects

I wanted to use the OSGi User Admin service for security but I could not get enough resource about it.
I want to authenticate certain bundles that will be installed in the system and represent them by User-Objects after authentication. So that I can later use these User-Object for authorization.
I have 2 questions:
Since I have more than one user, how can I know which bundle is calling a secured method? (I don't want to pass the user object as a parameter to every method I want to control).
How can I relate the bundles with the User-Object representing them?
I want to have one bundle as an entry point that will authenticate all these other bundles and have control over them. But I couldn't even find anyone mentioning using User Admin service. Is there another option for OSGi security besides CPA? I would like to use this to secure my console as well.
That's quite a few questions rolled into one. Let me try to answer them all.
First of all, the UserAdmin service is specified in the OSGi compendium. There, it explains how users, roles, etc are defined and how you can use the service to answer questions like "does this user have role X"? What that does not tell you is how to use this service as part of a security solution. That's up to you.
Regarding question 1, which is not an OSGi related problem (but rather a generic one in Java applications), there traditionally have been a few methods of passing on a "context" to a method:
Making it an argument to each method (which you do not want to do).
Storing it in the ThreadLocal context (which is fairly popular in JavaEE, but has its downsides if your application delegates work to threadpools that might or might not pass on such a context correctly).
If this is all about security for services that you implement yourself (and not third-party ones) you could use the ServiceFactory pattern in OSGi to give each client bundle it's own context (and embed the User object in there; for examples look at the LogService implementation in Felix, which uses that mechanism to add a bundle.id to each log message).
Sometimes it also makes sense to embed the context not in an extra parameter to your methods, but as part of some existing object (so effectively you are then associating the context with specific objects, which might or might not make sense depending on your domain).
Another option would be to use the Apache Felix Dependency Manager to intercept the services you want to secure (with an aspect) and, in the aspect, figure out what bundle is calling, and do the proper security checks (probably requires a more detailed answer if you want to give that a go).
Regarding question 2, bundles have a symbolic name that identifies them. You could use that to associate a bundle with a User. There are other options, but this is the most obvious one.
Regarding your question about options for OSGi security, I would say ConditionalPermissionAdmin (and the older PermissionAdmin) is the only solution to address security within the OSGi framework itself, if you want to specify what specific bundles can and cannot do in terms of importing packages, using services, accessing the filesystem, etc. You would have to write your own custom permissions if you want to integrate this with UserAdmin.
Finally, the secure console is yet another thing you need to address yourself. You might be able to find some building blocks as I know there have been people implementing some role based access (David Bosschaert comes to mind). However, the console is a complex and powerful thing, so answering this question alone takes more than a simple SO question because it depends what and how fine grained you want to implement this.

Vaadin starts multiple Application instances for single application

I'm looking at my Vaadin app running on a local tomcat server with JProfiler. This shows that every time I start up the server and run my application, there are 3 instances of my main Application class. If I close the application in the browser or even close the browser completely, there are 2 left. I've noticed that the Application's init() method gets called 3 times during startup, even though I never explicitly call it myself. I am using the Threadlocal pattern (but with InheritableThreadlocal).
It doesn't look normal to me, is there anything that can cause this kind of behaviour?
(Copied this question from my post on the vaadin forums)
From your description, I gather that Application is a class written by you (and not something supplied by Vaadin) and that you somehow save the instances of this class in a ThreadLocal.
This would explain the behavior that you're seeing: Tomcat will start several threads to handle client requests. For each thread, a new Application instance will be saved in the ThreadLocal.
Try the (evil) Singleton pattern or (better) dependency injection with the singleton scope instead.
If you use the singleton pattern, make sure you use the code under "Construct in multi-threaded applications" or you will get odd errors in Tomcat. This article on JavaWorld explains it in depth: Simply Singleton
EDIT Based on your feedback: The behavior your see is expected and correct. Tomcat uses threads to handle requests and it will pre-spawn a couple to be ready for business (in your case, it spawns three).

Single background thread in an EJB3.0 container

We have a need to run a housekeeping thread in an EJB3.0 container. We currently have a "TimerService" #Stateless EJB (necessary because it has has other #EJBs injected), which creates an interval EJB Timer when it's startTimer() method is called. There should only be one instance of this timer thread. The current solution involves calling startTimer() from the init() method of one of our servlets, where the servlet is forced to load at startup using in the web.xml, but that feels like coincidental behaviour instead of the right way to do things. We've already had a problem because someone else subclassed that servlet, which meant that init() was called twice, which meant two timer threads.
This feels like it's not an unusual requirement, so what's the proper way to do this, if anything? It seems to me like there ought to be a simple way to ask the container to start a thread when it starts up, without having to tie it to other resources in the container.
For EJB < 3.1 you are going to have to get application server specific or hackish. Since you mention you are using JBoss, you can use the #Management tag which has defined lifecycle methods.
I want to suggest 2 solutions.
1 The fix to your implementation.
make your servlet final. this will avoid subclassing. But the servlet still may be deployed twice. To avoid this create static boolean variable into the servlet. The init should check this variable. If it is false it turns it to true and continues. Otherwise it throws exception.
This is fast fix that you can do now.
but it is not a "right" solution. For example this will not work in clustered environment.
2 There are 2 "right" solutions.
2.1. use quartz
2.2. Implement timer using JCA. Connector is the only place in J2EE where you can legally use threads and timers.
I mentioned JCA in other context in this article:
http://alexradzin.blogspot.com/2010/10/send-delayed-jms-messages.html
You are welcome to view it and see a short code sample that can probably help you.
Does your app server support "startup beans"? I ask because in WebSphere Application Server, there is an option in the administrative console to set the server to fire "startup beans" on server start up. We use it for certain applications we have that require a lot of "heavy loading" and initializing, so that way we can minimize start up time for the end-user experience.
Here is a link to WAS 6 documention (old, I know, but still helpful). Startup beans
I know this is specific to IBM WebSphere, but perhaps your app server (if not WebSphere) has something similar to help you kick them off?

Singleton in Java App Server.. How bad of an idea is this?

I am currently working on some older java code that was developed without App Servers in mind. It is basically a bunch of "black box code" with an input interface, and an output interface. Everything in the "black box" classes are static Data Structures that contain state, which are put through algorithms at timed intervals (every 10 seconds). The black box is started from a main method.
To keep this easy for myself, I am thinking of making the "black box" a Singleton. Basically, anyone who wants to access the logic inside of the black box will get the same instance. This will allow me to use Message Driven beans as input to the black box, and a JMS Publisher of some sort as the output of the black box.
How bad of an idea is this? Any tips?
One of the main concerns I have though, is there may be Threads in the "black box" code that I am unaware of.
Is there such thing as "application scoped objects" in EJB?
Note: I am using Glassfish
If you use a simple singelton, you will be facing problems once you enter a clustered environment.
In such scenario, you have multiple classloaders on multiple JVMs, and your sinlgeton pattern will break as you will have several instances of that class.
The only acceptable use for a singleton in an app server (potentially in a clustered environment) is when you the singleton is totally state-less, and is only used as a convenience to access global data/functions.
I suggest checking your application server vendor's solution for this issue. Most, if not all vendors, supply some solution for requirements of your sort.
Specifically for Glassfish, which you say you are using, check out Singleton EJB support for Glassfish. It might be as simple as adding a single annotation.
I would say that creating a singleton is actually the only viable idea. Assuming that code inside this "black box" is known to use static fields, it is absolutely unsafe to create two instances of this facade. Results are unpredictable otherwise.
Far from being a bad idea, it actually sounds to me like potentially quite a good idea.
Just from a program design point of view: if your black box is conceptually an "object" with properties and methods that work on them, then make it into an object, even if there'll only ever be one of them instantiated.
It should work, but there are some issues you may have to deal with.
Threading, as you have mentioned. An MDB is run in the EJB container where you cannot create your own threads, so you have a potential problem there. If you have access to the actual code (which it sounds like you do), you may want to do some refactoring to either eliminate the threads or use an "approved" threading method. The CommonJ TimerManager will probably work in your stated case since it is performing some task on an interval. There are implementations available for most app servers (WAS and Weblogic have it included).
Classloading - This is dependent on you configuration. If the singleton is created and manipulated from MDB's within the same EAR, you will be fine. Separate EAR's will mean different classloaders and multiple instance of you Singleton. Can't comment on whether this would be a problem in your case or not without more information.
I'm missing a point? You mentioned that the 'black box code' contains state. MDBs may be limited to 1 instance per destination but without proper configuration you will end up with a few MDBs. All of them working with your single instance of 'black box code'. For me it seems this is not a good idea, because one bean will override the 'black box code' state a other bean has created a few ticks before.
It seems to me that the artifact that better fits to your requirement is a JBoss MBean. (If you are thinking on JBoss as AS candidate).
Standard MBean Example
MBeans can also be deployed as Singletons, in case of JBoss clustering.
Clustering with JBoss
I hope that this is useful for you.
Rafa.
Fix the code to get rid of the statics as soon as possible. Singletons are not a step in the right direction - they just add extra misdirection.
Don't use Singletons where state may change.
Exposing the global instance of your black-box class doesn't seem like the way to go. Often times, singletons will seem like they will make things easier on you, and in a way they can, but it often comes back to bite you and you end up having to restructure a large chunk of your code.
In the webserver world, an object can be scoped to the request, the session, or the application. Perhaps what you need is a application-scope object.
Search the docs for "application scope object" or "application lifetime object".
Why not create a rest interface for the blank box thingy and let clients make http calls ?
IMO, it's a good idea to have an EJB container of your Singleton needs. In Java EE 6 placing a #Singleton annotation in your session bean gives you a named singleton.

Categories