Wednesday, November 24, 2021

Java Stream - findAny() With Examples

In Java Stream API findAny() method is used to return some element of the stream. Method returns the element as an Optional or an empty Optional if the stream is empty.

Syntax of the Stream.findAny() method is as follows-

Optional<T> findAny()

findAny() is a short-circuiting terminal operation meaning it may terminate in finite time when presented with infinite input.

The element of the Stream returned by findAny() is random in nature though in most of the case it returns the first element of the stream just like findFirst() method but this behavior is not guaranteed.

Java Stream findAny() examples

1. An example to get some element from a Stream of Integers.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamFindAny {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(3, 9, 1, 9, 7, 8);
    Optional<Integer> anyNumFromStream = list.stream().findAny();
    if(anyNumFromStream.isPresent()) {
      System.out.println("Element in the Stream- " + anyNumFromStream.get());
    }else {
      System.out.println("No element found");
    }
  }
}

Output

Element in the Stream- 3

2. You can also use findAny() method along with other Stream operations to get any element from the resultant stream. For example using filter method to filter out elements which are less than 5 and then getting any element from the resultant stream.

public class StreamFindAny {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(3, 2, 6, 2, 7, 8);
    list.stream()
      .filter(e -> e > 5)
      .findAny()
      .ifPresent(System.out::println);
  }
}

Output

6

That's all for this topic Java Stream - findAny() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - findFirst() With Examples
  2. Java Stream - max() With Examples
  3. collect() Method And Collectors Class in Java Stream API

You may also like-

  1. Adding Tomcat Server to Eclipse
  2. JVM Run-Time Data Areas - Java Memory Allocation
  3. Types of JDBC Drivers
  4. Java ArrayBlockingQueue With Examples
  5. What Are JVM, JRE And JDK in Java
  6. How to Read Input From Console in Java
  7. Angular First App - Hello world Example
  8. Spring Component Scan to Automatically Discover Beans

Tuesday, November 23, 2021

Java Stream - findFirst() With Examples

In Java Stream API, findFirst() method is used to find the first element of this stream. Method returns the first element as an Optional or an empty Optional if the stream is empty.

Syntax of the Stream.findFirst() method is as follows-

Optional<T> findFirst()

findFirst() is a short-circuiting terminal operation meaning it may terminate in finite time when presented with infinite input.

Java Stream findFirst() examples

1. An example to get first element from a Stream of Integers.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamFindFirst {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(3, 9, 1, 9, 7, 8);
    Optional<Integer> firstNumFromStream = list.stream().findFirst();
    if(firstNumFromStream.isPresent()) {
      System.out.println("First Element in the Stream- " + firstNumFromStream.get());
    }else {
      System.out.println("No element found");
    }
  }
}

Output

First Element in the Stream- 3

2. You can also use findFirst() method along with other Stream operations to get the first element from the resultant stream. For example using filter method to filter out elements which are less than 3 and then getting the first element from the resultant stream.

public class StreamFindFirst {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(3, 9, 1, 9, 7, 8);
    Optional<Integer> firstNumFromStream = list.stream()
                           .filter(e -> e > 3)
                           .findFirst();
    if(firstNumFromStream.isPresent()) {
      System.out.println("First Element in the Stream- " + firstNumFromStream.get());
    }else {
      System.out.println("No element found");
    }
  }
}

Output

First Element in the Stream- 9

3. Using with Stream of strings. In the example findFirst() is used to get the first name that starts with “M”.

public class StreamFindFirst {

  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Andy", "Mona", "Vikram", "Jenny", "Meena");
    Optional<String> firstName = nameList.stream()
                           .filter(e -> e.startsWith("M"))
                           .findFirst();
    if(firstName.isPresent()) {
      System.out.println("First Element in the Stream- " + firstName.get());
    }else {
      System.out.println("No element found");
    }
  }
}

Output

First Element in the Stream- Mona

That's all for this topic Java Stream - findFirst() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - findAny() With Examples
  2. Java Stream - min() With Examples
  3. Java Stream - limit() With Examples
  4. Java Stream API Interview Questions And Answers

