How to use Error code description in java using Enum

package com.prj.exception;

public enum ErrorCodeDescription {

/** The unauthorized user. */
UNAUTHORIZED_USER(1000, “Invaild User Name or Password”),
/** Generic error */
ERROR_GENERIC(2000, “Service Un-Available”), ERROR_FK_CONSTRAINT(2001, “Cannot Delete or Update the record.”),
/** The error code. */
private int errorCode;

/** The error description. */
private String errorDescription;

/**
* Instantiates a new error code description.
*
* @param code
* the code
* @param description
* the description
*/
private ErrorCodeDescription(int code, String description) {

this.errorCode = code;
this.errorDescription = description;
}

/**
* Gets the error code.
*
* @return the error code
*/
public int getErrorCode() {
return errorCode;
}

/**
* Gets the error description.
*
* @return the error description
*/
public String getErrorDescription() {
return errorDescription;
}

/**
* This method returns description for the given error code
*
* @param code
* – input error code
* @return String – description
*/
public static String getDescription(int code) {
for (final ErrorCodeDescription codes : values()) {
if (codes.getErrorCode() == code) {
return codes.getErrorDescription();
}
}
return null;
}

/**
* This method returns description for the given error code
*
* @param code
* – input error code
* @return ErrorCodeDescription
*/
public static ErrorCodeDescription getErrorCodeDesc(int code) {
for (final ErrorCodeDescription codes : values()) {
if (codes.getErrorCode() == code) {
return codes;
}
}
return null;
}
}
===================================
to use this enum :

emailRequest.setErrorCode(ErrorCodeDescription.ERROR_GENERIC);
emailRequest.setErrorDesc(ErrorCodeDescription.ERROR_GENERIC.getErrorDescription());


 

Advertisements

How to get the response object using @AfterReturning

@Pointcut(“execution(* com.prj.service.*.*(..))”)
private void afterPointCut() {
// Nothing to be implement
}
@AfterReturning(value=”afterPointCut()”,
returning=”baseDto”)
public void runAfter(JoinPoint joinPoint, BaseDto baseDto) throws Throwable {
log.info(“Inside RunAfterExecution.afterReturning() method…”);
log.info(“inserted after : ” + joinPoint.getSignature().getName());
log.info(“Method returned value is : ” + baseDto.toString());
}

AuditLogging flow using spring

 

1)take a model :

package com.prj.model;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.prj.util.JsonDateSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import lombok.Data;
import lombok.ToString;

@Entity
@Data
@Table(name = “audit_log”)
@ToString
public class AuditLog implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;

/*Created User Name */
@Column(name=”user_Id”, length=30, nullable=true)
String userId;

/*Created Status Code */
@Column(name=”status_code”, length=30, nullable=false)
int statusCode;

/*Created Method Name */
@Column(name=”method_name”, length=30, nullable=false)
String methodName;

/*Created Date */
@Column(name=”create_date”, nullable=false)
@JsonSerialize(using = JsonDateSerializer.class)
Date createDate;

/*Last Updated User Name */
@Column(name=”last_updated_userId”, length=30, nullable=true)
String lastUpdatedUserId;

/*Last Updated Date */
@Column(name=”last_updated_date”, nullable=true)
@JsonSerialize(using = JsonDateSerializer.class)
Date lastUpdatedDate;

}
2)create a AuditLoggingController :

package com.prj.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.prj.dto.BaseDto;
import com.prj.model.AuditLog;
import com.prj.service.AuditLogService;

import lombok.extern.log4j.Log4j;

