Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to send E-mail to a Group in Java using Java Mail API ?.

Program to demonstrate how to send E-mail to a Group in Java using Java Mail API.

package com.hubberspot.email.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailToGroupDemo {

 public static void main(String[] args) {

  // Create a SendEmail object and call start 
  // method to send a mail in Java.
  SendEmailToGroupDemo sendEmailToGroup = new SendEmailToGroupDemo();
  sendEmailToGroup.start();

 }

 private void start() {

  // For establishment of email client with 
  // Google's gmail use below properties.
  // For TLS Connection use below properties
  // Create a Properties object 
  Properties props = new Properties();

  // these properties are required
  // providing smtp auth property to true
  props.put("mail.smtp.auth", "true");
  // providing tls enability
  props.put("mail.smtp.starttls.enable", "true");
  // providing the smtp host i.e gmail.com
  props.put("mail.smtp.host", "smtp.gmail.com");
  // providing smtp port as 587
  props.put("mail.smtp.port", "587");

  // For SSL Connection use below properties

  /*props.put("mail.smtp.host", "smtp.gmail.com");
   props.put("mail.smtp.socketFactory.port", "465");
   props.put("mail.smtp.socketFactory.class",
     "javax.net.ssl.SSLSocketFactory");
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.port", "465");*/

  // Create Scanner object to take necessary 
  // values from the user.
  Scanner scanner = new Scanner(System.in);

  System.out.println("Please provide your Username for Authentication ...");
  final String Username = scanner.next();

  System.out.println("Please provide your Password for Authentication ...");
  final String Password = scanner.next();

  System.out.println("Please provide Email Address from which you want to send Email ...");
  final String fromEmailAddress = scanner.next();

  System.out.println("Please provide Email Addresses to which you want to send Email ...");
  System.out.println("If you are done type : Done or done");

  // ArrayLists to store email addresses entered by user
  ArrayList< String> emails = (ArrayList< String >) getEmails();

  System.out.println("Please provide Subject for your Email ... ");
  final String subject = scanner.next();

  System.out.println("Please provide Text Message for your Email ... ");
  final String textMessage = scanner.next();

  // Create a Session object based on the properties and 
  // Authenticator object
  Session session = Session.getDefaultInstance(props, 
    new LoginAuthenticator(Username,Password));

  try {

   // Create a Message object using the session created above
   Message message = new MimeMessage(session);

   // setting email address to Message from where message is being sent
   message.setFrom(new InternetAddress(fromEmailAddress));

   // setting the email addressess to which user wants to send message 
   message.setRecipients(Message.RecipientType.BCC, getEmailsList(emails));

   // setting the subject for the email 
   message.setSubject(subject);

   // setting the text message which user wants to send to recipients
   message.setText(textMessage);

   // Using the Transport class send() method to send message 
   Transport.send(message);

   System.out.println("\nYour Message delivered successfully ....");

  } catch (MessagingException e) {

   throw new RuntimeException(e);

  }  
 }

 // This method takes a list of email addresses and 
 // returns back an array of Address by looping the 
 // list one by one and storing it into Address[]
 private Address[] getEmailsList(ArrayList< String > emails) {

  Address[] emaiAddresses = new Address[emails.size()];

  for (int i =0;i < emails.size();i++) {
   try {
    emaiAddresses[i] = new InternetAddress(emails.get(i));
   }
   catch (AddressException e) {

    e.printStackTrace();
   }
  }
  return emaiAddresses;
 }

 // This method prompts user for email group to which he
 // wants to send message
 public List< String > getEmails() {
  ArrayList< String > emails = new ArrayList< String >();

  int counter = 1;
  String address = "";
  Scanner scanner = new Scanner(System.in);

  // looping inifinitely times as long as user enters 
  // emails one by one
  // the while loop breaks when user types done and 
  // press enter.
  while(true) {

   System.out.println("Enter E-Mail : " + counter);
   address = scanner.next();

   if(address.equalsIgnoreCase("Done")){
    break;
   }
   else {
    emails.add(address);
    counter++;
   }
  }

  return emails;
 }
}

// Creating a class for Username and Password authentication
// provided by the user.
class LoginAuthenticator extends Authenticator {
 PasswordAuthentication authentication = null;

 public LoginAuthenticator(String username, String password) {
  authentication = new PasswordAuthentication(username,password);
 }