You may also like-

  1. forEach Statement in Java 8
  2. Java Lambda Expression as Method Parameter
  3. HashSet Vs LinkedHashSet Vs TreeSet in Java
  4. Multi-Catch Statement in Java Exception Handling
  5. Java Program to Reverse a Number
  6. Spring Bean Life Cycle
  7. Namespace And Variable Scope in Python
  8. Angular Pipes With Examples

Monday, November 22, 2021

Java Stream - min() With Examples

In Java Stream API there is a min() method that is used to get the minimum element of this stream according to the provided Comparator. In this post we’ll see some examples of the min() method.

Syntax of the Stream.min() method

min is a terminal operation and its syntax is as given below-

Optional<T> min(Comparator<? super T> comparator)

Here comparator argument is an implementation of the Comparator to compare elements of this stream.

Method returns an Optional describing the minimum element of this stream, or an empty Optional if the stream is empty.

Stream.min is considered a special case of a reduction operation as it takes a sequence of input elements and combines them into a single summary result.

min() method Java examples

1. Finding min value from a stream of numbers.

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamMin {
  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 9, 14, 1, 59, 23, 77, 10, 12, 4);
      Optional<Integer> minElement = numList.stream().min(Integer::compare);
      if(minElement.isPresent()){
        System.out.println("Minimum element: " + minElement.get());
      }
  }
}

Output

Minimum element: 1

2. In the following example custom comparator is passed as an argument to the min() method to get minimum method as per the passed Comparator.

public class StreamMin {
  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 9, 14, 1, 59, 23, 77, 10, 12, 4);
      Optional<Integer> minElement = numList.stream().min(new MyComparator());
      if(minElement.isPresent()){
        System.out.println("Minimum element: " + minElement.get());
      }
  }
}

class MyComparator implements Comparator<Integer>{
  @Override
  public int compare(Integer o1, Integer o2) {
    return o1.compareTo(o2);
  }
}

Output

Minimum element: 1

3. Using Stream.min() method with custom object. In the example, objects of Employee class are used and the objective is to find minimum salary using the min() method of the Java Stream API.

Employee class used is as given here.

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
}

In the example mapToInt() method is used to get the salary part of the employee object which is then passed to the min() to get the minimum salary.

public class StreamMin {
  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E003", 24, "Mark", 'M', 9000), 
                new Employee("E004", 37, "Rani", 'F', 10000),
                new Employee("E005", 32, "Anuj", 'M', 12000));  
     OptionalInt minEmpSal = empList.stream()
                .mapToInt(Employee::getSalary)
                .min();
      if(minEmpSal.isPresent()){
        System.out.println("Minimum salary: " + minEmpSal.getAsInt());
      }
  }
}

Output

Minimum salary: 5000

That's all for this topic Java Stream - min() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - max() With Examples
  2. Java Stream - filter() With Examples
  3. Java Stream - distinct() With Examples
  4. Java Stream - findFirst() With Examples
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. How to Sort ArrayList of Custom Objects in Java
  2. equals() And hashCode() Methods in Java
  3. Type Casting in Java With Conversion Examples
  4. StringJoiner Class in Java With Examples
  5. Writing a File Asynchronously Java Program
  6. Spring Integration With Quartz Scheduler
  7. Operator Overloading in Python
  8. Angular Access Control CanActivate Route Guard Example

Sunday, November 21, 2021

Multiple Catch Blocks in Java Exception Handling

There might be a case when a code enclosed with in a try block throws more than one exception. To handle these types of situations, multiple catch blocks can be specified where each catch clause catches a different type of exception. When an exception is thrown, every catch statement is inspected in order, and the first one whose type matches that of the thrown exception is executed.

After one of the catch statement, out of the multiple catch blocks, executes the others are bypassed and execution continues after the try-catch block.

Notice that with Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Refer Multi catch statement in Java 7 to read more about it.

Multiple catch blocks Java example

In this program there is an array with only one element which is zero. From main method when calculateValue method is called a parameter is passed which is used as an index of the array.

First time 0 is passed which will mean divide by a[0]. Since the value at that index is 0 thus it will result in divide by 0 and ArithmeticException will be thrown.

Next time 2 is passed but array has only one element so trying to access a[2] will result in ArrayIndexOutOfBoundsException.

