Only no-arg methods may be annotated with #Scheduled - spring

#Component
public class SaveProviderStartupRunner implements ApplicationRunner {
#Autowired
private ProviderController providerController;
#Autowired
private AttachmentEmail attachmentEmail;
String fileDate1 = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
LocalDate today = LocalDate.now();
String fileDate = (today.minusDays(1)).format(DateTimeFormatter.ofPattern("dd MMM"));
String fileDate2 = (today.minusMonths(1)).format(DateTimeFormatter.ofPattern("MMM"));
#Override
public void run(ApplicationArguments args) throws Exception {
providerController.saveCards();
}
//#Override
#Scheduled(cron = "26 17 * * * *")
public void run1(ApplicationArguments args) throws Exception {
attachmentEmail.sendMail1("SomeEmail#gmail.com", "SomeEmail2#gmail.com", "List for " + fileDate, " ", "Report " + fileDate1 + ".xlsx");
attachmentEmail.sendMail2("SomeEmail#gmail.com", "SomeEmail3#gmail.com", "List for " + fileDate, " ", "Report1 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail3("SomeEmail#gmail.com", "SomeEmail4#gmail.com", "List for " + fileDate, " ", "Report2 " + fileDate1 + ".xlsx");
}
#Scheduled(cron = "27 17 * * * *")
public void run2(ApplicationArguments args) throws Exception {
attachmentEmail.sendMail4("SomeEmail#gmail.com", "SomeEmail5#gmail.com", "List for " + fileDate, " ", "Report3 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail5("SomeEmail#gmail.com", "SomeEmail6#gmail.com", "List for " + fileDate, " ", "Report4 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail6("SomeEmail#gmail.com", "SomeEmail7#gmail.com", "List for " + fileDate, " ", "Report5 " + fileDate1 + ".xlsx");
}
#Scheduled(cron = "28 17 * * * *")
public void run3(ApplicationArguments args) throws Exception {
attachmentEmail.sendMail7("SomeEmail#gmail.com", "SomeEmail8#gmail.com", "List for " + fileDate, " ", "Report6 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail8("SomeEmail#gmail.com", "SomeEmail9#gmail.com", "List for " + fileDate, " ", "Report7 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail9("SomeEmail#gmail.com", "SomeEmail10#gmail.com", "List for " + fileDate, " ", "Report8 " + fileDate1 + ".xlsx");
}
}
My project has a method that starts saving to a .xlsx file. First, I want to separate them so that some files are saved at one time and others at another time. I tried to set up this method to run through Scheduled
#Override
#Scheduled(cron = "10 10 * * * *")
public void run(ApplicationArguments args) throws Exception {
providerController.saveCards();
}
However, I get an error, because in the parameters of the method I have (args), without which this method does not work. How do I set the Scheduler so that my method is called on time?

On run1(), run2() and run3() you don't need the ApplicationArguments args because the only method actually overriding ApplicationRunner.run(ApplicationArguments args) method, so just drop them. Additionally, I would keep it simple and simply separate the methods (the one overriding ApplicationRunner.run(ApplicationArguments args) method and the one that is scheduled):
#Component
public class SaveProviderStartupRunner implements ApplicationRunner {
#Autowired
private ProviderController providerController;
#Autowired
private AttachmentEmail attachmentEmail;
String fileDate1 = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
LocalDate today = LocalDate.now();
String fileDate = (today.minusDays(1)).format(DateTimeFormatter.ofPattern("dd MMM"));
String fileDate2 = (today.minusMonths(1)).format(DateTimeFormatter.ofPattern("MMM"));
#Override
public void run(ApplicationArguments args) throws Exception {
providerController.saveCards();
}
#Scheduled(cron = "10 10 * * * *")
public void run() throws Exception {
providerController.saveCards();
}
#Scheduled(cron = "26 17 * * * *")
public void run1() throws Exception {
attachmentEmail.sendMail1("SomeEmail#gmail.com", "SomeEmail2#gmail.com", "List for " + fileDate, " ", "Report " + fileDate1 + ".xlsx");
attachmentEmail.sendMail2("SomeEmail#gmail.com", "SomeEmail3#gmail.com", "List for " + fileDate, " ", "Report1 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail3("SomeEmail#gmail.com", "SomeEmail4#gmail.com", "List for " + fileDate, " ", "Report2 " + fileDate1 + ".xlsx");
}
#Scheduled(cron = "27 17 * * * *")
public void run2() throws Exception {
attachmentEmail.sendMail4("SomeEmail#gmail.com", "SomeEmail5#gmail.com", "List for " + fileDate, " ", "Report3 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail5("SomeEmail#gmail.com", "SomeEmail6#gmail.com", "List for " + fileDate, " ", "Report4 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail6("SomeEmail#gmail.com", "SomeEmail7#gmail.com", "List for " + fileDate, " ", "Report5 " + fileDate1 + ".xlsx");
}
#Scheduled(cron = "28 17 * * * *")
public void run3() throws Exception {
attachmentEmail.sendMail7("SomeEmail#gmail.com", "SomeEmail8#gmail.com", "List for " + fileDate, " ", "Report6 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail8("SomeEmail#gmail.com", "SomeEmail9#gmail.com", "List for " + fileDate, " ", "Report7 " + fileDate1 + ".xlsx");
attachmentEmail.sendMail9("SomeEmail#gmail.com", "SomeEmail10#gmail.com", "List for " + fileDate, " ", "Report8 " + fileDate1 + ".xlsx");
}
}

Related

How to write the Junit Mockito code for this Aspect class for maximum code coverage

Could someone please help me out in writing Junit for this piece of code and provide resources to learn the same. I have been trying to figure out from multiple resources but couldn't find anything. I need to mock the pointcuts and methods which are invoked within the pointcut. Is unit testing possible for this using Mockito
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.sample.api.rest.account.AccountResource;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.CustomLog;
import lombok.extern.slf4j.slf4j;
#Aspect
#CustomLog
public class sample {
ObjectMapper mapper = new ObjectMapper();
long startTimeController = 0L;
long endTimeController = 0L;
#Pointcut("within(com.sample.api.rest.account. .) || "
+ "within(com.sample.api.rest.metadata..') ")
public void entryController() {}
#Pointcut("within(com. sample.api.rest.user..*)")
public void entryControllerUser() {}
#Pointcut("within(com.sample.api.service. .*)")
public void entryService() {}
#Pointcut("within(com. sample.cmo.repositories..*)")
public void entryDAO() {}
#Before("entryController()")
public void beforeOtherControllerCall(JoinPoint jp) throws JsonProcessingException {
String methodName = jp.getSignature().getName();
String className = jp.getTarget().getClass().toString();
Object[] arguments = jp.getArgs();
log.info(className + " Method : " + methodName + " Arguments passed : " +
mapper.writeValueAsString(arguments));
startTimeController = System.currentTimeMillis();
}
#Before("entryControllerUser()")
public void beforeUserControllerCall(JoinPoint jp) throws JsonProcessingException {
String methodName = jp.getSignature().getName();
String className = jp.getTarget().getClass().toString();
log.info(className + " Method : " + methodName);
startTimeController = System.currentTimeMillis();
}
#After("entryController() || entryControlleruser()")
public void afterControllerCall(JoinPoint jp) throws JsonProcessingException {
endTimeController = System.currentTimeMillis();
String methodName = jp.getSignature().getName();
String className = jp.getTarget().getClass().toString();
log.info(className + " Method : " + methodName + " Values returned :");
if (endTimeController != 0) {
log.info("Time consumed in " + className + " " + methodName + " call is "
+ (endTimeController - startTimeController) + "ms");
}
}
#Around("entryService()")
public Object executionTimeService(ProceedingJoinPoint pjp) throws Throwable {
String methodName = pjp.getSignature().getName();
String className = pjp.getTarget().getClass().toString();
Object[] arguments = pjp.getArgs();
log.info(className + " Method: " + methodName + " Arguments passed :" +
mapper.writeValueAsString(arguments));
long startTime = System.currentTimeMillis();
Object obj = pip.proceed();
long endTime = System.currentTimeMillis();
log.info(className + " Method : " + methodName + " Execution time: " + (endTime -
startTime) + "ms");
log.info(className + " Method : " + methodName + " Response received : " +
mapper.writeValueAsString(obj));
return obj;
}
#Around("entryDAO()")
public Object executionTimeDAO(ProceedingJoinPoint pjp ) throws Throwable {
String methodName pjp.getSignature().getName();
String className pjp.getTarget().getClass().toString();
Object[] arguments = pjp.getArgs();
log.info(className+" Method : "+methodName+" Arguments passed :"
+mapper.writeValueAsString(arguments) );
long startTime = System.currentTimeMillis();
Object obj = pip.proceed();
long endTime = System.currentTimeMillis();
log.info(className+" method : " + methodName+" Execution time: "
+(endTime-start Time)+"ms" );
log.info(className+" Method: "+methodName+" Response received : "+
mapper.writeValueAsString(obj));
return obj;
}
}
Here is the sample of what I have tried with
#Test
public void testBeforeOtherControllerCall() throws Throwable{
JoinPoint joinPoint = mock(JoinPoint.class);
AspectLogging logging = mock(AspectLogging.class);
String[] args = {"arg1", "arg2"};
Object[] obj args)
Signature signature = mock (Signature.class);
when(joinPoint.getSignature().thenReturn(signature);
when(signature.getName().thenReturn("MethodName");
Object object = mock(Object.class);
when(joinPoint.getTarget().thenReturn(object);
when(object.getClass().thenReturn(objectClass);
when(joinPoint.getArgs().thenReturn(obj);
logging.beforeOtherControllerCali(joinPoint);
verify(joinPoint, times (1)).getSignature().getName().equals("MethodName");
}
Preface
When trying to recreate your situation, I had to
guess about which libraries and versions you use,
replace the Lombok logging annotation by a regularly created SLF4J logger, because, as the AspectJ compiler tells you in a warning message, Lombok's byte code modifications do not work with the AspectJ compiler: java: You aren't using a compiler supported by lombok, so lombok will not work and has been disabled. (...) Lombok supports: sun/apple javac 1.6, ECJ. When using Spring AOP instead, it probably works with Lombok, because there you are simply using the normal Java compiler. I however tested in native AspectJ.
fix many syntax errors in your aspect and test Java code as well as several syntax errors in your aspect pointcuts. The classes did not even compile and the aspect cannot have done anything meaningful with faulty pointcuts. If you modify original code in order to create a stand-alone example, please test before posting it. You should have a little bit more pride as a developer when presenting your work publicly. This was your free shot, because you are new on SO, but next time I will just close the question.
Please do read the MCVE article, try to understand it and ask better questions in the future.
Fixed aspect code
package de.scrum_master.aspect;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#Aspect
public class LoggingAspect {
private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);
ObjectMapper mapper = new ObjectMapper();
long startTimeController = 0L;
long endTimeController = 0L;
#Pointcut("within(com.sample.api.rest.account..*) || within(com.sample.api.rest.metadata..*)")
public void entryController() {}
#Pointcut("within(com.sample.api.rest.user..*)")
public void entryControllerUser() {}
#Pointcut("within(com.sample.api.service..*)")
public void entryService() {}
#Pointcut("within(com.sample.cmo.repositories..*)")
public void entryDAO() {}
#Before("entryController()")
public void beforeOtherControllerCall(JoinPoint jp) throws JsonProcessingException {
String methodName = jp.getSignature().getName();
String className = jp.getTarget().getClass().toString();
Object[] arguments = jp.getArgs();
log.info(className + " Method : " + methodName + " Arguments passed : " + mapper.writeValueAsString(arguments));
startTimeController = System.currentTimeMillis();
}
#Before("entryControllerUser()")
public void beforeUserControllerCall(JoinPoint jp) throws JsonProcessingException {
String methodName = jp.getSignature().getName();
String className = jp.getTarget().getClass().toString();
log.info(className + " Method : " + methodName);
startTimeController = System.currentTimeMillis();
}
#After("entryController() || entryControllerUser()")
public void afterControllerCall(JoinPoint jp) throws JsonProcessingException {
endTimeController = System.currentTimeMillis();
String methodName = jp.getSignature().getName();
String className = jp.getTarget().getClass().toString();
log.info(className + " Method : " + methodName + " Values returned :");
if (endTimeController != 0) {
log.info("Time consumed in " + className + " " + methodName + " call is " + (endTimeController - startTimeController) + "ms");
}
}
#Around("entryService()")
public Object executionTimeService(ProceedingJoinPoint pjp) throws Throwable {
String methodName = pjp.getSignature().getName();
String className = pjp.getTarget().getClass().toString();
Object[] arguments = pjp.getArgs();
log.info(className + " Method: " + methodName + " Arguments passed :" + mapper.writeValueAsString(arguments));
long startTime = System.currentTimeMillis();
Object obj = pjp.proceed();
long endTime = System.currentTimeMillis();
log.info(className + " Method : " + methodName + " Execution time: " + (endTime - startTime) + "ms");
log.info(className + " Method : " + methodName + " Response received : " + mapper.writeValueAsString(obj));
return obj;
}
#Around("entryDAO()")
public Object executionTimeDAO(ProceedingJoinPoint pjp) throws Throwable {
String methodName = pjp.getSignature().getName();
String className = pjp.getTarget().getClass().toString();
Object[] arguments = pjp.getArgs();
log.info(className + " Method : " + methodName + " Arguments passed :" + mapper.writeValueAsString(arguments));
long startTime = System.currentTimeMillis();
Object obj = pjp.proceed();
long endTime = System.currentTimeMillis();
log.info(className + " method : " + methodName + " Execution time: " + (endTime - startTime) + "ms");
log.info(className + " Method: " + methodName + " Response received : " + mapper.writeValueAsString(obj));
return obj;
}
}
Fixed test
I sent you two links before in my comment, showing you how to write unit and integration tests. Why did you not do it more similar to my examples? Some things you did wrong are:
You created a mock for the aspect class under test. Why? You want to mock dependencies, not the thing you actually want to test. Like in my examples, you should instantiate the aspect normally, only inject a mock joinpoint when calling an advice method.
You cannot simply verify a chain of method calls on a corresponding chain of mock objects, but need to verify them separately. So, something like verify(joinPoint, times (1)).getSignature().getName().equals("MethodName") does not work.
You tried to stub when(object.getClass()).thenReturn(objectClass), which is unnecessary, because Object.getClass() returns something already. Furthermore, it is a final method of a JDK bootstrap class. You cannot simply mock that.
How about this?
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class LoggingAspectTest {
#Test
public void testBeforeOtherControllerCall() throws Throwable {
JoinPoint joinPoint = mock(JoinPoint.class);
LoggingAspect logging = new LoggingAspect();
String[] args = { "arg1", "arg2" };
Object[] obj = args;
Signature signature = mock(Signature.class);
when(joinPoint.getSignature()).thenReturn(signature);
when(signature.getName()).thenReturn("MethodName");
Object object = mock(Object.class);
when(joinPoint.getTarget()).thenReturn(object);
when(joinPoint.getArgs()).thenReturn(obj);
logging.beforeOtherControllerCall(joinPoint);
verify(joinPoint, times(1)).getSignature();
verify(signature, times(1)).getName();
verify(joinPoint, times(1)).getTarget();
verify(joinPoint, times(1)).getArgs();
}
}
This covers the method under test and verifies the calls on the mock objects you are interested in, even though I find those verifications somewhat questionable. Do you really want to test the internals of the aspect? You should rather test for side effects or results, if any. But of course you can do it like in my example.
My IDE looks like this when running the test with coverage:

How to trim video with start and end pos of seekbar using FFmpeg android?

String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};
private void trimVideo(ProgressDialog progressDialog) {
outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
+ "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
+ "filter_apply.mp4";
if (startTrim.equals("")) {
startTrim = "00:00:00";
}
if (endTrim.equals("")) {
endTrim = timeTrim(player.getDuration());
}
String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};
execFFmpegBinary1(cmd, progressDialog);
}
private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {
ProgressDialog progressDialog = prpg;
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
#Override
public void onFailure(String s) {
progressDialog.dismiss();
Toast.makeText(PlayerActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
Log.d(TAG, "FAILED with output : " + s);
}
#Override
public void onSuccess(String s) {
Log.d(TAG, "SUCCESS wgith output : " + s);
String finalPath = outputAudioMux;
videoPath = outputAudioMux;
Toast.makeText(PlayerActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(PlayerActivity.this, ShareVideoActivity.class);
intent.putExtra("pathGPU", finalPath);
startActivity(intent);
finish();
MediaScannerConnection.scanFile(PlayerActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);
}
#Override
public void onProgress(String s) {
Log.d(TAG, "Started gcommand : ffmpeg " + command);
progressDialog.setMessage("Please Wait video triming...");
}
#Override
public void onStart() {
Log.d(TAG, "Startedf command : ffmpeg " + command);
}
#Override
public void onFinish() {
Log.d(TAG, "Finished f command : ffmpeg " + command);
progressDialog.dismiss();
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
}
}

Spring aop and aspectj

How to store all the logged method calls in database of a single session using spring aop and aspectj ?
In the following code i will get the method names i need to capture them and store in database for an individual session.
#Aspect
#Component
public class LoggingAspect {
// #Autowired
// private SessionFactory sessionFactory;
//
// #Autowired
// private ActionRolesService actionRolesService;
private Logger logger = LoggerFactory.getLogger(getClass());
#Pointcut(" execution(java.lang.String com.bis.sourcelead.entity..*.*()) && "
+ "!execution(java.lang.String com.bis.sourcelead.entity..*.set*()) && "
+ "!execution(java.lang.String com.bis.sourcelead.entity..*.get*())")
private void intercepterMethod() {
}
#Pointcut("execution(#javax.inject.Inject * com.bis.sourcelead.web..*.*(..))")
public void methodAnnotatedWithInjectAndInDemoPackage() {
}
#Before("intercepterMethod()")
public void logAround(JoinPoint joinPoint) throws Throwable {
logger.info("********** Action class Before Method Excution ************");
logger.info("Class name : " + joinPoint.getTarget().getClass().getSimpleName());
logger.info("Method name : " + joinPoint.getSignature().getName());
logger.info("Parameters name : " + Arrays.toString(joinPoint.getArgs()));
}
#Before("execution(* com.bis.sourcelead.service..*.*(..))")
public void logBeforeService(JoinPoint joinPoint) throws Throwable {
logger.info("**********Service Layer Before Method Excution ************");
logger.info("Class name : " + joinPoint.getTarget().getClass().getSimpleName());
logger.info("Method name : " + joinPoint.getSignature().getName());
logger.info("Parameters name : " + Arrays.toString(joinPoint.getArgs()));
}
#AfterReturning(pointcut = "execution(* com.bis.sourcelead.service..*.*(..))", returning = "result")
public void logAfterReturningService(JoinPoint joinPoint, Object result) {
logger.info("********** Service Layer After Method Exectution ************");
logger.info("Class name : " + joinPoint.getTarget().getClass().getSimpleName());
logger.info("Method name : " + joinPoint.getSignature().getName());
logger.info("Method returned value : " + result);
}
#AfterThrowing(pointcut = "execution(* com.bis.sourcelead.service.*.*(..))", throwing = "error")
public void logAfterThrowingService(JoinPoint joinPoint, Throwable error) {
logger.info("********** Service Layer Method Throwing Error ************");
logger.info("Class name : " + joinPoint.getTarget().getClass().getSimpleName());
logger.error("Method name : " + joinPoint.getSignature().getName());
logger.error("Exception : " + error);
}
#AfterThrowing(pointcut = "execution(* com.bis.sourcelead.dao.*.*(..))", throwing = "error")
public void logAfterThrowingDao(JoinPoint joinPoint, Throwable error) {
logger.info("********** Dao Layer Method Throwing Error ************");
logger.info("Class name : " + joinPoint.getTarget().getClass().getSimpleName());
logger.error("Method name : " + joinPoint.getSignature().getName());
logger.error("Exception : " + error);
}
#Around("execution(* com.bis.sourcelead.dao..*.*(..))")
public Object logAroundDao(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
logger.info("********** Dao Layer Before Method Excution ************");
logger.info("Class name : " + joinPoint.getTarget().getClass().getSimpleName());
logger.info("Method name : " + joinPoint.getSignature().getName());
logger.info("Parameters name : " + Arrays.toString(joinPoint.getArgs()));
long start = System.currentTimeMillis();
//result = joinPoint.proceed(); //continue on the intercepted method
result = joinPoint.proceed(joinPoint.getArgs()); //continue on the intercepted method
long elapsedTime = System.currentTimeMillis() - start;
logger.info("********** Dao Layer After Method Excution ************");
logger.info("Method execution time: " + elapsedTime + " milliseconds.");
return result;
}
#Before("execution(* com.bis.sourcelead.rest..*.*(..)) && methodAnnotatedWithInjectAndInDemoPackage() ")
public void logBeforeWebService(JoinPoint joinPoint) throws Throwable {
logger.info("**********Web Service Layer Before Method Excution ************");
logger.info("Class name : " + joinPoint.getTarget().getClass().getSimpleName());
logger.info("Method name : " + joinPoint.getSignature().getName());
logger.info("Parameters name : " + Arrays.toString(joinPoint.getArgs()));
System.out.print("Executed the #Injected method: "
+ joinPoint.getSignature() + " with value(s): ");
for (Object object : joinPoint.getArgs()) {
System.out.print(object);
}
System.out.println();
}
#AfterReturning(pointcut = "execution(* com.bis.sourcelead.rest..*.*(..))", returning = "result")
public void logAfterReturningWebService(JoinPoint joinPoint, Object result) {
logger.info("********** Web Service Layer After Method Exectution ************");
logger.info("Class name : " + joinPoint.getTarget().getClass().getSimpleName());
logger.info("Method name : " + joinPoint.getSignature().getName());
logger.info("Method returned value : " + result);
// try {
// if(joinPoint.getSignature().getName().equalsIgnoreCase("createUser"))
// logger.info("pradeep::"+actionRolesService.getActionNameUsingMethodName(joinPoint.getSignature().getName()));
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
#AfterThrowing(pointcut = "execution(* com.bis.sourcelead.rest.*.*(..))", throwing = "error")
public void logAfterThrowingWebService(JoinPoint joinPoint, Throwable error) {
logger.info("********** Web Service Layer Method Throwing Error ************");
logger.info("Class name : " + joinPoint.getTarget().getClass().getSimpleName());
logger.error("Method name : " + joinPoint.getSignature().getName());
logger.error("Exception : " + error);
}
}
//end class

Use Spring AOP and get respective class name in log file

I am using Spring AOP for logging purpose. Everything is working but in the log i am only getting the name of the Aspect class. I want the respective name of the class to be printed. Here is the code snippet. What changes are required in the following code to suffice my requirement.
private static final Logger logger = Logger.getLogger(LogginAspect.class);
#After("execution(* com.app.c2pc...(..))")
public void logAfter(JoinPoint joinPoint) {
logger.info("After executing method : " + joinPoint.getSignature().getName());
logger.info("***************************************************************************");
}
#Before("execution(* com.app.c2pc..*.*(..))")
public void logBefore(JoinPoint joinPoint) {
logger.info("***************************************************************************");
logger.info("Before executing method : " + joinPoint.getSignature().getName());
}
#Around("execution(* com.app.c2pc..*.*(..)) && !execution(* com.app.c2pc.login.LoginController.*(..)) ")
public Object logAround(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
Object clazz = pjp.getTarget().getClass().getName();
String methodName = pjp.getSignature().getName();
logger.info("Entering Class " + clazz + " With Method Name " + methodName);
Object[] obj = pjp.getArgs();
int i = 0;
try {
for (Object o : obj) {
logger.info(++i + " : Parameter Name :" + (null != o ? o.toString() : ""));
}
} catch (Exception e) {
e.printStackTrace();
}
Object output = pjp.proceed(pjp.getArgs());
logger.info("Excecution Completed for method : " + methodName + " in Class : " + clazz + " with result "
+ output);
long elapsedTime = System.currentTimeMillis() - start;
logger.info("Execution time for method : " + methodName + " in Class : " + clazz + " : " + elapsedTime
+ " milliseconds.");
return output;
}
#AfterThrowing(pointcut = "execution(* com.app.c2pc..*.*(..))", throwing = "error")
public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
logger.info("Exception thrown by method : " + joinPoint.getSignature().getName());
logger.info("Exception name : " + error);
}
#AfterReturning(pointcut = "execution(* com.app.c2pc..*.*(..))", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
logger.info("Method : " + joinPoint.getSignature().getName() + " returned value is : " + result);
}
This is the o/p i get in the log file:-
2016-07-20 23:41:20 | | INFO LogginAspect:23 - After executing method : checkSubmitEvalFlag
2016-07-20 23:41:20 | | INFO LogginAspect:24 - ***************************************************************************
2016-07-20 23:41:20 | | INFO LogginAspect:70 - Method : checkSubmitEvalFlag returned value is : 0
2016-07-20 23:41:20 | | INFO LogginAspect:40 - Entering Class com.app.c2pc.scie.daoImpl.PbdDAOImpl$$EnhancerBySpringCGLIB$$688f6ece With Method Name getBackUpUserDetails
2016-07-20 23:41:20 | | INFO LogginAspect:45 - 1 : Parameter Name :com.app.c2pc.scie.bean.SearchCriteriaBean#77ef5b02
you can use "joinPoint.getTarget().getClass().getName()" to get fully qualified class name like "com.abc.pqr.MyClass"
you can use "joinPoint.getTarget().getClass().getSimpleName()" to get only class name like "MyClass".

Can I know why it doesn't give out the output for below code since there's no any error?

package labexercise2;
import java.sql.*;
public class LabExercise2
{
public static void main (String [] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
System.out.println ("Driver Loaded");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost/restaurant?"+ "user=root&password=");
System.out.println ("Database connected");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT MenuID, MenuName, Type, Cuisine FROM menu WHERE Price BETWEEN 7 AND 13");
while (rs.next()){
System.out.println(rs.getString("MenuID") + " : " +
rs.getString("MenuName") + " : " +
rs.getString("Type") + " : " +
rs.getString("Cuisine") + " : " +
rs.getString("Price")); }
connection.close();
}
}
Can I know why it doesn't give out the output for below code since there's no any error?
Any help will be appreciated
i think you missed port number in DriverManager.getConnection argument,it should be as following.
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/restaurant?"+ "user=root&password=");
package labexercise2;
import java.sql.*;
public class LabExercise2
{
public static void main (String [] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
System.out.println ("Driver Loaded");
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/restaurant?"+ "user=root&password=");
System.out.println ("Database connected");
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM menu WHERE Price BETWEEN 7.00 AND 13.00");
while (rs.next()){
System.out.println(rs.getString("MenuID") + " : " +
rs.getString("MenuName") + " : " +
rs.getString("Type") + " : " +
rs.getString("Cuisine") + " : " +
rs.getString("Price")); }
conn.close();
}
}
can you try following code instead connection.close();
if (statement != null) {
statement.close();
}
if (connection!= null) {
connection.close();
}
i have mocked and tested your code, it's working for me as explained below.
import java.sql.*;
public class LabExercise2 {
public static void main (String [] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
System.out.println ("Driver Loaded");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost/restaurant?"+ "user=root&password=root");
System.out.println ("Database connected");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM menu WHERE Price BETWEEN 7 AND 13");
while (rs.next()){
System.out.println(rs.getString("MenuID") + " : " +
rs.getString("MenuName") + " : " +
rs.getString("Type") + " : " +
rs.getString("Cuisine") + " : " +
rs.getLong("Price")); }
connection.close();
}
}

Resources