How can you manage user notification in spring boot

Posted By : Prakhar Verma | 31-Jan-2018

Notification is used for giving a small unit of information to anyone.

Most of the web-based application has some kinds of users and each user performs some activities which depend on the application.

For example => if you have a wallet based application then you inform each user regarding his activities like

(if any deposit is performed by user then we gives a notification to user on his deposit and any withdraw is performed by user then you gives notification to user).

you can implement and manage notification in spring boot by using these steps.

1. Create an Entity Notification in java with some attributes

    these are given below    

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

import com.oodles.domain.user.User;
import com.oodles.util.ObjectHash;

@Entity
public class Notification {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Integer notificationId;
	
	private String message;
	
	private Date createdAt;
	
	private boolean isRead;
	
	@ManyToOne
	private User user;
	
	public Notification(){}
	
	public Notification(String message,Date createdAt,User user){
		this.message = message;
		this.createdAt = createdAt;
		this.user = user;
		this.isRead = false;
	}


	public Integer getNotificationId() {
		return notificationId;
	}

	public void setNotificationId(Integer notificationId) {
		this.notificationId = notificationId;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Date getCreatedAt() {
		return createdAt;
	}

	public void setCreatedAt(Date createdAt) {
		this.createdAt = createdAt;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public boolean isRead() {
		return isRead;
	}

	public void setRead(boolean isRead) {
		this.isRead = isRead;
	}

}

 

2. In Notification, entity create many to one relation with the user because the user has multiple notifications.
 
3. Create a service class for notification named "NotificationService."
 
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.oodles.domain.AuthenticationToken;
import com.oodles.domain.Notification;
import com.oodles.domain.Req_UpdateNotitfication;
import com.oodles.domain.user.User;
import com.oodles.repository.NotificationRepository;
import com.oodles.service.token.AuthTokenService;
import com.oodles.util.KYCUtilities;
import com.oodles.util.MessageUtility;
import com.oodles.util.ObjectMap;

@Service
public class NotificationService {

	@Autowired
	private NotificationRepository notificationRepository;


	private static final Logger logger = LoggerFactory.getLogger(NotificationService.class);

	public NotificationService(){}

	public Map<String,Object> updateUserNotification(Notitfication notitfication,User user){

                notification = save(notification);
		if(notification == null){
			return KYCUtilities._errorMultipleObject(MessageUtility.getErrorMessage("NotificationNotUpdated"), HttpStatus.INTERNAL_SERVER_ERROR);
		}
         
		return KYCUtilities._successMultipleObject(ObjectMap.objectMap(notification),MessageUtility.getSuccessMessage("NotificationUpdated"));
	}

	public Notification save(Notification notification){
		try{
			return notificationRepository.save(notification);
		}catch (Exception e) {
			logger.error("Exception occur while save Notification ",e);
			return null;
		}
	}


	public Notification findByUser(User user){
		try{
			return notificationRepository.findByUser(user);
		}catch (Exception e) {
			logger.error("Exception occur while fetch Notification by User ",e);
			return null;
		}
	}

	public List<Notification> findByUser(User user,Integer limit){
		try{
			return notificationRepository.userNotification(user.getUid(), new PageRequest(0, limit));
		}catch (Exception e) {
			logger.error("Exception occur while fetch Notification by User ",e);
			return null;
		}
	}

	public Notification createNotificationObject(String message,User user){
		return new Notification(message,new Date(),user);
	}

	public Notification findByUserAndNotificationId(User user,Integer notificationId){
		try{
			return notificationRepository.findByUserAndNotificationId(user,notificationId);
		}catch (Exception e) {
			logger.error("Exception occur while fetch Notification by User and Notification Id ",e);
			return null;
		}
	}

}

4. Notification service is used to provide services like save and updated notification into database,

    and fetch user notifications.

5. Create JpaRepository for performed database related operation corrresponding to notification.

import java.util.List;

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.oodles.domain.Notification;
import com.oodles.domain.user.User;

@Repository
public interface NotificationRepository extends JpaRepository<Notification,Integer> {

	Notification findByUser(User user);

	@Query("select n from Notification n where n.user.uid=:userId ORDER BY n.createdAt DESC")
	List<Notification> userNotification(@Param("userId") Integer userId,Pageable pageSize);

	Notification findByUserAndNotificationId(User user,Integer notificationId);
	
}

6. Create a Notification controller for expose api's for fetch user notification.

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.oodles.constant.KYCConstants;
import com.oodles.domain.AuthenticationToken;
import com.oodles.domain.Notification;
import com.oodles.domain.Req_UpdateNotitfication;
import com.oodles.domain.user.User;
import com.oodles.service.NotificationService;
import com.oodles.service.token.AuthTokenService;
import com.oodles.util.Activity;
import com.oodles.util.KYCUtilities;
import com.oodles.util.MessageUtility;
import com.oodles.util.ObjectMap;
import com.oodles.util.ResponseUtil;

import io.swagger.annotations.ApiOperation;

@RestController
public class NotificationController {

	@Autowired
	private NotificationService notificationService;

	private static Logger logger=LoggerFactory.getLogger(NotificationController.class);

	public NotificationController(){}

	@RequestMapping(value="/notifications/user",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<Object> getNotificationsByUser(@RequestParam(required=false,defaultValue="") String limit){

		logger.debug("inside getNotificationsByUser api for fetch user notification ");
		Integer intLimit = KYCUtilities.parseIntoInteger(limit);
		
		if(intLimit == null){
			return ResponseUtil.errorResponse(MessageUtility.getErrorMessage("IntLimit"),HttpStatus.BAD_REQUEST);
		}
		
		User user = notificationService.getLoggedInUser();

		List<Notification> notifications = notificationService.findByUser(user, intLimit);

		Map<String,Object> response = new HashMap<String,Object>();
		response.put("notifications", ObjectMap.objectMap(notifications));
		response.put("user", ObjectMap.objectMap(user,"email"));
		
		return ResponseUtil.response(response, MessageUtility.getSuccessMessage("NotificationFethced"), HttpStatus.OK);
	}

	@RequestMapping(value="/notifications/user",method=RequestMethod.PATCH,produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<Object> updateUserNotification(@RequestHeader(@Valid @RequestBody Req_UpdateNotitfication reqUpdateNotitfication){

		logger.debug("inside updateUserNotification api ");
		Map<String,Object> response = notificationService.updateUserNotification(reqUpdateNotitfication,reqUpdateNotitfication.getUser());
		
		if((boolean)response.get("error") == true){
			return ResponseUtil.errorResponse(response.get("message").toString(),(HttpStatus)response.get("status"));
		}

		return ResponseUtil.response(response.get("data"),response.get("message").toString(),HttpStatus.OK);	
	}

}

 

7. "getNotificationByUser" method is used for return user notifications and "updateUserNotification"

     method is used for update state of notification like its readed or not.

Request for Proposal

Recaptcha is required.

Sending message..