Showing message from inner class of a managed bean - jsf

I have used the solution described in this discussion to implement BackgroundJobManager as an inner class inside my JSF bean class. I have also created an ABCTask (also an inner class) as a thread that will run at the scheduled time for the BackgroundJobManager. I have a requirement to push a message onto the JSF page but doing so from the task class ABCTask results in an NPE. The same thing works for the outer bean so i'm convinced it's something to do with the context of this inner class and the bean. Would appreciate if anyone knows a solution for this.
My inner class code is as below :
public class ABCTask implements Runnable {
public ABCTask() {
}
#Override
public void run() {
setTimeoutOccuredFlag(true);
try {
if (getActiveControlledAgent().isEventLogRunning()) {
getActiveControlledAgent().setEventLogRunning(false);
}
printTimeoutMessage();
logger_o.fine("Now leaving the ABCTask ...");
} catch (Exception e) {
logger_o.error("An error while idling "+e.getMessage());
}
}
}
The $printTimeoutMessage() is as follows :
void printTimeoutMessage() {
FacesUtils.addErrorMessage(MESSAGES.getString("common.timeoutOccured"));
}

You're basically manually spawning a thread. The FacesContext is only available in the thread serving the HTTP request which matches the URL pattern of the FacesServlet, not in other threads. The FacesContext#getCurrentInstance() would return null in all other threads.
Think once again, how would you ever send a message to the HTTP response without that the client has sent a HTTP request? By default, you can't send anything to the client without that it has requested for it.
Look for poll/push techniques. This concrete problem is completely unrelated to the class hierarchy/scope. In the future, it'd be more helpful for you and us if you've identified what exactly is null. You seem to not have done that at all.

Related

Cannot rebind JHipsterProperties properties with Spring Cloud ContextRefresher

I have a piece of code to do automatic configuration properties reloading in my JHipster application.
A lot of #ConfigurationProperties annotated beans are well refreshed except JHipsterProperties bean that is not.
The JHipsterProperties bean is not known by Sring Cloud Context's ConfigurationPropertiesBeans and I cannot understand why.
A solution is to add the missing #ConfigurationProperties beans to ConfigurationPropertiesBeans but this is just an ugly workaround.
public void triggerReload() throws IOException {
LOG.info("Reloading configuration");
try {
this.contextRefresher.refresh();
} catch (final BeanCreationException e) {
// DO SOMETHING USEFUL
}
LOG.info(this.jHipsterProperties.getMail().getFrom()); // <--- value is not updated
LOG.info(this.mailProperties.getHost()); // <--- value is updated
}

Calling #Asynchronous metod from library on Wildfly Linux

I've encounter some problem while applying a small library to send email using wildfly email resource
Idea with library is to provide singleton providing asynchronous method to send emails.
in short service looks like
#Singleton
public class MailService {
private static final String MIME_TYPE = "text/html; charset=utf-8";
private static final Logger LOG = Logger.getLogger(MailService.class.getName());
#Inject
private Session session;
#Asynchronous
public void sendEmail(final EmailModel email) {
try {
MimeMessage message = new MimeMessage(session);
if (email.normalRecipientsListIsEmpty()) {
throw new RuntimeException("need destination address.");
}
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email.getNormalRecipients()));
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(email.getCCRecipients()));
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(email.getBCCRecipients()));
message.setSubject(email.getSubject());
message.setContent(email.getContent(), MIME_TYPE);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException("Failed to sen email.", e);
}
}
}
Injected session is produced in project via #Produces annotation in Stateless service field.
While on windows everything works fine, however if deployed on wildfly running on linux, there is an timeout exception with message like "could not obtain a lock on method within 5000milis"
When i moved whole code to project, with no changes, everything started to work perfectly.
My question is, why is this happening? Is there a difference in implementation somewhere or in configuration? How can i fix that and move code back to library where it can be reused in other projects?

Entity Framework Context on multiple threads

