Example usage for org.aspectj.lang.reflect MethodSignature getMethod

List of usage examples for org.aspectj.lang.reflect MethodSignature getMethod

Introduction

In this page you can find the example usage for org.aspectj.lang.reflect MethodSignature getMethod.

Prototype

Method getMethod();

Source Link

Usage

From source file:org.finra.herd.service.advice.NamespaceSecurityAdviceTest.java

License:Apache License

@Test
public void checkPermissionAssertNoExceptionWhenHasPermissionsNamespaceTrimmed() throws Exception {
    // Mock a join point of the method call
    // mockMethod(" foo ");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespace" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { BLANK_TEXT + "foo" + BLANK_TEXT });

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);//w w  w  .  j ava2 s.c  o  m
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    // User has permission to "foo" but the actual namespace given is " foo "
    applicationUser.getNamespaceAuthorizations()
            .add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(
            new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser),
            null));

    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
    } catch (AccessDeniedException e) {
        fail();
    }
}

From source file:org.finra.herd.service.advice.NamespaceSecurityAdviceTest.java

License:Apache License

@Test
public void checkPermissionAssertAccessDeniedWhenNoPermissionsNamespaceTrimmed() throws Exception {
    // Mock a join point of the method call
    // mockMethod(" foo ");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespace" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { BLANK_TEXT + "foo" + BLANK_TEXT });

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);//from w w  w. j a v  a 2  s  .c o m
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    // User has permission to "bar" but the actual namespace given is " foo "
    applicationUser.getNamespaceAuthorizations()
            .add(new NamespaceAuthorization("bar", Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(
            new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser),
            null));

    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    } catch (Exception e) {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String
                .format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"foo\"", userId),
                e.getMessage());
    }
}

From source file:org.finra.herd.service.advice.NamespaceSecurityAdviceTest.java

License:Apache License

@Test
public void checkPermissionAssertMultipleAccessDeniedExceptionsAreGatheredIntoSingleMessageWhenMultipleAnnotations()
        throws Exception {
    // Mock a join point of the method call
    // mockMethodMultipleAnnotations("namespace1", "namespace2");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethodMultipleAnnotations",
            String.class, String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespace1", "namespace2" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { "foo", "bar" });

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);/* ww  w.jav a 2  s  . c  o  m*/
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    // User has no permissions
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(
            new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser),
            null));

    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    } catch (Exception e) {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format(
                "User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"foo\"%n"
                        + "User \"%s\" does not have \"[WRITE]\" permission(s) to the namespace \"bar\"",
                userId, userId), e.getMessage());
    }
}

From source file:org.finra.herd.service.advice.NamespaceSecurityAdviceTest.java

License:Apache License

@Test
public void checkPermissionAssertMultipleAccessDeniedExceptionsAreGatheredIntoSingleMessageWhenCollections()
        throws Exception {
    // Mock a join point of the method call
    // mockMethod({"", ""})
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", List.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespaces" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { Arrays.asList("foo", "bar") });

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);//from  ww  w  . ja  v a  2s . c  om
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    // User has no permissions
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(
            new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser),
            null));

    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    } catch (Exception e) {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format(
                "User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"foo\"%n"
                        + "User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"bar\"",
                userId, userId), e.getMessage());
    }
}

From source file:org.finra.herd.service.advice.NamespaceSecurityAdviceTest.java

License:Apache License

/**
 * Assert no access denied exception when parameter value is null.
 *///from ww w . j  a va  2s  .c  om
@Test
public void checkPermissionAssertNoExceptionWhenNull() throws Exception {
    // Mock a join point of the method call
    // mockMethod(null);
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespace" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { null });

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(
            new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser),
            null));

    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
    } catch (AccessDeniedException e) {
        fail();
    }
}

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 va  2s .co  m*/
 *
 * @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
 *//*from  www .  ja va2  s. co  m*/
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   ww  w  .  j av a  2s .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   w  w  w  .  j  a va 2  s.c  o m*/
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. j a  va  2  s.  co m
@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();
    }
}