 @Override
 protected PasswordAuthentication getPasswordAuthentication() {
  return authentication;
 }
}


Output of the program :



How to implement After Returning Advice using Classic Spring Proxy-Based AOP in Java ?.

A simple application to demonstrate how to implement After Returning Advice using Classic Spring Proxy-Based AOP in Java.

Scenario 1 ....

Step 1:- Subtraction.java Interface

 

package com.hubberspot.classic.aop.afterreturningadvice;

// Its a simple interface for the Subtraction service.
// It contains one single method called as subtract().
// This method takes in two arguments both of the type
// int.

public interface Subtraction {

 public void subtract(int a , int b);

}




Step 2:- SubtractionImpl.java Service Implementation Class

 package com.hubberspot.classic.aop.afterreturningadvice;

 // It is the implementation class for the 
 // Subtraction service. It just calculates and returns 
 // subtraction of two numbers passed to it as arguments.

 public class SubtractionImpl implements Subtraction {

  @Override
  public int subtract(int a, int b) {

   if(a > b) {

    return (a-b);

   }
   else {

    return (b-a);

   }

  }

 }




Step 3:- After Returning Advice Implementation class

package com.hubberspot.classic.aop.afterreturningadvice;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

// This class is a simple After Returning Advice which implements 
// interface called as AfterReturningAdvice. This interface 
// has a method by name afterReturning(). This advice method is 
// called just before the subtract() method in the SubtractionImpl
// class. It just outputs to the console a simple message.

public class AfterReturningSubtractAdvice implements AfterReturningAdvice {

 // afterReturning() method has to be implemented in this advice class.
 // It takes in four parameters:
 // 1. Object which holds the value returned from the method invoked
 // 2. java.lang.reflect.Method object which refers to the method
 // to which the Advice is applied.
 // 3. A simple array of Objects that are the arguments which are
 // passed to the method which is been implemented in the service
 // class. 
 // 4. The target object on which the method is been called.

 @Override
 public void afterReturning(Object returnValue, Method method, Object[] args,
   Object target) {

  System.out.println("Subtraction of two numbers done .... ");

 }

}




Step 4 :- Spring Configuration file


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">


<!-- After Returning Advice:- Advice is been configured as beans -->
<bean id="afterReturningSubtract"
class="com.hubberspot.classic.aop.afterreturningadvice.AfterReturningSubtractAdvice" />

<!-- Implementation Class -->
<bean id="subtractImpl"
class="com.hubberspot.classic.aop.afterreturningadvice.SubtractionImpl" />

<!-- Proxy Implementation Class:- This configuration binds advices to the 
 implementation code using a proxy factory bean. In order to apply the advice 
 final bean has to be proxied. Spring's ProxyFactoryBean is a factory that 
 creates a proxy which implies one or more interceptors to bean -->
<bean id="subtract" class="org.springframework.aop.framework.ProxyFactoryBean">
 
<!-- This proxy bean definition has three properties 
  
 1. target :- It tells ProxyFactoryBean to which bean it will be 
 making proxy. 

 2. intercepterNames :- Interceptor Names property is configured 
 as a list of interceptor or advices which is being applied to 
 this proxy. 
  
 3. proxyInterfaces :- It just tells to ProxyFactoryBean that 
 which interface Proxy bean has to implement. 
  
 -->
 
 
 <property name="target">
  <ref bean="subtractImpl" />
 </property>

 <property name="interceptorNames">
  <list>
   <value>afterReturningSubtract</value>
  </list>
 </property>

 <property name="proxyInterfaces">
  <value>com.hubberspot.classic.aop.afterreturningadvice.Subtraction
  </value>
 </property>
 </bean>
</beans>


Step 5:- Test class

package com.hubberspot.classic.aop.afterreturningadvice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SubtractionTest {

 public static void main(String[] args) {

  ApplicationContext context = 
    new ClassPathXmlApplicationContext("after_returning_advice.xml");
  Subtraction subtract = (Subtraction)context.getBean("subtract");

  int result = subtract.subtract(10, 6);

  System.out.println("Result = " + result);

  result = subtract.subtract(5, 10);

  System.out.println("Result = " + result);



 }

}





Output of the program : 




















Scenario 2 .... Changes done only to step 2 and 4 in previous scenario

