Using timers in jboss modules - timer

I am required to create a timer/schedule service in jboss (JEE6). The issue is, it gets deployed as jboss module. I know that following code works if deployed as EJB
#Schedule(hour="*/1", persistent=false)
but it doesnt work if deployed otherwise. Are there any recommendations or standard ways to create and use timers in jboss modules? I want to avoid core-java way of creating TimerTask.

jboss modules are created for sharing code across applications in an efficient way. For more refer here. Now, because modules are not deployed in EJB container; its not possible to use EJB scheduler here. The possible solution or way around for this in our case was to create an EJB which has dependency on these jboss modules whose methods will be invoked by schedulers.
for example,
#Singleton
#Startup
public class NotificationRecorderBean {
#Inject
private MyJbossModule myJbossModule;
#Schedule(hour="*/1", persistent=false)
public void execute() {
LOGGER.debug("Recording notification count");
myJbossModule.process();
}
}

Related

#EnableJpaRepositories annotation disables data.sql initialization script

My Spring Boot (v2.3.4) based application uses my custom library containing core entities and business logic. To use entities and repositories from this library I had to use #EnableJpaRepositories and #EntityScan annotations with proper packages provided.
I also wanted to initialize database with some required data (let's say the configuration) during application startup. I found that Spring Boot allows to use data.sql or data-${platform}.sql files to achieve that.
Long story short when using #EnableJpaRepositories annotation the data.sql script is not executed.
I did some digging in the code and found that when #EnableJpaRepositories annotation is not used then entityManagerFactory bean is of org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean type. This bean uses org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher bean post processor, which fires org.springframework.boot.autoconfigure.jdbc.DataSourceSchemaCreatedEvent event indicating the schema has been created. Class, which listens for this event is org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker. This listener invokes initSchema() method from org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer class. This method is responsible for whole initialization using data.sql script.
It looks like setting #EnableJpaRepositories annotation creates instance of different class for entityManagerFactory bean, which does not support this simple initialization.
My basic question is then how to make it all work with #EnableJpaRepositories annotation. I can always use Hibernate's import.sql file (which works fine) but I'm also trying to understand what exactly is going on under the hood I how can I control it.
UPDATE 1 28.09.2021
I did further investigation and #EnableJpaRepositories annotation does not change the instance type of entityManagerFactory but it causes silent exception (?) when creating org.springframework.scheduling.annotation.ProxyAsyncConfiguration bean (during creation of org.springframework.context.annotation.internalAsyncAnnotationProcessor bean). It looks like everything is related to #EnableAsync annotation, which I'm also using but didn't know it might be related. But it is - removing it makes the initialization work even with #EnableJpaRepositories.
UPDATE 2 28.09.2021
I've found full explanation for my issue. There are 4 conditions, which must be met to reproduce the issue:
#EnableJpaRepositories annotation in application configuration
#EnableAsync annotation in application configuration
Configuration implements AsyncConfigurer interface
Autowired any JpaRepository repository or any other bean which injects repository
Enabling asynchronous execution and implementing AsyncConfigurer makes the whole configuration to be instantiated before regular beans. Because Spring has to inject repository, it needs to instantiate entityManagerFactory bean too. Spring prints thenINFO level logs like below:
Bean 'entityManagerFactoryBuilder' of type [org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
One of not eligible BeanPostProcessors is DataSourceInitializedPublisher responsible for firing DataSourceSchemaCreatedEvent event. Without that event, data-${platform}.sql script won't be processed at all.
I'm not sure what is the role of #EnableJpaRepositories in that process but without it the problem does not occur.
Example
Minimal code to reproduce the issue (data.sql located in src/main/resources):
#Entity
public FileStore {
...
}
public interface FileStoreRepository extends extends JpaRepository<FileStore, Long> {
}
#Configuration
#EnableAsync
#EnableJpaRepositories
public class Configuration implements AsyncConfigurer {
#Autowired
private FileStoreRepository fileStoreRepository;
...
}
Solutions
There are two solutions I'm aware of:
Move AsyncConfigurer along with its overrided methods and #EnableAsync annotation to separate configuration class
Use #Lazy annotation on autowired bean like below:
#Lazy
#Autowired
private FileStoreRepository fileStoreRepository;
Similar problem was pointed by #Allen D. Ball and can be checked there.
This behavior had changed.
Take a look at the
how-to guide.
Add:
spring.jpa.defer-datasource-initialization: true

Google App Engine Cloud endpoints, no API

I came to know GAE cloud endpoints yesterday. From that time I am trying to generate APIs for my current web application. I am using JPA2.0, I chose one of my entity classes right clicked on it and then "generate Google endpoint class" . So now I have another class for this entity with #API annotations, etc.
But the problem is after deploying the app when I go to : https://developers.google.com/apis-explorer/?base=https://myAppId.appspot.com/_ah/api#p/
the services tab is empty. Same thing when I check it locally(Image below)
You need to Generate Cloud Endpoints Library (in Eclipse, right click on the Project, it's under Google) as well.
I had similar issue and it was caused by missing public attribute in methods.
#Api
public class MyApi {
#ApiMethod
void myMethod() { }
}
caused that I saw no methods. While added
#Api
public class MyApi {
#ApiMethod
public void myMethod() { }
}
methods started to be visible.
1.Login appengine
https://appengine.google.com/
2.Click the [Version] link in a Main category
3.Select your version and [Make Default] button
4.You can access the api explorer
https://myAppId.appspot.com/_ah/api/explorer
Best Regard.
I actually managed to resolve the above issue. So I had a web application existing and I thought I could just add annotations to it and have the APIs represented for it after deployment. But I realized that I had to start from scratch by creating an android app and then generate the back-end for that app and add my classes there. It now works. Thank you.
Points to remember before working on endpoints :
Need to create an endpoint client library before running your project.(In Eclipse : Project -> Right click -> Google -> Generate cloud endpoints library)
Check whether you are using latest Google Plugin or not. Because files required by endpoints will be executed from the plugin. If you are not able to generate the endpoint library. problem is with the plugin .Try updating it.
Endpoints will work only on default versions. Make sure that you made your version default.
finally try loading http://myApp.appspot.com/_ah/api/explorer. Everything should be fine now.

Prism - what if multiple modules register the same service

I am currently playing around with and reading up on Prism. I know that the suggested way is to have some common "services" that are defined as interfaces in the Infrastructure assembly that all modules can reference. Different modules can implement these interfaces and essentially register to provide these services. And other modules can "consume" these services.
I am wondering what happens if two different modules implement the interface and essentially provide the same service. Which service is a consumer going to get when calling the service interface.
Assume I have an INewsFeed and the BlogScraper module implements this service as well as the PrintMagazineScanner module. If I have another module that consumes this service, lets say by displaying the newsfeeds, which of these services is it going to get?
It depends on the IoC container that you use. Generally, if you try to register a service using the same interface twice, it will either throw an exception right away or will let you do so overriding the previous registration or it will throw an exception when you try to request a single instance while there is more than one registered.
For example, if you take MEF, you can export multiple services using the same contract (interface), but when you import those services you have to define a collection property with the ImportMany attribute on it:
[ImportMany]
public IEnumerable<IMyService> MyServices { get; set; }
This has nothing to do with prism. It is more likely a question of the behaviour of your IoC container.
Yes, this is an IoC issue. If you use the ServiceLocator interface then calling GetInstance will usually (including Unity) return the last type that was registered for that service interface. GetAllInstances will return a list of all registered implementations.

First Hibernate project where to place addAnnotatedClass()

Hello all
I'm trying to build up my first Hibernate project for a Web app, but i'm having some issues
Trying to find out where to place the method:
AnnotationConfiguration config =
new AnnotationConfiguration();
config.addAnnotatedClass(Object.class);
config.configure();
i have some java beans decorated with annotations, shel i just insert it in the same class there the bean is?
Thank you
Ideally, you'd call this only if you are developing a standalone application. In a Java EE environment, you'd just define a persistence.xml file (or hibernate.cfg.xml) in your deployment archive and the container (like JBoss AS) would make a #PersistenceContext (EntityManager) available to you.
In a standalone application, you'd call this in your "Bootstrap" code. The one which sets up the environment.
In "non-Java EE" web applications (seriously, who still uses that?), you'd have to resort to some "hacks", like doing some initialization during context startup (so that you won't need to run this for all requests, as it's an expensive operation).
Partenon is right, you should bootstrap JPA with a persistence.xml.
The Stripes web framework it self does not offer any persistence services. But to make life easier there is an Stripersist extension that offers an out of the box session in view pattern (starts a transaction before the actionbean and does a roll back after the request is handled). Very good examples of how to use and configure Stripersist can be found in the book: Stripes: ...and Java web development is fun again

Guice and JSF 2

I'm trying to use Guice to inject properties of a JSF managed bean. This is all running on Google App Engine (which may or may not be important)
I've followed the instructions here:
http://code.google.com/docreader/#p=google-guice&s=google-guice&t=GoogleAppEngine
One problem is in the first step. I can't subclass the Servlet module and setup my servlet mappings there because Faces is handled by the javax.faces.webapp.FacesServlet which subclasses Servlet, not HttpServlet. So, I tried leaving my servlet configuration in the web.xml file and simply instantiating a new ServletModel() along with my business module when creating the injector in the context listener described in the second step.
Having done all that, along with the web.xml configuration, my managed bean isn't getting any properties injected. The method is as follows
#ManagedBean
#ViewScoped
public class ViewTables implements Serializable
{
private DataService<Table> service;
#Inject
public void setService( DataService<Table> service )
{
this.service = service;
}
public List<Table> getTables()
{
return service.getAll();
}
}
So, I'm wondering if there is a trick to get Guice injecting into a JSF managed bean? I obviously can't use the constructor injection because JSF needs a no-arg constructor to create the bean.
Check the following JSF-Guice integration framework/advice:
http://code.google.com/p/jsf-sugar/
http://notdennisbyrne.blogspot.com/2007/09/integrating-guice-and-jsf.html
http://cagataycivici.wordpress.com/2007/03/26/integrating_guice_and_jsf/
http://snippets.dzone.com/posts/show/7171
You can also create an HTTP servlet that then simple delegates the request on to a FacesServlet (like a wrapper). This should give you the same effect using Guice Servlet.
How about this approach, works well for us:
http://uudashr.blogspot.com/2008/12/guicing-jsf-with-guice.html
being the developer of jsf sugar I really would like to know the problem you had using it. We are already using it in production here so there shouldn't be any "show stoppers", maybe something is just not well documented? Just drop me a mail: murbanek(at)gmx_net (replace the _ with a .) .
check out http://code.google.com/p/guice2jsf/, and website starchu.blogspot.com, it has excellent library that provides Guice and JSF 2.0 integration
As information in this post are getting out of date but the question is still relevant, I'd like to share my findings about this topic. I wrote a little tutorial including a runnable sample project on how to setup a fully guice powered web stack. You can find it here: https://github.com/skuzzle/guice-jsf

Resources