I've seen so many questions similar to mine, but no answers that quite seem to apply to my situation.
My ASP.NET MVC app with EF 6 Code first and Unity has a web service that adds something to the database, then fires off another thread that adds more stuff to the database. The reason for using the other thread is to return the original request as quickly as possible. The context class is obtained using the Unity container RegisterType().
I've got lots of repository classes all using the same context, so to make sure they get the same instance I could use the PerRequestLifetimeManager in my Unity container, and that's fine for the http request threads but that the other threads can't use the context returned by the PerRequestLifetimeManager because this is only valid on the original http request thread.
So, I can use the PerThreadLifetimeManager. This is great because now the main request thread and the other thread it kicks off get the same instance of the context returned by Unity. The trouble is that so do other requests if they get given the same thread, so this is no good either.
So how can I configure things so that the request threads get their own PerRequest Lifetime Manager created context, and other threads get a different context?
The issue is made a little more difficult by the fact that the new thread calls other classes that need to use a context instance. However, these other classes can be used from the main request thread or the new thread, so grabbing a context instance when the thread is started and then passing it around will be tricky.
Thanks in advance
No takers then...
I'm going to have a go at answering my own question, but could do with some thoughts on my approach.
So I can't use the PerRequestLifetimeManager because worker threads can't use the context that this returns, but I can't use the PerThreadLifetimeManager because the context can last the lifetime of several HTTP requests. This class attempts to provide the best of both worlds.
/// <summary>
/// For the context class the PerRequestLifetimeManager is the most suitable lifetime manager,
/// but this doesn't work when a new worker thread is started as this needs to access the context.
/// The PerThreadLifetimeManager is no good either as the context can last for more than on request.
/// This class attempts to give the best of both worlds: per request lifetime management for HTTP requests
/// and thread storage for worker threads.
/// </summary>
public class PerRequestOrThreadLifetimeManager : PerRequestLifetimeManager, IDisposable
{
private const string threadDataSlotName = "PerRequestOrThreadLifetimeManager";
public override object GetValue()
{
if (System.Web.HttpContext.Current != null)
{
return base.GetValue();
}
else
{
return getManagedObject();
}
}
public override void RemoveValue()
{
throw new NotImplementedException();
}
public override void SetValue(object newValue)
{
if (System.Web.HttpContext.Current != null)
{
base.SetValue(newValue);
}
else
{
Thread.SetData(Thread.GetNamedDataSlot(threadDataSlotName), newValue);
}
}
private object getManagedObject()
{
return Thread.GetData(Thread.GetNamedDataSlot(threadDataSlotName));
}
public void Dispose()
{
try
{
IDisposable obj = getManagedObject() as IDisposable;
if (obj != null)
{
obj.Dispose();
obj = null;
}
}
catch { }
}
}

Synchronized vector- java server

So I am building a website according to MVC Pattern. I use Eclipse/Tomcat.
I have a PostAccess class, which retrieves my posts from the DB, it creates an vector with PostBean items in it. The servlet gives the vector to the jsp file and the jsp file creates the html etc.
My problem is that more than one thread is interacting with the vector, so I get this on eclipse:
java.util.NoSuchElementException
at java.util.Vector$Itr.next(Unknown Source)
As i learned from googling, this error comes because of not having synchronized the threads that edit the vector.
But where exactly should i do the synchronization?
This code is in my PostAccess class :
public synchronized Vector<Post> RetrievePosts() throws SQLException
{
Vector c = (Vector)(new Vector());return c;
}
This is in my Servlet class:
public synchronized void process(ServletContext servletContext,HttpServletRequest request, HttpServletResponse response)
{
Vector<Post> c = (Vector<Post>)(new Vector<Post>());
try {
PostDAO pDAO=new PostDAO(servletContext);
c=(Vector<Post>) pDAO.RetrievePosts();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
request.setAttribute("posts", c);
}
This is in my jsp:
<% Vector<Post> c =(Vector<Post>)request.getAttribute("posts");
Iterator<Post> i = c.iterator();
herePost p=(Post)i.next();
while (!c.isEmpty()) { %>
I don't think two threads are working on the same Vector as in the code you show the Vector is declared within the process method (I'm assuming that that's the one that gets called by doGet) and thus it's private to the thread that's handling the request. So, unless something really funky is going on in PostAccess I think you can rule out threads thrashing the Vector.
However, this looks like it could be the cause of the problem:
Iterator<Post> i = c.iterator();
herePost p=(Post)i.next();
If the vector is empty to start with that will cause a java.util.NoSuchElementException as the isEmpty() test is done afterwards.

How to update UI after a web service calling thread is finished

Questions about threads are in no shortage, I know, but I can't seem to find a "full" example of a thread doing http work and then coming back to update the UI.
I basically call a few web services upon app launch. I obviously don't want to freeze the UI so I would want to use a separate thread, right? I have found a bunch of examples online on how to get a new thread to perform some task. But I haven't yet found one that shows how to actually update the UI when the thread's task is done.
How do I know when the web service thread is done? Is there a callback method? Can I access the UI from this callback method if one exists.
Edit: (Here is some code)
//The activate method is called whenever my application gains focus.
public void activate(){
DoSomething wsThread = new DoSomething();
wsThread.start();
}
public void wsCallBack()
{
myTabScreen.add(new ButtonField("Callback called"));
}
public class DoSomething extends Thread
{
public void run()
{
try
{
wsCallBack();
}
catch(Exception e)
{
}
}
}
Very simple. But it never creates the button.
Any ideas?
Thanks a lot.
You can set up a "callback" system to notify the UI when the threads complete. Have a class that extends Thread and pass to it a reference of the class that should be called at the end. If you have a list of such classes that needs to be notified create a Vector on the Thread implementation to hold them. Override the run function and after doing everything you need to do simply call a method on the UI class (iterating through the vector if needed). So your classes may look like:
public class commThread extends Thread{
MyUIClass callbackObj;
public commThread(MyUIClass myUiClass){
callbackObj = myUiClass;
}
public void run(){
//do stuff
callbackObj.callback();
}
}
and your UI class:
public MyUIClass{
public void callback(){
//refresh the UI
}
}
Of course if you have multiple threads running at the same time and calling the same UI object make sure to synchronize the callback method.
Hope this helps!

Resources