@RestController
@RequestMapping(value=”/auditlog”)
@Log4j
public class AuditLogController {

/**
* AuditLogService
*/
@Autowired
AuditLogService auditLogService;
/**
* Method get
*
* @param ID
* Description RestAPI to get auditLog by id
*/
@RequestMapping(value = “/get/id/{id}”, method = RequestMethod.GET)
public BaseDto get(@PathVariable Long id) {
log.info(“auditLogController get by id method called.”);
return auditLogService.get(id);
}
/**
* Method Save
*
* @param AuditLog
* Description RestAPI to Save auditLog
*/
@RequestMapping(value = “/create”, method = RequestMethod.POST)
public BaseDto create(@RequestBody AuditLog auditLog) {
log.info(“auditLogController create method called.”);
return auditLogService.create(auditLog);
}

/**
* Method Update
*
* @param AuditLog
* Description RestAPI to Update auditLog
*/
@RequestMapping(value = “/update”, method = RequestMethod.POST)
public BaseDto update(@RequestBody AuditLog auditLog) {
log.info(“AuditLogController update method called.”);
return auditLogService.update(auditLog);
}

/**
* Method Delete
*
* @param auditLog
* Description RestAPI to Delete auditLog
*/
@RequestMapping(value = “/delete/{id}”, method = RequestMethod.DELETE)
public BaseDto delete(@PathVariable(“id”) Long id) {
log.info(“AuditLogControler delete method called.”);
return auditLogService.delete(id);
}

}
3)create a AuditLoggingService :

package com.prj.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.prj.common.component.CacheRepository;
import com.prj.dto.BaseDto;
import com.prj.exception.BadRequestException;
import com.prj.exception.ErrorCodeDescription;
import com.prj.exception.InvalidParameterFormatException;
import com.prj.exception.RestException;
import com.prj.model.AuditLog;
import com.prj.repository.AuditLogRepository;
import com.prj.util.SaaSUtil;

