Here's my scenario:
some email sending bean gets called with a bunch of parameters needed for mail construction.
it creates MultiPartEmail and queues it for sending which is done by separate thread on the background, caller doesn't care if it was sent or not.
the delivering thread picks up queued email instance and does email.send() - so off it goes.
when delivery fails, the bean will try re-sending the mail every 5 minutes for three times and then give up.
Question:
I can't figure out how to handle #4. What I've got at hand is previously constructed MultiPartEmail instance which failed to be sent. Apparently doing email.send() again throws this:
java.lang.IllegalStateException: The MimeMessage is already built.
Is there a way to reset this illegal state so that message can be re-used. I don't really have means of creating new instance from scratch - the caller is long gone, and it will make the whole mechanism quite ugly without being able to use already built object. I think I'm missing something very simple here..
I see this is an old question, but I just hit the same problem and I found the solution.
When you create an instance of MultiPartEmail (or HtmlEmail), set its properties, and then invoke the send() method, the object will internally invoke the following methods:
buildMimeMessage()
sendMimeMessage()
It is ok to invoke sendMimeMessage() multiple times, such as a send-with-retry scenario. The problem is that buildMimeMessage() can only be invoked once. When you rely on the send() method of the base Email class, you get the exception found by the original poster.
The solution is to use the two methods I just mentioned when your Email object is a MultiPartEmail. You explicitly invoke buildMimeMessage() once, then invoke sendMimeMessage() one or more times.
Related
I am exposing some operations in a class in my Spring Boot application through JMX. However, in jConsole, when I invoke the method, "Method invoked successfully" pops up. I know that's because the method returns nothing. But I want to show useful information when method invoked.
I am using #ManagedOperation which is provided by Spring, but it has no such property. I couldn't find anything on the documentation, either.
I can notify the executor by sending a notification, but I wonder if there's any way of directly alerting information.
This is how it normally alerts.
Let me give an example. I have multiple containers that are running and I have provided an operation to stop and start them. When, for example, start is invoked, I want it to alert that "Container X has started" or "Container X is already running". I can do this, by returning these responses as string from the method, but I don't think this should be the way to go. I wonder if a way to do this exists through the API itself.
Hope, I'm clear.
That's not possible and you cannot change the jConsole behavior.
To your example:
If you have multiple outcomes of the invoked method it makes perfectly sense to return this as the message.
But maybe you should consider to expose these as HTTP endpoints where you can return an appropriate HTTP status code instead of a string.
The scenario of my problem is:
In my servlet I get a large amount of data from somewhere (not relevant). I have to iterate over all this data and put it in an array, convert it to a JSON object and send it to the client side for viewing. If I do this in a single response it takes a very long time to display the results. Hence, I need to do multithreading.
The created thread needs to keep on adding data to the list while the main thread whenever it gets a request (requests for data keep on coming periodically) sends the present available list.
For instance on first request the response sent is : 1 2 3
Second request : 4 5 6 and so on.
Now I come to actual problem : I don't know how to do multithreading in a servlet. I have looked through numerous resources and examples but it only has confused me further. Some examples have created threads right in doGet which I think is very wrong, some have created them in the init() method but I dont know how can I pass parameters and get results from the thread if it is declared in the init method (It cannot be a global variable). Then there are examples of servletContextListener but I havent found anything useful or that makes sense.
Can anyone please guide to me a reliable source or just give me some sort of pseudo code to get a solution to my problem. It would be extremely helpful if the answers are in context with the aforementioned scenario.
Thanks
The created thread needs to keep on adding data to the list while the
main thread whenever it gets a request (requests for data keep on
coming periodically) sends the present available list.
If I got you correct, you like to get some data as background service and make them ready for clients once they request them(sounds like harvesting data).
Well, creating thread in web-apps, or generally stuffs come with managed environment is different, creating a thread implicitly would cause of memory leak.
One good solution would having a ThreadPool(either by container context/ndi or create it manually).
AND it MUST be created in a manageable manner, where you would control it by environment related events.
ContextListener is your friend, having a context listener class, like this.
public class dear_daemon implements ServletContextListener,Runnable{
ExecutorService the_pool;
Thread the_evil;
/*following get invoked once the context is called*/
public void contextInitialized(ServletContextEvent sce){
/*initialize the thread-pool, and run evil thread*/}
/*following get invoked once the context is destroying*/
public void contextDestroyed(ServletContextEvent sce){eviling=false;
/*stop evil(this) thread(first), then destroy thread pool*/
}
volatile boolean eviling=true;
public void run(){
while(eviling){
/*run Runnable instance which do data fetching using thread-pool*/
}
}
}
And register the listener in web.xml
<listener>
<listener-class>dudes.dear_daemon</listener-class>
</listener>
Having a class(runnable) which do the data fetching, and invoke it by evil thread, each instance using one thread.
The ContextLisstener helps you correctly shutdown and manage init and hult events by container, using the same thing with servlet init is possible, but make sure you do the same thing about hulting with destroy method of servlet.
If you like to do thread-thing about it, make sure you are doing things thread-safe since you have one thing to store data(a list).
If any synchronization is needed(for example ordering the fetched data), make sure you are doing it right, or you will face with deadlocks, or low-performance code.
If any(probably) IO action is needed for getting data, note java IO is blocking, so set appreciated read and connection timeouts, or switch to NIO if you can handle complex NIO stuffs.
If applying these changes make the environment complex, and you like to do alternative solutions, you may simply extract the data fetching from web-profile and run it as a external daemon-service or applciation, where the applciation will pass the fetched data to the server context using calling one of your CGI/Servlet.
I am trying to work out if javax.websocket.Endpoint.onError (and thus the resulting methods in say Spring) can be called during a call to any of the websocket send methods (e.g. javax.websocket.RemoteEndpoint.Async.sendText or thin wrappers in say Spring), at least for the specific javax.websocket.Session, since if it can I need to make sure my server implementation regarding state associated with that socket is re-entrant, which complicates it.
The method is documented here:
https://javaee-spec.java.net/nonav/javadocs/javax/websocket/Endpoint.html#onError%28javax.websocket.Session,%20java.lang.Throwable%29
It only mentions errors regarding incoming data. So I think it is safe to say the send will never itself cause it to be called (rather than passing an Exception to the send handler, or throwing an IOException from the basic remotes), but is incoming data processed while a send is in progress, and can that result in the method being called (presumably from another thread, threading details seem a bit thin as well...).
I have a Java class which creates a supervisor Actor which then creates a child actor for each request it needs to generate.
Java class uses a Future to get response back from supervisor Actor
Supervisor uses tell and sender reference to get response back from child Actor
However my supervisor Actor is a singleton scoped bean so i need to be able find a way to store the sender reference each time my Java class makes a request to the supervisor. What is the best way to do this?
I don't think singleton scope is a good isea, as Akka needs to be able to restart actors when exceptions occur. That might lead to some weird problems. We used prototype scope ourselves.
Other than that, one possibility is to simply decouple receiving the request and sending the response by passing the server through your actors, you just use forward instead of tell, and the last actor in your pipeline will respond to the sender. This way the supervisor does not need to care about the response. Obviously this is ideal if your supervisor does nothing but sending the response to the sender.
If there is some processing to be done before sending the response, you can create a temporary actor and pass it the sender reference, and let this actor collect the results, send the response to your future and stop itself. This is especially useful if you need to wait for more than one response and aggregate it.
You can also add the sender reference to the message you send from the supervisor to your actors and back to the supervisor. Simple, yet effective.
I am making an application that will work much like a real time chat. A user will be constantly writing on lets say a text area and messages will be send to other users. On the communications class I have set up a receiver. When a message from someone reaches the client, the receive method will be invoked and will get the message. What I can't understand is how the code will be executed. What happens if, while the user is typing/sending a message the receive message is invoked ? What do I need to do in order for this to work properly ?
Hope the question is clear enough.
ps : Im still in the design phase thats why I haven't tested it to see what happens.
Also atm I only use a second thread to receive messages which calls the receive method.
There should not be a problem at all.
When a message from someone reaches the client, the receive method
will be invoked and will get the message. What I can't understand is
how the code will be executed?
You should have a Receiver class that will encapsulate a socket (from which your receive data) and keep a set of listeners (see Observer pattern). A GUI can be one of the listeners. When a message is received via the socket, you need to notify all listeners by forwarding the data received. This way, you have a clean and nice way to notify the GUI about new messages arrivals.
What happens if, while the user is typing/sending a message the
receive message is invoked ?
This depends on the type of IP protocol you are using but in general your don't have to worry about this although I suggest you protect your sockets using lock mechanisms.
What do I need to do in order for this to work properly ?
Here is a nice example that can give you some inspiration :)
EDIT: As for your question regarding execution flow, sending and receiving are two different and uncorrelated operations that can happen at the same time. This can be achieved by implementing send and receive operations in two different threads. Here is an article on socket communications and multithreading.
You should either do what traditional Java EE app servers have done, which is assign a separate thread for processing each incoming message, or try a Java NIO solution along the lines of Netty.