About Gal Levinsky

Graduated B.s.c Information System Engineering on BGU University (2004). Been working on large cloud based ERP application in SAP for 7 years and as a development group manager in affiliation company. Co-founded few startups in the domain of social web.

Email filtering using Aspect and Spring Profile

During web application development, often the need for sending emails arise.

However, sometimes the database is populated by data from production and there is a risk of sending emails to real customers during email test execution.

This post will explain how to avoid it without explicitly write code in the send email function.

We would use 2 techniques:

  1. Spring Profiles – a mechanism to indicate what the running environment is (i.e. development, production,..)
  2. AOP – in simplified words its a mechanism to write additional logic on methods in decoupled way.

I would assume you already have Profiles set on your projects and focus on the Aspect side.

In that example the class which sends emails is EmailSender with the method send, as specified below:

public class EmailSender {
//empty default constructor is a must due to AOP limitation
public EmailSender() {}

//Sending email function
//EmailEntity - object which contains all data required for email sending (from, to, subject,..)
public void send(EmailEntity emailEntity) {
//logic to send email
}
}

Now, we will add the logic which prevent sending email to customers where code is not running on production.
For this we will use Aspects so we won’t have to write it in the send method and by that we would maintain the separation of concern principle.

Create a class that will contain the filtering method:

@Aspect
@Component
public class EmailFilterAspect {

public EmailFilterAspect() {}
}

Then create a PointCut for catching the send method execution:

@Pointcut("execution(public void com.mycompany.util.EmailSender.send(..))")
 public void sendEmail(){}

Since we need to control whether the method should be executed or not, we need to use the Arround annotation.

@Around("sendEmail()")
public void emailFilterAdvice(ProceedingJoinPoint proceedingJoinPoint){
 try {
  proceedingJoinPoint.proceed(); //The send email method execution
 } catch (Throwable e) {                           
  e.printStackTrace();
 }
}

As a last point, we need to access the send method input parameter (i.e. get the EmailEntity) and verify we don’t send emails to customers on development.

@Around("sendEmail()")
 public void emailFilterAdvice(ProceedingJoinPoint proceedingJoinPoint){

 //Get current profile
ProfileEnum profile = ApplicationContextProvider.getActiveProfile();

Object[] args = proceedingJoinPoint.getArgs();        //get input parameters
        if (profile != ProfileEnum.PRODUCTION){
            //verify only internal mails are allowed
            for (Object object : args) {
                if (object instanceof EmailEntity){
                    String to = ((EmailEntity)object).getTo();
                    if (to!=null && to.endsWith("@mycompany.com")){//If not internal mail - Dont' continue the method                        
                        try {
                            proceedingJoinPoint.proceed();
                        } catch (Throwable e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }else{
            //In production don't restrict emails
            try {
                proceedingJoinPoint.proceed();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
}

That’s it.
Regarding configuration, you need to include the aspect jars in your project.
In Maven it’s look like this:

                    
                   
                     org.aspectj
                     aspectjrt
                     ${org.aspectj.version}
                   
                    
                   
                     org.aspectj
                     aspectjweaver
                     ${org.aspectj.version}
                     runtime
                   

and in your spring application configuration xml file, you need to have this:

Good luck!

Reference: Email filtering using Aspect and Spring Profile from our JCG partner Gal Levinsky at the Gal Levinsky’s blog blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


one × 8 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.