import lombok.extern.log4j.Log4j;
@Service
@Log4j
public class AuditLogService {

/*
*
* AuditLog Master Repository autowired
*/
@Autowired
AuditLogRepository auditLogRepository;

@Autowired
CacheRepository cacheRepository;

/**
* Method – get
*
* @param id
* AuditLog id
* @return baseDto
*/

public BaseDto get(Long id) {

log.info(“get method is called….[” + id + “]”);

BaseDto baseDto = new BaseDto();

try {

AuditLog auditLog = cacheRepository.get(SaaSUtil.getSaaSId(), AuditLog.class.getName(), id,
auditLogRepository);

//ValidateUtil.notNull(auditLog, ErrorCodeDescription.AUDIT_LOG_ID_NOT_FOUND);

log.info(“Successfully getting AuditLog by id…[” + auditLog.getId() + “]”);

baseDto.setResponseCode(ErrorCodeDescription.SUCCESS.getErrorCode());

baseDto.setResponseObject(auditLog);

} catch (RestException exception) {

log.error(“Exception in get method… “, exception);

String errorCode = exception.getMessage().split(” “)[0];

baseDto.setResponseCode(Integer.parseInt(errorCode));

} catch (Exception exception) {

log.error(“Exception in get method : “, exception);

baseDto.setResponseCode(ErrorCodeDescription.FAILED.getErrorCode());
}

return baseDto;
}

/**
* create – This method creates a new carrier
*
* @Param AuditLog master entity
*
* @Return BaseDto
*/

public BaseDto create(AuditLog auditLog) {

log.info(“Create method is called…..[” + auditLog.getId() + “]”);

BaseDto baseDto = new BaseDto();

try {

auditLogRepository.save(auditLog);

log.info(“carrier Saved successfully…..”);

baseDto.setResponseCode(ErrorCodeDescription.SUCCESS.getErrorCode());

baseDto.setResponseObject(auditLog);

} catch (BadRequestException bre) {

log.error(“BadRequestException Occured with error code “, bre);

String errorCode = bre.getMessage().split(” “)[0];

baseDto.setResponseCode(Integer.parseInt(errorCode));

} catch (InvalidParameterFormatException ipfe) {

log.error(“InvalidParameterFormatException Occured with error code “, ipfe);

String errorCode = ipfe.getMessage().split(” “)[0];

baseDto.setResponseCode(Integer.parseInt(errorCode));
} catch (DataIntegrityViolationException dve) {

log.error(“Exception occured”, dve);

String exceptionCause1 = dve.getCause().getCause().getMessage();

log.error(“Exception Cause 1 ::: ” + exceptionCause1);

// General error condition
baseDto.setResponseCode(ErrorCodeDescription.ERROR_GENERIC.getErrorCode());

if (exceptionCause1.contains(“UK_AUDIT_LOGMASTER_AUDIT_LOGCODE”)) {
//baseDto.setResponseCode(ErrorCodeDescription.AUDIT_LOG_CODE_ALREADY_EXIST.getErrorCode());
} else if (exceptionCause1.contains(“UK_AUDIT_LOGMASTER_AUDIT_LOGNAME”)) {
//baseDto.setResponseCode(ErrorCodeDescription.AUDIT_LOG_NAME_ALREADY_EXIST.getErrorCode());
} else if (exceptionCause1.contains(“UK_AUDIT_LOGMASTER_AUDIT_LOGNO”)) {
// baseDto.setResponseCode(ErrorCodeDescription.AUDIT_LOG_NUM_ALREADY_EXIST.getErrorCode());
}

} catch (RestException exception) {

log.error(“RestException in Create method : “, exception);

String errorCode = exception.getMessage().split(” “)[0];

baseDto.setResponseCode(Integer.parseInt(errorCode));

} catch (Exception exception) {

log.error(“Exception in Create method : “, exception);

baseDto.setResponseCode(ErrorCodeDescription.FAILED.getErrorCode());
}

return baseDto;
}

/*
* Update- This method updates a existing carrier
*
* @Param AuditLog master entity
*
* @Return BaseDto
*/
@Transactional
public BaseDto update(AuditLog existingAuditLog) {
log.info(“update method is called….”);
BaseDto baseDto = new BaseDto();
try {
/*AuditLog auditLog = cacheRepository.get(SaaSUtil.getSaaSId(), AuditLog.class.getName(),
existingAuditLog.getId(), auditLogRepository);

auditLog = cacheRepository.save(SaaSUtil.getSaaSId(), AuditLog.class.getName(), auditLog,
auditLogRepository);*/

AuditLog auditLogResponse = auditLogRepository.saveAndFlush(existingAuditLog);

log.info(“auditLogService updated successfully…”);
baseDto.setResponseCode(ErrorCodeDescription.SUCCESS.getErrorCode());
baseDto.setResponseObject(auditLogResponse);
return baseDto;
} catch (BadRequestException bre) {
log.error(“Exception occured”, bre);

String exceptionCause1 = bre.getCause().getCause().getMessage();

log.error(“Exception Cause 1 ::: ” + exceptionCause1);

// General error condition
baseDto.setResponseCode(ErrorCodeDescription.ERROR_GENERIC.getErrorCode());
}

return baseDto;
}
/*
* Delete- This method deletes a existing carrier
*
* @Param AuditLog master entity
*
* @Return BaseDto
*/

public BaseDto delete(Long id) {

log.info(“delete method is called….”);

BaseDto baseDto = new BaseDto();

try {

cacheRepository.delete(SaaSUtil.getSaaSId(), AuditLog.class.getName(), id, auditLogRepository);

log.info(“Successfully deleted AuditLog by id…”);

baseDto.setResponseCode(ErrorCodeDescription.SUCCESS.getErrorCode());

baseDto.setResponseObject(ErrorCodeDescription.SUCCESS.getErrorDescription());

} catch (RestException exception) {

log.error(“Exception in Create method : “, exception);

String errorCode = exception.getMessage().split(” “)[0];

baseDto.setResponseCode(Integer.parseInt(errorCode));
} catch (Exception exception) {

log.error(“Exception in Create method : ” + exception);

baseDto.setResponseCode(ErrorCodeDescription.FAILED.getErrorCode());
}
return baseDto;

}

}

4)create a reposotary :

package com.prj.repository;

import java.util.List;

import org.springframework.data.domain.Page;
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 com.prj.model.AuditLog;

public interface AuditLogRepository extends JpaRepository<AuditLog, Long> {

AuditLog findById(Long id);

AuditLog findByStatusCode(int statusCode);

AuditLog findByMethodName(String methodName);

@Override
@Query(“Select a from AuditLog a ORDER BY a.methodName ASC”)
List<AuditLog> findAll();

@Query(“Select a from AuditLog a where ( UPPER(a.methodName) like :keyword% or UPPER(a.methodName) like :keyword%) ORDER BY a.methodName ASC”)
Page<AuditLog> findByKeyword(@Param(“keyword”)String keyword, Pageable page);

}
5)create a LoggingUserActivityAspect :

package com.prj.aspect;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.prj.configuration.SessionRoutingDataSource;
import com.prj.exception.BadRequestException;
import com.prj.exception.ErrorCodeDescription;
import com.prj.model.AuditLog;
import com.prj.service.AuditLogService;

import lombok.extern.log4j.Log4j;

@Aspect
@Component
@Log4j

public class LoggingUserActivityAspect {

@Autowired
SessionRoutingDataSource sessionRoutingDataSource;

@Autowired
AuditLogRepository auditLogRepository;

@Autowired
private HttpSession httpSession;

@Autowired
private HttpServletResponse httpServletResponse;

@Autowired
private AuditLogComponent auditLogComponent;

@Value(“${newage.saas.based.application}”)
String saasBased;

@Pointcut(“execution(* com.prj.controller.*.*(..))”)
private void pointCut() {
// Nothing to be implement
}

@Pointcut(“execution(* com.prj.service.*.*(..))”)
private void pointCutAfterReturning() {
// Nothing to be implement
}

@Pointcut(“execution(* *(..)) &&(within(com.prj.controller..*) || within(com.prj.service..*))”)
private void auditLogExceptionAdvicePointCut() {
// Nothing to be implement
}

@Before(“pointCut()”)
public void beforeInit() {

ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();

String saas = null;

if (“1”.equals(saasBased)) {
HttpServletRequest request = servletContainer.getRequest();

saas = request.getHeader(“SAAS_ID”);

if (saas == null || saas.trim().length() == 0) {
log.error(“SAAS Id is Empty”);
throw new RestException(ErrorCode.SAAS_USER_EMPTY);
}

if (sessionRoutingDataSource.getSaasMap().get(saas) != null) {
sessionRoutingDataSource.setClientKey(saas);
} else {
log.error(“Invaild SAAS Id”);
throw new RestException(ErrorCode.SAAS_INVAILD_USER);
}

} else {
sessionRoutingDataSource.setClientKey(saas);
}

}

@Before(“pointCut()”)
public void insertAuditLogAdvice(JoinPoint joinPoint) {
log.info(“LoggingUserActivityAspect.insertAuditLog start.”);

try {

if (httpSession != null) {

String className = joinPoint.getTarget().getClass().getName();

String methodName = joinPoint.getSignature().getName();

AuditLog auditLog = new AuditLog();

auditLog.setCreateDate(new Date());
auditLog.setMethodName(methodName);
auditLog.setClassName(className);
auditLog.setUserName(AuthService.getCurrentUser().getUserName());

AuditLog auditLogResponse = auditLogComponent.create(auditLog);

// Storing AuditLog id in session
httpSession.setAttribute(methodName, auditLogResponse.getId());

} else {
log.info(“No session for the operation in “);
}

} catch (Exception e) {
log.debug(“Exception in loggingUserActivityAspect.insertAuditLog : ” + e);
}
log.info(“LoggingUserActivityAspect.insertAuditLog end.”);
}

@AfterThrowing(value = “auditLogExceptionAdvicePointCut()”, throwing = “error”)
public void auditLogExceptionAdvice(JoinPoint joinPoint, Throwable error) {

log.info(“LoggingUserActivityAspect.auditLogExceptionAdvice start.”);

log.info(“Exception inside method name : ” + joinPoint.getSignature().getName());

log.debug(“Exception : ” + error);

log.info(“LoggingUserActivityAspect.auditLogExceptionAdvice end.”);
}

@After(“pointCut()”)
public void updateAuditLogAdvice(JoinPoint joinPoint) {
log.info(“LoggingUserActivityAspect.updateAuditLog start.”);

try {

log.info(“joinPoint.getTarget().getClass() : ” + joinPoint.getTarget().getClass());

if (httpSession != null) {

String methodName = joinPoint.getSignature().getName();

// Getting AuditLog id in session
Long auditLogId = (Long) httpSession.getAttribute(methodName);
int ststusCode = (int) httpSession.getAttribute(methodName + “StatusCode”);
httpSession.removeAttribute(methodName);
httpSession.removeAttribute(methodName + “StatusCode”);
AuditLog auditLogToUpdate = auditLogRepository.getOne(auditLogId);

log.info(“auditLogResponse.getId() : ” + auditLogId);

auditLogToUpdate.setStatusCode(ststusCode);
auditLogToUpdate.setHttpResponseCode(httpServletResponse.getStatus());
auditLogToUpdate.setLastUpdatedDate(new Date());
auditLogToUpdate.setLastUpdatedUserName(AuthService.getCurrentUser().getUserName());

log.info(“auditLogToUpdate : ” + auditLogToUpdate);

auditLogComponent.update(auditLogToUpdate);

} else {
log.info(“No session for the operation.”);
}
} catch (Exception e) {
log.debug(“Exception in loggingUserActivityAspect.updateAuditLogAdvice : “, e);
}
log.info(“LoggingUserActivityAspect.updateAuditLog end.”);
}

@AfterReturning(value = “pointCutAfterReturning()”, returning = “baseDto”)
public void afterReturningAuditLogAdvice(JoinPoint joinPoint, com.prj.dto.BaseDto baseDto) {
log.info(“LoggingUserActivityAspect.afterReturningAuditLogAdvice start.”);

String methodName = joinPoint.getSignature().getName();

log.info(“The Method Name is : ” + methodName);

httpSession.setAttribute(methodName + “StatusCode”, baseDto.getResponseCode());

log.info(“LoggingUserActivityAspect.afterReturningAuditLogAdvice end.”);
}

}