In the code there are multiple catch blocks and both of these exceptions will be caught by separate catch blocks.

public class MultipleCatchDemo {
  private void calculateValue(int i){
    int a[] = {0};
    try{
      int b = 7/a[i];
    }catch(ArithmeticException aExp){
      aExp.printStackTrace();
    }catch(ArrayIndexOutOfBoundsException aiExp){
      aiExp.printStackTrace();
    }
  }

  public static void main(String[] args) {
    MultipleCatchDemo mcDemo = new MultipleCatchDemo();
    mcDemo.calculateValue(0);
    mcDemo.calculateValue(2);
  }
}

Output

java.lang.ArithmeticException: / by zero
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:21)
java.lang.ArrayIndexOutOfBoundsException: 2
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:22)

Restriction with Multiple catch blocks in Java

When multiple catch blocks are used in Java, it is important to follow the order where the exception sub type is caught before any of their super type. Which means a catch block that catches an exception subclass must come before the catch clause that catches an exception super class.

As example– With in the Java exception handling hierarchy Exception class is super class and ArithmeticException is the child class so catch block for Exception class will catch an ArithmeticException too. Thus placing the catch block for Exception class before the catch block for ArithmeticException would mean that the catch block for ArithmeticException is never reached.

Note that in Java, unreachable code is an error so this situation will result in a compiler error.

In the same code as used above if one more catch block for Exception is added as the first one, that will result in compiler error.

multiple catch blocks

That's all for this topic Multiple Catch Blocks in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Best Practices For Exception Handling in Java
  2. Creating Custom Exception Class in Java
  3. throws Keyword in Java Exception Handling
  4. Try-With-Resources in Java With Examples
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. Difference Between Abstract Class And Interface in Java
  2. Inheritance in Java
  3. How to Loop Through a Map in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Difference Between Thread And Process in Java
  6. Thread Priority in Java Multi-Threading
  7. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  8. Varargs (Variable-length Arguments) in Java

Saturday, November 20, 2021

Object Creation Using new Operator in Java

In OOP a class provides the blueprint for objects; you create an object from a class. When a new class is created essentially a new data type is created. This type can be used to declare objects of that type. In this post we'll see what all happens when an object is created using new operator in Java.

Creating Objects in Java

Creation of an object for a class in Java is done in three steps-

  • Declaration- Declare a variable of the class type, note that no object is defined yet. This variable can refer to an object as and when the object is created.
  • Instantiation- Create an object and assign it to the variable created in step 1. This object creation is done using new operator.
  • Initialization- Class name followed by parenthesis after the new operator (new classname()) means calling the constructor of the class to initialize the object.

General form of using new operator by combining all these three steps is as-

Class_Name class_Variable = new Class_Name();

Here Class_Name is the class whose object is created and class_Variable is the variable that refers to the created object. Here note that when you refer Class_Name followed by parenthesis, you are actually calling the constructor of the class to initialize the object. That constructor may be a constructor with arguments or a no-argument constructor (or default constructor).

Let’s go through the steps of declaration, instantiation and initialization-

Declaring a Variable to Refer to an Object

When you just declare a variable no memory is allocated for it. As example if you declare a variable obj of class Test-

Test obj;

What you have done here is to notify the Java compiler that you will use obj to refer to data whose type is Test.

At this stage, when you have just declared the variable obj, it doesn’t refer to an object. Actually its value is undetermined at this time. To create an object you need to use the new operator in Java. You must assign an object to obj variable before you use it in your code. Otherwise, you will get a compiler error.

A variable in this state, which currently has no reference to any object can be pictorially represented as follows-

object declaration in Java
Object declaration

Instantiating a Java Class

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

The new operator requires a single, postfix argument: a call to a constructor and it returns the refrence to the object it created. This reference is usually assigned to a variable of the appropriate type, As example

Test obj = new Test(9, 10);

Initializing an Object in Java

The last step is to initialize an object. This is the process where constructor of the class is called to initialize the object.

As example-

If we have a Test class as follows-

public class Test{
  public int x = 0;
  public int y = 0;
  //constructor
  public Test(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

This class contains a single constructor which takes two integer arguments, in order to initialize a object created using new operator you can have a statement as follows-

Test obj = new Test(9, 10);

Here you have a variable obj of type Test, using new operator you have created a new object of class Test and initialized it to have values 9 and 10 for variables x and y respectively. So, this instantiation of class Test has its variables initialized to 9 and 10 i.e. obj.x = 9 and obj.y = 10.

obj is the variable that refers to the object.

If we have to pictorially represent this instantiation and initialization, it will look as follows.

Initializing an Object in Java
Initializing an Object

That's all for this topic Object Creation Using new Operator in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Package in Java
  2. Access Modifiers in Java - Public, Private, Protected and Default
  3. Abstraction in Java
  4. Difference Between Abstract Class And Interface in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Association, Aggregation and Composition in Java
  2. Initializer block in Java
  3. String in Java Tutorial
  4. Nested Try Statements in Java Exception Handling
  5. Generics in Java
  6. Map operation in Java Stream API
  7. How HashMap Works Internally in Java
  8. How ArrayList Works Internally in Java

Friday, November 19, 2021

Check if Given String or Number is a Palindrome Java Program

This post is about writing a Java program to find that a given string or number is a palindrome or not.

Remember a String or a number is a palindrome if it remains unchanged when reversed, for example "madam" is a palindrome as reverse of the madam is again madam. Another example is "malayalam" or 12344321.


Logic for finding if String palindrome or not

Here three ways are given to check whether given string is a palindrome or not in Java. First 2 ways use the inbuilt String functions to do that.

In the first method checkPalindrome1(), StringBuilder class instance is used which is instantiated using the given String, then the inbuilt reverse method of the StringBuilder is used. If the given string is a palindrome then reverse of the string should be same as the original string.

Second method checkPalindrome2() is same as the first method, it works on the logic that the second half of the string is the mirror image of the first half so if second half of the string is reversed then it should be same as the first half.
As example: If we have a string 12344321 then the second half 4321 if reversed will become 1234 which is equal to the first half, thus string is a palindrome.
In this logic whether a given string is of even length or odd length matters. That's why the ternary operator while creating the StringBuilder object.

index + index == str.length() ? str.substring(index) : str.substring(index + 1)

Third method checkPalindrome3() doesn't use any inbuilt function. In this method we start from the end of the string and read one character at a time to create a new String. Now if a given string is a palindrome then the new string should be equal to the original string.

Given String palindrome or not Java program

public class Palindrome {
  public static void main(String[] args) {
    Palindrome pm = new Palindrome();
    pm.checkPalindrome1("DogeeseseeGod");
    pm.checkPalindrome2("malayalam");
    pm.checkPalindrome3("1234442");
  }
    
  private void checkPalindrome1(String str){            
    StringBuilder sb = new StringBuilder(str);
    // reverse the string and check if it is equal to original 
    // string
    if(str.equalsIgnoreCase(sb.reverse().toString())){
      System.out.println(str + " is a Palindrome");
    }else{
      System.out.println(str + " is not a Palindrome");
    }        
  }
    
  /**
  * In a palindrome one half of the string is the mirror image of the other
  * this logic is based on that
  * @param str
  */
  private void checkPalindrome2(String str){        
    int index = str.length()/2;        
    StringBuilder sb = new StringBuilder(index + index == str.length() 
          ? str.substring(index) : str.substring(index + 1));
    if(str.substring(0, index).equalsIgnoreCase(sb.reverse().toString())){
      System.out.println(str + " is a Palindrome");
    }else{
      System.out.println(str + " is not a Palindrome");
    }        
  }        
    
  /**
  * If no inbuilt function has to be used.
  * 
  * @param str
  */
  private void checkPalindrome3(String str){
    StringBuilder sb = new StringBuilder();
    // start reading the string backward
    for(int i = str.length() - 1; i >= 0; i--){
      sb.append(str.charAt(i));
    }            
    System.out.println("string 3 " + sb.toString());
    if(str.equalsIgnoreCase(sb.toString())){
      System.out.println(str + " is a Palindrome");
    }else{
      System.out.println(str + " is not a Palindrome");
    }    
  }
}

Output

DogeeseseeGod is a Palindrome
malayalam is a Palindrome
string 3 2444321
1234442 is not a Palindrome

Java program to check if number palindrome or not

Though we can convert number to string and use any of the above mentioned methods to verify if given number is a palindrome or not but in a scenario where we have to do it for number this program can be used.

public class PalindromeNumber {

  public static void main(String[] args) {
    PalindromeNumber pm = new PalindromeNumber();
    pm.checkNumberPalindrome(12344321);
    pm.checkNumberPalindrome(12322);
  }
 
  /**
  * To check for integers
  * @param num
  */
  private void checkNumberPalindrome(int num){
    int reverse = 0;
    int remainder;
    int originalNum = num;
    // reversing the number
    while (num > 0) {
      remainder = num % 10;
      reverse = (reverse * 10) + remainder;
      num = num / 10;
    }
    if(reverse == originalNum){
      System.out.println(originalNum + " is a Palindrome");
    }else{
      System.out.println(originalNum + " is not a Palindrome");
    }
  }
}

Output

12344321 is a Palindrome
12322 is not a Palindrome

That's all for this topic Check if Given String or Number is a Palindrome Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Find The Longest Palindrome in The Given String
  2. Check Given Strings Anagram or Not Java Program
  3. Count Number of Words in a String Java Program
  4. Add Double Quotes to a String Java Program
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program

You may also like-

  1. Find Largest and Second Largest Number in Given Array Java Program
  2. Method Overloading in Java
  3. Encapsulation in Java
  4. Race Condition in Java Multi-Threading
  5. Callable and Future in Java With Examples
  6. Java ReentrantLock With Examples
  7. How HashMap Works Internally in Java
  8. Dependency Injection in Spring Framework

Thursday, November 18, 2021

Spring Email Scheduling Example Using Quartz Scheduler

In this post we’ll see a Spring email scheduling example using Quartz scheduler integration with Spring framework.

Spring Mail API is used to configure Java mail for sending email.

Spring Quartz integration facilitates the use of Quartz for job scheduling.

Technologies Used

  • Spring 5.0.8.Release
  • Java 10
  • Java Mail API
  • Quartz Scheduler

Maven Dependencies

You need to add following dependencies for sending mail using Quartz scheduler in Spring framework.

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <spring.version>5.0.8.RELEASE</spring.version>
</properties>

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>3.8.1</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>        
  </dependency> 
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
  </dependency>  
  <!-- Spring module Required for Quartz integration -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
     <groupId>com.sun.mail</groupId>
     <artifactId>javax.mail</artifactId>
     <version>1.6.1</version>
  </dependency>

  <dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.6.1</version>
  </dependency>
  <dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.0</version>
  </dependency>
  <dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
  </dependency>     
</dependencies>

Spring email scheduling example using Quartz scheduler

In this Spring email scheduling example reminder mail is sent to a set of Users everyday at the scheduled time. For scheduling the mail to be triggered at the specific time Quartz scheduler is used.

Bean class (User.java)

public class User {

  private String firstName;
  private String lastName;
  private String email;

  public User() {
   
  }
  public User(String firstName, String lastName, String email) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.email = email;
  }
  
  public String getFirstName() {
   return firstName;
  }
  public void setFirstName(String firstName) {
   this.firstName = firstName;
  }
  public String getLastName() {
   return lastName;
  }
  public void setLastName(String lastName) {
   this.lastName = lastName;
  }
  public String getEmail() {
   return email;
  }
  public void setEmail(String email) {
   this.email = email;
  }
}

Spring email scheduling example – Quartz Job class

Quartz scheduler job that would be called at the configured time. This class uses the EmailService class for sending the email. Here a dummy list of Users is created and EmailService method is called for each user in the list once the job is triggered.

@Service
public class MailReminderJob extends QuartzJobBean {
  private EmailService emailService;
  public void setEmailService(EmailService emailService) {
    this.emailService = emailService;
  }
  @Override
  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    System.out.println("In executeInternal");
    List<User> userList = getListOfUsers();
    for(User user : userList) {
      emailService.sendMail(user);
    }
  }
    
  // Dummy method for adding List of Users
  private List<User> getListOfUsers() {
    List<User> users = new ArrayList<User>();
    users.add(new User("Jack", "Reacher", "jr@gmail.com"));
    users.add(new User("Remington", "Steele", "rs@gmail.com"));  
    return users;
  }
}

Spring email scheduling example – Mail Service class

Class used for sending the mails. This class get the mail properties like From and Subject from a properties file email.properties which is stored in the application’s classpath. MimeMessageHelper is used here so that attachment can also be sent with the email.

EmailService.java

@Service("emailService")
@Configuration
@PropertySource("classpath:email.properties")
public class EmailService {
 @Autowired
 private Environment env;
 @Autowired
 private JavaMailSender mailSender;

 public void sendMail(User user) {
  System.out.println("In Send mail");
  try{
   MimeMessage message = mailSender.createMimeMessage();
   // use the true flag to indicate you need a multipart message
   MimeMessageHelper helper = new MimeMessageHelper(message, true);
   helper.setFrom(env.getProperty("email.From"));
   // each user's email ID
   helper.setTo(user.getEmail());
   helper.setSubject(env.getProperty("email.Subject"));
   helper.setText("Dear " + user.getFirstName() + " " +user.getLastName()
   + "\r\n" + "This is a reminder mail to go through the attached PDF.");
   helper.addInline("Inline image", new ClassPathResource("netjs.png"));
   helper.addAttachment("MyImage.png", new ClassPathResource("netjs.png"));
   helper.addAttachment("MyPdf.pdf", new FileSystemResource("F:\\Doc\\index.pdf"));
  
   this.mailSender.send(message);
  }
  catch (MessagingException ex) {
   // just printing
   System.out.println(ex.getMessage());
  }
 }
}

