java.lang.NullPointerException what I'm doing wrong?

807 views Asked by At

I'm working on a project in which my intention is to run a Corn job and send mail to my friends to wishing them on their birthday, I was able to get email from MySQL DB and compared it to the current date but when it comes to sending an email I'm getting NullPointerException.

I'm sure there is no problem with application properties I used them with other projects as well and they are function properly

//Imports
package dev.teja.happybirthday;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.persistence.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.Email;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;

//Main
@SpringBootApplication
public class HappybirthdayApplication {
    public static void main(String[] args) {
        SpringApplication.run(HappybirthdayApplication.class, args);
    }
    @Autowired
    MyFriendsRepository myFriendsRepository ;
    @Scheduled(cron = "*/30 * * * * *")
    void WishMyFriends() {
        List<MyFriends> myFriendsList = myFriendsRepository.findAll();
        myFriendsList.forEach(friend -> {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
            String CurrentDate= formatter.format(date);
            String GivenDate = formatter.format(friend.dob);
            if (GivenDate.equals(CurrentDate)){
                Job job = new Job();
                Map<String, Object> model = new HashMap<>();
                model.put("Name",friend.name);
                job.sendWish(friend.email,model);
            }
        });
    }
}
@Configuration
@ConditionalOnProperty(name = "scheduling.enabled", matchIfMissing = true)
@EnableScheduling
class Tasks {
}
//Model
@Data
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
class MyFriends {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
    String name;
    @Email
    @Column(unique = true)
    String email;
    @JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
    Date dob;
    Long phoneNumber;
}
//Repository
interface MyFriendsRepository extends JpaRepository<MyFriends, Long> {
}
@RestController
@RequestMapping("/")
class FriendsController {
    @Autowired
    MyFriendsRepository myFriendsRepository;
    @PostMapping("/friends")
    ResponseEntity<MyFriends> createFriend(@RequestBody MyFriends myFriend) {
        myFriendsRepository.save(myFriend);
        return new ResponseEntity<MyFriends>(myFriend, HttpStatus.CREATED);
    }
    @GetMapping("/friends")
    List<MyFriends> getFriends() {
        return myFriendsRepository.findAll();
    }
}
//Interface
interface wisher{
    void sendWish(String email, Map<String, Object> model);
}
//Implementation
@Service
class Job implements wisher{
    @Autowired
    private JavaMailSender sender;
    @Autowired
    private freemarker.template.Configuration config;
    @Override
    public void sendWish(String email,Map<String, Object> model) {
        System.out.println("wishes sent to "+ email);
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                    StandardCharsets.UTF_8.name());
            Template template = config.getTemplate("new-template.ftl");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            helper.setTo(email);
            helper.setFrom("[email protected]");
            helper.setSubject("Happy Birthday");
            helper.setText(html,true);
            sender.send(message);
        } catch (MessagingException | IOException | TemplateException e) {
            e.printStackTrace();
        }
    }
}

Friends Table

FreeMaker file in ./resources/Templates

/**
 * FREEMAKER new-template.ftl
 * <html xmlns="http://www.w3.org/1999/xhtml">
 * <head>
 *     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 *     <title>Comment Alert Mail</title>
 * </head>
 * <body>
 * <p>happy birthday ${Name}</p>
 * </body>
 */

This is the error I'm getting this following


Hibernate: select myfriends0_.id as id1_0_, myfriends0_.dob as dob2_0_, myfriends0_.email as email3_0_, myfriends0_.name as name4_0_, myfriends0_.phone_number as phone_nu5_0_ from my_friends myfriends0_
wishes sent to [email protected]
2020-09-26 21:01:52.012 ERROR 84242 --- [   scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task

java.lang.NullPointerException: null
    at dev.teja.happybirthday.Job.sendWish(HappybirthdayApplication.java:115) ~[classes/:na]
    at dev.teja.happybirthday.HappybirthdayApplication.lambda$WishMyFriends$0(HappybirthdayApplication.java:53) ~[classes/:na]
    at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_251]
    at dev.teja.happybirthday.HappybirthdayApplication.WishMyFriends(HappybirthdayApplication.java:44) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_251]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_251]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_251]
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) [spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_251]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_251]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_251]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [na:1.8.0_251]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_251]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_251]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_251]

2

There are 2 answers

0
Guilherme Faria On

Try add getting in the @Autowired private JavaMailSender sender;

0
Angshuman On

I think you have not implemented your JavaMailSender bean. Define a bean like below. Then your @Autowire annotation will work.

@Bean
public JavaMailSender getJavaMailSender() 
{
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(25);
      
    mailSender.setUsername("[email protected]");
    mailSender.setPassword("password");
      
    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");
      
    return mailSender;
}