why we are using private constructor in util file in java

Utility classes could have private constructors. Users of the classes should not be able to instantiate these classes:

public class AuthUtil {
 private AuthUtil() {
 // Exists only to defeat instantiation.
 }

 public static String genarateResetTokenKey() {
 log.info("AuthUtil.genarateResetTokenKey called.");
 String RandomStringUtilsInput = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 String resetTokenKey = RandomStringUtils.random(13, RandomStringUtilsInput);
 return resetTokenKey;
 }

}

Setting up a static IP address in Ubuntu

sudo vi /etc/network/interfaces

 

For our example lets say we want configure our network configuration to the following (This should work on most default networks, especially home networks)

Change the line iface eth0 inet dhcp to iface eth0 inet static and add the following just below it:

address 192.168.1.100 (IP address of what you want your Ubuntu machine to be)
netmask 255.255.255.0
(Default mask which in this case is the default class c subnet)
gateway 192.168.1.1  
(Typically your router’s IP address)
network 192.168.1.0 
(The network that this machine is running on)
broadcast 192.168.1.255
 (A message that is sent to all out network-attached hosts to essentially find a specific address. You also receive them from other hosts)
dns-nameservers 192.168.1.1
 (DNS or Domain Name Server used for responding to queries when you are searching for a website)

 

e.g-

=========================

auto eth0
iface eth0 inet static
address 192.168.50.94
netmask 255.255.255.0
gateway 192.168.1.1
network 192.168.1.0
broadcast 192.168.50.255
dns-nameservers 192.168.1.1k

==========================

Alternatively, for your dns-nameservers some people prefer to use Google’s Public DNS which is 8.8.8.8 or 8.8.4.4 you can easily swap 192.168.1.1 to one of Googles. You can find more information regarding Google Public DNS here.

 

Once you save this file you should restart your networking service.

sudo /etc/init.d/networking restart

or

sudo service networking restart

As you can see setting up a static IP address in Ubuntu is pretty straight forward!

If you have any issues setting up a static IP please comment here or make a post on our forums.