Step 2:- SubtractionImpl.java Service Implementation Class

package com.hubberspot.classic.aop.afterreturningadvice;


public class SubtractionImpl implements Subtraction {

 @Override
 public void subtract(int a, int b) {



  if(a > b) {

   System.out.println((a-b));

   throw new RuntimeException();

  }
  else {

   System.out.println((b-a));

   throw new RuntimeException();

  }
 }

}




Step 4:- Test class

package com.hubberspot.classic.aop.afterreturningadvice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SubtractionTest {

 public static void main(String[] args) {

  ApplicationContext context = 
    new ClassPathXmlApplicationContext("after_returning_advice.xml");
  Subtraction subtract = (Subtraction)context.getBean("subtract");

  subtract.subtract(10, 6);
  subtract.subtract(5, 10);





 }

}


Output of the program :
 

 

How to implement After Advice using @AspectJ Annotation-Driven AOP in Java ?.

A simple application to demonstrate how to implement After Advice using @AspectJ Annotation-Driven AOP in Java.

Step 1:- Create a Interface Sum.java

package com.hubberspot.aspectj.annotation.afteradvice;

// Its a simple interface for the Sum service.
// It contains one single method called as addition().
// This method takes in two arguments both of the type
// int.
public interface Sum {

 public int addition(int a , int b);

}



Step 2:- SumImpl.java Service Implementation Class

package com.hubberspot.aspectj.annotation.afteradvice;

// It is the implementation class for the 
// Sum service. It just calculates and returns 
// sum of two numbers passed to it as arguments.

public class SumImpl implements Sum {

 @Override
 public int addition(int a, int b) {
  System.out.println("Addition method called ...");
  return (a + b);

 }

}




Step 3:- After Advice Implementation class

package com.hubberspot.aspectj.annotation.afteradvice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;

//@Aspect annotation treats this Java class as 
//Aspect. Its not ordinary POJO class.

@Aspect
public class AfterSumAdvice {

 // Method after() is a after advice
 // implemented by providing @After annotation.
 // This annotation takes in Pointcut expression, which 
 // indicates when this advice executes.
 // This Pointcut expression tells that after() advice
 // will execute addition method of Sum interface.
 // The after advice takes in JoinPoint which here represents
 // method execution.

 @After("execution(* com.hubberspot.aspectj.annotation.afteradvice.Sum.addition(..))")
 public void after(JoinPoint joinPoint) {

  System.out.println("Call after addition method ...");

 }

}




Step 4 :- Spring Configuration file


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:aop="http://www.springframework.org/schema/aop"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">

   <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

     <!-- Implementation Class -->
     <bean id="sum" class="com.hubberspot.aspectj.annotation.afteradvice.SumImpl" />

     <bean id="afterAdvice"
 class="com.hubberspot.aspectj.annotation.afteradvice.AfterSumAdvice" />

</beans>



Step 5:- Test class

package com.hubberspot.aspectj.annotation.afteradvice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SumTest {

 public static void main(String[] args) {

  // ApplicationContext is a Spring interface which 
  // provides with the configuration for an application. 
  // It provides us with all the methods that BeanFactory 
  // provides. It loads the file resources in a older 
  // and generic manner. It helps us to publish events to the
  // listener registered to it. It also provides quick support
  // for internationalization. It provides us with the object 
  // requested, it reads the configuration file and provides
  // us with the necessary object required.
  // We are using concrete implementation of AbstractApplicationContext
  // here called as ClassPathXmlApplicationContext because this 
  // bean factory reads the xml file placed in the classpath of 
  // our application. We provide ClassPathXmlApplicationContext
  // with a configuration file called as before_advice.xml placed
  // at classpath of our application. 

  ApplicationContext context = 
    new ClassPathXmlApplicationContext("after_advice.xml");

  // In order to get a object instantiated for a particular bean 
  // we call getBean() method of ClassPathXmlApplicationContext
  // passing it the id for which the object is to be needed. 
  // Here getBean() returns an Object. We need to cast it back 
  // to the Sum object. Without implementing new keyword we 
  // have injected object of Sum just by reading an xml 
  // configuration file.

  Sum sum = (Sum)context.getBean("sum");

  int result = sum.addition(5, 10);

  System.out.println("Result = " + result);


 }

}


Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot