How to send email to registered user in Java EE - email

I want to send an email activation link to a registered user. I already set up my Sendmail.class which work` perfectly.
Here is the scenario:
the user request for registration by providing information via a restful client
the restful endpoint gets the request to do some business operation and sends a computed code to the email of the registered user and returns a response saying 'successfully registered'
The problem is that I don't want to wait for the Sendmail.class to finish the sending process (it may fail) to return the 'successfully registered message
How can I handle this process using Java EE?

Put the code that sends the email in an #Asynchronous method.
Example:
#Stateless
public class EmailSender {
#Asynchronous
public void sendMail(...) {
// send mail here
}
}
From the place where you do your business logic:
#Inject
private EmailSender emailSender;
public Foo myBusiness() {
// Compute stuff
emailSender.sendMail(stuff); // returns immediately
// do other stuff if needed
}
See the Oracle tutorial for some extra info.

Put your e-mail sending code in a thread. Even you can easily use SwingWorker:
SwingWorker worker = new SwingWorker() {
#Override
protected void done() {
}
#Override
protected Object doInBackground() throws Exception {
// Send your e-mail here.
}
};
worker.execute();

Related

Apache Shiro; SecurityUtils.getSubject() for a schedule user?

I want to implement the following scenario:
I have a EJB scheduler, which should run every 1 minute.
My issue is the following:
I need a login for the user, who execute the schedule. This should be a system user. There will be no login via GUI.
How can I login this user and execute further task?
Currently I´m trying in my class:
#Singleton
#LocalBean
#Startup
public class Scheduler {
public void startSchedule() {
Subject currentUserShiro = SecurityUtils..getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("test#domain.com", "test1234");
currentUserShiro.login(token);
In one of my function, I check e.g. for the permission:
SecurityUtils.getSubject().isPermitted("billingInvoice:create")
I´m getting currently the following issue:
No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.
Any idea?
Code update:
private void addScheduleToList(ScheduleExecution scheduleExecution) throws UnknownHostException {
synchronized (this) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-web.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = new Subject.Builder().buildSubject();
Runnable myRunnable = null;
subject.execute(myRunnable = new Runnable() {
#Override
public void run() {
// Add tasks
executeAction(scheduleExecution);
}
});
//////
schedulingService.addTaskToExecutor(taskId, myRunnable, 0);
}
}
I´m gettig now not anymore the issue message which I got initialy, but it seems I´m getting PermissionException, because the user has not the permission? If I check the Subject object, this object is not authenticated. This Subject object needs full permission. How can I do this?
SecurityUtils.getSubject().isPermitted("billingInvoice:create") == false
You have a couple of options.
Move your permission checking to your web-based methods, this moves the permission checkout outside of your scheduled task.
(this isn't always possible and since you are asking the question, I'm assuming you want the 2nd option)
You need to execute your task in the context of a user. Create a new Subject using a SubjectBuilder and then call the execute with a runnable from your task.
See https://shiro.apache.org/subject.html specifically the "Thread Association" section.

How to removing response header with a RestFilter

Is it possible to remove response headers with a RestFilter? Looking at this cookbook you would say it should be possible. However, the filter is only called when the request is incoming, before the call to the resource class. I was expecting to have a hook where I can modify the response headers before sending it back to the client.
i had a look at CORSFilter as an example, but it only sets headers, not remove them.
To be more specific, I want to remove the WWW-Authenticate header that is set by the Auth provider when the session has expired. This header causes a popup in the browser (chrome) that is undesirable.
what you need is a javax.ws.rs.container.ContainerRequestFilter. In jax-rs such filters can be registered in a javax.ws.rs.core.Application. The application used in ICM is com.intershop.component.rest.internal.application.DefaultRestApplication which can be adapted using an com.intershop.component.rest.internal.application.ApplicationClassesProvider that can be registered using a Set-Binding.
So you could create a Guice-Module and your filter:
public class MyRestModule extends AbstractModule
{
#Override
protected void configure()
{
Multibinder<ApplicationClassesProvider> binder = Multibinder.newSetBinder(binder(),
ApplicationClassesProvider.class);
binder.addBinding().toInstance(c->c.accept(MyResponseFilter.class));
}
}
public class MyResponseFilter extends ContainerRequestFilter
{
#Override
public void filter(ContainerRequestContext request, ContainerResponseContext response)
{
response.getHeaders().remove("WWW-Authenticate");
}
}
Please note that this filter will be applied to all requests, so please make sure you remove headers only for requests you really care about.

QuickFIX/J: Not receiving ExecutionReport messages

After opening an order with our brokerage firm, we desire to obtain the fill price from the ExecutionReport messages. Below you will find the callback code used.
The MarketDataSnapshotFullRefresh messages are received properly, but the second if block is never triggered. Strangely, the corresponding messages.log file does contain multiple 35=8 messages.
We use QuickFIX/J as FIX engine.
#Override
public void fromApp(Message message, SessionID sessionID) throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {
if (message instanceof MarketDataSnapshotFullRefresh) {
// do stuff with MarketDataSnapshotFullRefresh
}
if(message instanceof ExecutionReport) {
// do stuff with ExecutionReport
}
Message handling is ideally done by a quickfix.MessageCracker, though sometimes handling them in fromApp is the way to go.
You can read more about message cracking here: QuickFIX/J User Manual - Receiving Messages.
I'll outline both ways:
In fromApp
Messages coming in fromApp are not of specific message types as defined in the QuickFIX/J library, but are of type quickfix.Message. If you wanted to process them the way you are doing now (from fromApp), you would have to inspect the MsgType manually:
MsgType msgType = (MsgType) message.getHeader( ).getField( new MsgType( ) );
Based on the type retrieved, you would call a handler method for the specific message type:
if( msgType.valueEquals( MsgType.MARKET_DATA_SNAPSHOT_FULL_REFRESH ) )
handleMarketDataSnapshotFullRefresh( message, sessionID );
else if ...
...
private void handleMarketDataSnapshotFullRefresh( quickfix.Message msg, SessionID sessionID ) {
// handler implementation
}
Using MessageCracker
Another way to handle incoming messages as mentioned before, is through a MessageCracker. You would e.g. extend the class that implements quickfix.Application with quickfix.MessageCracker.
Add an onMessage method with two parameters, first being the message type, second a SessionID. Call crack from the fromApp method which will route to the appropriate handler.
import quickfix.*;
public class MyApplication extends MessageCracker implements Application
{
public void fromApp(Message message, SessionID sessionID)
throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue {
crack(message, sessionID);
}
#Handler
public void onMessage(quickfix.fix44.MarketDataSnapshotFullRefresh mdsfr, SessionID sessionID) {
// handler implementation
}
}
Why are you doing the message processing in the wrong place ? If you check what is recommended by Quickfix you will see they recommend message processing happens in onMessage (which you might not have implemented). And there should only exist a message cracker in fromApp method.
Or else your fromApp method is going to be a hotchpotch of code and the next person handling your code is not going to be a happy soul.

GWT requestfactory: How to catch the exception i thrown in Locator at server side?

At client side:
factory.find(proxyId).fire(new Receiver<P>()
{
#Override
public void onSuccess( P response )
{
proxy = response;
...
}
#Override
public void onFailure( com.google.web.bindery.requestfactory.shared.ServerFailure error )
{
Window.alert( error.getMessage() );
}
}
at server side i use an Locator like below:
public class myLocator extends Locator<T, String>
{
#Injector LocatorHook hook;
#Override
public T find( Class<? extends T> clazz, String id )
{
T result = ...;
hook.run( result );
return result;
}
....
}
The hook.run() method may throwRunTimeException("validation exception") there, i expect to catch the
exception at client side in onFailure(), however, i did catch the exception, but the message is "Internal Server Error",
not the exception i thrown in hook.run():"validation exception".
Any ideas to let client catch the exception i throw at server side?
Updation:
As Thomas said it's weird that validating objects that come fresh from data store, but i encounter a
situation that i don't know how to use service method:
At client i get EntityProxyId object, through the factory.find( proxyId ).fire(...) i can get the entity
from datastore, but the entity may not suitable for the user to access, in this situation i need to check it at server side, but i can't find a suitable place to do the
validation, Any ideas about this?
RequestFactory doesn't expect exceptions to be thrown by locators. Exceptions should only be thrown by service methods, and will be directed to the appropriate Receiver on the client-side (the one attached to the service method that threw).
Outside service methods, the only exceptions that gets routed to the client are ReportableExceptions, that can only be thrown from a ServiceLocatorDecorator's report() methods. That means you could hook your own ServiceLocatorDecorator that catches exceptions from your locators and report()s them.
That said, validating objects that come fresh from your data store seems weird. You might want to provide a ServiceLocatorDecorator that overrides validate() (that'll validate the objects after the changes coming from the client have been applied). The errors will go back to the client in the Receiver's onConstraintViolations, and the RequestContext will be unfrozen so you can further edit your proxies and fire() again.

Gwt RequestFactory: editing a proxy immediately after receiving it

I want to RequestContext.edit(anObject) immediately after I receive it in Receiver.onSuccess, so that I can put it in my client-side database as already editable. Unfortunately, when I do so, RequestFactory complains that a request is already in progress. How can I achieve this?
requestContext.findOrganization(id).fire(new Receiver<OrganizationProxy>()
{
public void onSuccess(OrganizationProxy response)
{
database.put(requestContext.edit(response)); //fails because a request is already in progress
}
});
I resolved this by using a disposable request context to create the request, and then using my more-permanent request context to edit the object:
temporaryRequestContext.findOrganization(id).fire(new Receiver<OrganizationProxy>()
{
public void onSuccess(OrganizationProxy response)
{
database.put(permanentRequestContext.edit(response)); //succeeds because it has not been fired, even though edit() has been called many times
}
});