List of usage examples for org.aspectj.lang ProceedingJoinPoint getTarget
Object getTarget();
From source file:org.finra.herd.dao.helper.AwsExceptionRetryAdvice.java
License:Apache License
/** * Invokes the method, catches following various exceptions and retries as needed: 1. Throttling exception. 2. 5xx exception. 3. Error codes defined in * configuration to be retried.//from www . j a v a2s . co m * * @param pjp the join point. * * @return the return value of the method at the join point. * @throws Throwable if any errors were encountered. */ public Object retryOnException(ProceedingJoinPoint pjp) throws Throwable { // Get the method name being invoked. Class<?> targetClass = pjp.getTarget().getClass(); MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature(); String methodName = targetClass.getName() + "." + targetMethodSignature.getName(); // Get the max delay in seconds. long maxTotalDelay = getMaxRetryDelaySecs() * 1000L; // Initialize a retry count to know the number of times we have retried calling the method. int retryCount = 0; // Get the minimum and maximum retry delay. long minAwsDelay = herdStringHelper .getConfigurationValueAsInteger(ConfigurationValue.AWS_MIN_RETRY_DELAY_SECS) * 1000L; long maxAwsDelay = herdStringHelper .getConfigurationValueAsInteger(ConfigurationValue.AWS_MAX_RETRY_DELAY_SECS) * 1000L; StopWatch totalElapsedTimeStopWatch = new StopWatch(); totalElapsedTimeStopWatch.start(); // Loop indefinitely. We will exit the loop if the method returns normally or a non-retryable exception is thrown. // If a retryable exception is thrown, the loop will exit after we have exceeded the maximum retry delay seconds. while (true) { try { // Proceed to the join point (i.e. call the method and let it return normally). return pjp.proceed(); } catch (AmazonServiceException ase) { // Retry if: // 1) Is throttling exception. // 2) Is 5xx exception. // 3) Is an error to be re-tried on as defined in configuration. if (RetryUtils.isThrottlingException(ase) || is5xxException(ase) || isRetryableException(ase)) { long totalElapsedTime = totalElapsedTimeStopWatch.getTime(); // It's a retryable exception. Check if we've retried for enough time. if (totalElapsedTime >= maxTotalDelay) { // We've retried for enough time so re-throw the original exception. LOGGER.warn("An exception occurred while calling " + methodName + ". The method has been retried for " + (totalElapsedTime / 1000.0f) + " second(s) and will not be retried anymore since it would exceed the maximum retry delay." + " The exception will now be thrown."); throw ase; } // Get the next delay. long nextSleepDelay = Math.min(((long) Math.pow(2, retryCount) * minAwsDelay), maxAwsDelay); long timeLeftToRetry = maxTotalDelay - totalElapsedTime; // If time left to try is less than next sleep delay, then use time left as next sleep delay to be retried the last time. if (timeLeftToRetry < nextSleepDelay) { nextSleepDelay = timeLeftToRetry; } // Log a warning so we're aware that we are retrying. LOGGER.warn("A retryable exception occurred while calling " + methodName + ". " + (totalElapsedTime / 1000.0f) + " second(s) have elapsed since initial exception and maximum retry delay is " + (maxTotalDelay / 1000.0f) + " second(s). Will retry in " + (nextSleepDelay / 1000.0f) + " second(s)."); // We can retry again so increment a counter to keep track of the number of times we retried and recalculate the total elapsed time. retryCount++; // Sleep for the next sleep delay. herdThreadHelper.sleep(nextSleepDelay); } else { // It's not a retryable exception (i.e. some other type of service exception) so just re-throw it. throw ase; } } } }
From source file:org.finra.herd.dao.MethodLoggingAdvice.java
License:Apache License
/** * Around advice that logs methods being invoked for all DAO operations methods. * * @param pjp the proceeding join point. * * @return the return value of the method we are advising. * @throws Throwable if there were any problems executing the method. *///from w w w.ja va 2s . c o m @Around("operationsMethods()") public Object logMethodBeingInvoked(ProceedingJoinPoint pjp) throws Throwable { // Get the target class being called. Class<?> targetClass = pjp.getTarget().getClass(); // Get the target method being called. MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature(); Method targetMethod = targetMethodSignature.getMethod(); if (targetMethod.getDeclaringClass().isInterface()) { // Get the underlying implementation if we are given an interface. targetMethod = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(), targetMethod.getParameterTypes()); } // Only log the method if the class and method aren't suppressing logging and the log level is debug. if ((AnnotationUtils.findAnnotation(targetClass, SuppressLogging.class) == null) && (AnnotationUtils.findAnnotation(targetMethod, SuppressLogging.class) == null) && (LOGGER.isDebugEnabled())) { LOGGER.debug("javaMethod=\"{}.{}\"", targetClass.getName(), targetMethodSignature.getName()); } // Proceed to the join point (i.e. call the method and let it return). return pjp.proceed(); }
From source file:org.finra.herd.service.advice.PublishJmsMessagesAdvice.java
License:Apache License
/** * Publishes all JMS messages stored in the "in-memory" JMS message queue. * * @param joinPoint the join point//from ww w .j a v a2 s . c om * * @return the return value of the method at the join point * @throws Throwable if any errors were encountered */ @Around("serviceMethods()") public Object publishJmsMessages(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); boolean publishJmsMessages = method.isAnnotationPresent(PublishJmsMessages.class); // Proceed to the join point (i.e. call the method and let it return). try { Object returnValue = joinPoint.proceed(); if (publishJmsMessages) { if (LOGGER.isDebugEnabled()) { // Get the target class being called. Class<?> targetClass = joinPoint.getTarget().getClass(); LOGGER.debug( "Method is initiating JMS message publishing. javaMethod=\"{}.{}\" jmsMessageInMemoryQueueSize={}", targetClass.getName(), methodSignature.getName(), jmsMessageInMemoryQueue.size()); } // Publish all JMS messages stored in the "in-memory" JMS message queue. while (!jmsMessageInMemoryQueue.isEmpty()) { JmsMessage jmsMessage = jmsMessageInMemoryQueue.remove(); try { // Send a text message to the specified AWS SQS queue. sqsDao.sendSqsTextMessage(awsHelper.getAwsParamsDto(), jmsMessage.getJmsQueueName(), jmsMessage.getMessageText()); LOGGER.info("Published JMS message. jmsQueueName=\"{}\" jmsMessagePayload={}", jmsMessage.getJmsQueueName(), jmsMessage.getMessageText()); } catch (Exception sqsException) { LOGGER.warn( "Failed to publish message to the JMS queue. jmsQueueName=\"{}\" jmsMessagePayload={}", jmsMessage.getJmsQueueName(), jmsMessage.getMessageText(), sqsException); try { jmsPublishingService.addJmsMessageToDatabaseQueue(jmsMessage.getJmsQueueName(), jmsMessage.getMessageText()); } catch (Exception dbException) { LOGGER.error( "Failed to add JMS message to the database queue. jmsQueueName=\"{}\" jmsMessagePayload={}", jmsMessage.getJmsQueueName(), jmsMessage.getMessageText(), dbException); } } } } return returnValue; } finally { // Removes all of the elements from the queue, since the thread might be reused from the thread pool. if (publishJmsMessages) { jmsMessageInMemoryQueue.clear(); } } }
From source file:org.finra.herd.service.advice.PublishJmsMessagesAdviceTest.java
License:Apache License
/** * Creates and returns a mocked join point of the method call. * * @param methodName the name of the method * * @return the mocked ProceedingJoinPoint *//*w w w . j ava2s. c om*/ private ProceedingJoinPoint getMockedProceedingJoinPoint(String methodName) throws Exception { ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = PublishJmsMessagesAdviceTest.class.getDeclaredMethod("mockMethod"); when(joinPoint.getTarget()).thenReturn(new PublishJmsMessagesAdviceTest()); when(joinPoint.getSignature()).thenReturn(methodSignature); when(methodSignature.getMethod()).thenReturn(method); when(methodSignature.getName()).thenReturn(methodName); return joinPoint; }
From source file:org.finra.herd.service.advice.PublishNotificationMessagesAdvice.java
License:Apache License
/** * Publishes all notification messages stored in the "in-memory" notification message queue. * * @param joinPoint the join point/*from w w w.j av a 2 s.c om*/ * * @return the return value of the method at the join point * @throws Throwable if any errors were encountered */ @Around("serviceMethods()") public Object publishNotificationMessages(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); boolean publishNotificationMessages = method.isAnnotationPresent(PublishNotificationMessages.class); // Proceed to the join point (i.e. call the method and let it return). try { Object returnValue = joinPoint.proceed(); if (publishNotificationMessages) { if (LOGGER.isDebugEnabled()) { // Get the target class being called. Class<?> targetClass = joinPoint.getTarget().getClass(); LOGGER.debug( "Method is initiating notification message publishing. javaMethod=\"{}.{}\" notificationMessageInMemoryQueueSize={}", targetClass.getName(), methodSignature.getName(), notificationMessageInMemoryQueue.size()); } // Publish all notification messages stored in the "in-memory" notification message queue. while (!notificationMessageInMemoryQueue.isEmpty()) { // Get notification message from the "in-memory" queue. NotificationMessage notificationMessage = notificationMessageInMemoryQueue.remove(); // Publish the message. try { notificationMessagePublishingService.publishNotificationMessage(notificationMessage); } catch (Exception sqsException) { // On error, add this notification message to the database queue. try { notificationMessagePublishingService .addNotificationMessageToDatabaseQueue(notificationMessage); } catch (Exception dbException) { // Log the error. LOGGER.error( "Failed to add notification message to the database queue. messageType=\"{}\" messageDestination=\"{}\" messageText={}", notificationMessage.getMessageType(), notificationMessage.getMessageDestination(), notificationMessage.getMessageText(), dbException); } } } } return returnValue; } finally { // Removes all of the elements from the queue, since the thread might be reused from the thread pool. if (publishNotificationMessages) { notificationMessageInMemoryQueue.clear(); } } }
From source file:org.finra.herd.service.advice.PublishNotificationMessagesAdviceTest.java
License:Apache License
/** * Creates and returns a mocked join point of the method call. * * @param methodName the name of the method * * @return the mocked ProceedingJoinPoint *//*from ww w . ja v a 2 s .com*/ private ProceedingJoinPoint getMockedProceedingJoinPoint(String methodName) throws Exception { ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = PublishNotificationMessagesAdviceTest.class.getDeclaredMethod("mockMethod"); when(joinPoint.getTarget()).thenReturn(new PublishNotificationMessagesAdviceTest()); when(joinPoint.getSignature()).thenReturn(methodSignature); when(methodSignature.getMethod()).thenReturn(method); when(methodSignature.getName()).thenReturn(methodName); return joinPoint; }
From source file:org.finra.herd.service.advice.StopWatchAdvice.java
License:Apache License
/** * Around advice that logs methods times for all service methods. * * @param pjp the proceeding join point. * * @return the return value of the method we are advising. * @throws Throwable if there were any problems executing the method. *///from w w w. ja v a 2s.c om @Around("serviceMethods()") public Object logMethodTime(ProceedingJoinPoint pjp) throws Throwable { // Get the target class being called. Class<?> targetClass = pjp.getTarget().getClass(); // Get the target method being called. MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature(); Method targetMethod = targetMethodSignature.getMethod(); if (targetMethod.getDeclaringClass().isInterface()) { // Get the underlying implementation if we are given an interface. targetMethod = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(), targetMethod.getParameterTypes()); } // Only keep a stop watch if the class and method aren't suppressing logging and the log level is info. if ((AnnotationUtils.findAnnotation(targetClass, SuppressLogging.class) == null) && (AnnotationUtils.findAnnotation(targetMethod, SuppressLogging.class) == null) && (LOGGER.isInfoEnabled())) { // Start the stop watch. StopWatch stopWatch = new StopWatch(); stopWatch.start(); // Proceed to the join point (i.e. call the method and let it return). Object returnValue = pjp.proceed(); // Log the duration. long durationMilliseconds = stopWatch.getTime(); LOGGER.info( "javaMethod=\"{}.{}\" javaMethodDurationTimeInMilliseconds={} javaMethodDurationTimeFormatted=\"{}\"", targetClass.getName(), targetMethodSignature.getName(), durationMilliseconds, HerdDateUtils.formatDuration(durationMilliseconds)); // Return the method return value. return returnValue; } else { // Invoke the method normally. return pjp.proceed(); } }
From source file:org.finra.herd.service.advice.StopWatchAdviceTest.java
License:Apache License
/** * Creates and returns a mocked join point of the method call. * * @param targetObject the target object * @param method the method/*from w w w . ja va 2 s .c o m*/ * * @return the mocked ProceedingJoinPoint */ private ProceedingJoinPoint getMockedProceedingJoinPoint(Object targetObject, Method method) throws Exception { ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); when(joinPoint.getTarget()).thenReturn(targetObject); when(joinPoint.getSignature()).thenReturn(methodSignature); when(methodSignature.getMethod()).thenReturn(method); when(methodSignature.getName()).thenReturn(method.getName()); return joinPoint; }
From source file:org.finra.herd.service.helper.CheckAllowedMethodAdvice.java
License:Apache License
/** * Checks whether the requested operation is permitted. * * @param pjp the join point./* ww w . jav a 2 s. c o m*/ * * @return the return value of the method at the join point. * @throws Throwable if any errors were encountered. */ @SuppressWarnings("rawtypes") public Object checkNotAllowedMethods(ProceedingJoinPoint pjp) throws Throwable { // Get the method name being invoked. Class targetClass = pjp.getTarget().getClass(); MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature(); String methodName = targetClass.getName() + "." + targetMethodSignature.getName(); configurationDaoHelper.checkNotAllowedMethod(methodName); return pjp.proceed(); }
From source file:org.fishwife.jrugged.aspects.CircuitBreakerAspect.java
License:Apache License
/** Runs a method call through the configured * {@link org.fishwife.jrugged.CircuitBreaker}. * @param pjp a {@link ProceedingJoinPoint} representing an annotated * method call.// w w w. j a v a2 s . com * @param circuitBreakerAnnotation the {@link org.fishwife.jrugged.CircuitBreaker} annotation * that wrapped the method. * @throws Throwable if the method invocation itself or the wrapping * {@link org.fishwife.jrugged.CircuitBreaker} throws one during execution. * @return The return value from the method call. */ @Around("@annotation(circuitBreakerAnnotation)") public Object monitor(final ProceedingJoinPoint pjp, CircuitBreaker circuitBreakerAnnotation) throws Throwable { final String name = circuitBreakerAnnotation.name(); org.fishwife.jrugged.CircuitBreaker circuitBreaker = circuitBreakerFactory.findCircuitBreaker(name); if (circuitBreaker == null) { DefaultFailureInterpreter dfi = new DefaultFailureInterpreter(circuitBreakerAnnotation.ignore(), circuitBreakerAnnotation.limit(), circuitBreakerAnnotation.windowMillis()); CircuitBreakerConfig config = new CircuitBreakerConfig(circuitBreakerAnnotation.resetMillis(), dfi); circuitBreaker = circuitBreakerFactory.createCircuitBreaker(name, config); } if (logger.isDebugEnabled()) { logger.debug( "Have @CircuitBreaker method with breaker name {}, " + "wrapping call on method {} of target object {} with status {}", new Object[] { name, pjp.getSignature().getName(), pjp.getTarget(), circuitBreaker.getStatus() }); } return circuitBreaker.invoke(new Callable<Object>() { public Object call() throws Exception { try { return pjp.proceed(); } catch (Throwable e) { if (e instanceof Exception) { throw (Exception) e; } else if (e instanceof Error) { throw (Error) e; } else { throw new RuntimeException(e); } } } }); }