email.properties

email.To=TO@gmail.com
email.From=FROM@gmail.com
email.Subject=Reminder Mail

Spring email scheduling example – Scheduling Configuration

The job is configured here to run at 8 AM everyday.

CronTrigger is used here for triggering the job using the implementation CronTriggerFactoryBean provided by the Spring framework for Quartz scheduling.

Trigger is scheduled using a SchedulerFactoryBean that exposes triggers to be set as properties.

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
  <context:component-scan base-package="org.netjs.service" />
  <!-- Mail related configuration -->
  <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="587"/>
    <property name="username" value="GMAIL_USER_NAME"/>
    <property name="password" value="PASSWORD"/>
    <property name="javaMailProperties">
      <props>
        <prop key="mail.transport.protocol">smtp</prop>
        <prop key="mail.smtp.auth">true</prop>
        <prop key="mail.smtp.starttls.enable">true</prop>
        <prop key="mail.debug">true</prop>
      </props>
    </property>
  </bean>
  <!-- Quartz scheduler related configuration -->
  <bean name="emailReminderJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="org.netjs.service.MailReminderJob"/>
    <property name="jobDataAsMap">
      <map>
        <entry key="emailService" value-ref="emailService"></entry>
      </map>
    </property>
  </bean>

  <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
    <property name="jobDetail" ref="emailReminderJob"/>
    <!-- run every morning at 8 AM -->
    <property name="cronExpression" value="0 0 8 * * ?"/>
  </bean>
  <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
      <list>
        <ref bean="cronTrigger"/>
      </list>
    </property>
  </bean>
</beans>

To run this example you can use the following class.

public class App {
  public static void main( String[] args ){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");

  }
}

That's all for this topic Spring Email Scheduling Example Using Quartz Scheduler. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC JSON as Response Example
  2. Spring Transaction Management Example - @Transactional Annotation and JDBC
  3. Spring Batch Processing Using JDBCTemplate batchUpdate() Method
  4. Spring Component Scan Example
  5. How to Read Properties File in Spring Framework

You may also like-

  1. Run Time Injection Using Spring Expression Language(SpEL)
  2. Excluding Bean From Autowiring in Spring
  3. BeanFactoryPostProcessor in Spring Framework
  4. Spring Web MVC Tutorial
  5. Difference Between Comparable and Comparator in Java
  6. How to Display Time in AM-PM Format in Java
  7. Java Collections Interview Questions And Answers
  8. Tips For Improving MapReduce Performance