All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.infusers.core.audit.AuditService Maven / Gradle / Ivy

There is a newer version: 2024.12.0008
Show newest version
package com.infusers.core.audit;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import com.infusers.core.logger.ILogger;
import com.infusers.core.reports.IReportService;
import com.infusers.core.util.InfusersUtility;

import jakarta.servlet.http.HttpServletRequest;

@Service
public class AuditService implements IReportService {
	
	private final Logger log = LogManager.getLogger(AuditService.class);
	private static final String CLASS_NAME = "AuditService";	

	@Autowired(required = true)
	private AuditRepository auditRepository;
	
    @Autowired
    private InfusersUtility infusersUtility;
	
	@Override
	public Page findAll(Specification spec, Pageable pageable) {
		return auditRepository.findAll(spec, pageable);
	}
	
	@Override
	public Page findAll(Pageable pageable) {
	    Page auditPage = auditRepository.findAll(pageable);
	    return auditPage.map(customerOrder -> (Object) customerOrder);
	}	
	
	@Override	
	public Page findByUserName(String userName, Pageable pageable) {
		Page auditPage = auditRepository.findByUserEmailId(userName, pageable);	
	    return auditPage.map(customerOrder -> (Object) customerOrder);		
	}
		
	private ResponseEntity createAuditRecord(AuditRecord auditRecord) {
		log.debug(CLASS_NAME+".createAuditRecord() Creating new audit record, audit id = ", auditRecord.getId());
		
		try {

			AuditRecord savedAuditRecord = auditRepository.save(auditRecord);
			URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedAuditRecord.getId())
					.toUri();
	
			return ResponseEntity.created(location).build();
		
		}
		catch(Exception e) {
			log.error(CLASS_NAME+".createAuditRecord() Creation of new audit record Failed!! auditRecord = ", auditRecord+" :: error = "+e.getMessage());
			return null;
		}
	}

    public boolean log(ILogger callerLogger, ILogger.LogTypes logType, String entityName, String action, String entityId, String comments) {
    	if(callerLogger!=null) {
    		callerLogger.log(logType, String.format("entityName = %s :: action = %s :: entityId = %s :: comments: %s", entityName, action, entityId, comments));
    	}
    	AuditRecord auditLog = new AuditRecord(infusersUtility.getLoggedInUserNameForAudit(),  entityName,  action, entityId, comments);
    	if(!auditLog.isValidExcludingId()) {
    		log.warn(CLASS_NAME+".log() AuditRecord is not valid, ignoring :: "+auditLog);    	    		
    		return false;
    	}
    	ResponseEntity createdLog = this.createAuditRecord(auditLog);
    	return createdLog!=null;
    }    
	
    public boolean log(HttpServletRequest httpRequest) {
		return log(null, ILogger.LogTypes.DEBUG, httpRequest.getRequestURI(), httpRequest.getMethod(), "", cleanQueryString(httpRequest));    	
    } 
    
    private String cleanQueryString(HttpServletRequest request) {
        String queryString = request.getQueryString();
        if (queryString == null) {
            return null;
        }
        
        try {
            // Decode the URL-encoded string
            String decodedString = URLDecoder.decode(queryString, "UTF-8");

            // Remove unnecessary characters (for example, newlines, or unwanted symbols)
            // This regex removes any character that is not a letter, number, space, or specific allowed symbols
            String cleanedString = decodedString.replaceAll("[^a-zA-Z0-9\\s:,.!]", "");

            return cleanedString;
        } 
        catch (UnsupportedEncodingException e) {
            return queryString;
        }
    }    
}