Example usage for org.aspectj.lang ProceedingJoinPoint getArgs

List of usage examples for org.aspectj.lang ProceedingJoinPoint getArgs

Introduction

In this page you can find the example usage for org.aspectj.lang ProceedingJoinPoint getArgs.

Prototype

Object[] getArgs();

Source Link

Usage

From source file:com.zte.spring.service.LogService.java

@Around("methodCachePointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {

    Object result = null;//from   w  ww.  j  a v a  2 s . co  m
    String methodName = point.getSignature().getName();

    // ?
    if (methodName.equals("login")) {
        result = point.proceed();
    }

    if (logMethodsMap.containsKey(methodName)) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String loginName = (String) request.getSession().getAttribute("userid");
        String roleName = (String) request.getSession().getAttribute("uname");
        String clientIP = (String) request.getSession().getAttribute("clientIP");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar ca = Calendar.getInstance();
        String operDate = df.format(ca.getTime());
        StringBuffer operDetail = new StringBuffer();
        operDetail.append(roleName).append(loginName).append("(").append(clientIP).append(")");
        Object[] method_param = point.getArgs(); // ??

        // ????
        if (!methodName.equals("addUser") && !methodName.equals("saveNews")
                && !methodName.equals("saveOrUpdateRole") && !methodName.equals("saveOrUpdateParam")
                && !methodName.equals("updateParam")) {
            operDetail.append(logMethodsMap.get(methodName));
        }
        operDetail.append(getOperContent(method_param, methodName));
        SysLog log = new SysLog();
        log.setType("oper");
        log.setCreatime(operDate);
        log.setUname(loginName);
        log.setUid("");
        log.setOper(logMethodsMap.get(methodName));
        log.setContent(operDetail.toString());
        logger.info(log.getContent());
        logService.saveLog(log);
    }

    if (!methodName.equals("login")) {
        result = point.proceed();
    }

    return result;
}

From source file:cs544.videohouse.util.Welcome.java

@Around("execution(* cs544.videohouse.controller.VideoController.checkUploadVideo(..))")
public String greet(ProceedingJoinPoint call) throws Throwable {
    Object[] args = call.getArgs();
    //        User u=(User) args[0];        
    //        System.out.println("Before: Hi "+u.getFirstName()+"!");
    String view = (String) call.proceed(args);
    //        args= call.getArgs();
    //        u=(User) args[0];                
    if (view.contains("#")) {
        rId = Integer.valueOf(view.split("#")[2]);
        recentUpload = "Latest: " + view.split("#")[1] + "!";
        view = view.split("#")[0];
    }/*from   w w  w . ja v  a 2 s.  c o  m*/
    System.out.println("Will go next to: " + view);
    System.out.println("Latest:" + recentUpload);
    return view;
}

From source file:cz.sohlich.workstack.aspect.AuthorizationAspect.java

@Around("execution(* cz.sohlich.workstack.api.TaskResource.*(..))")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
    Object[] array = pjp.getArgs();

    System.out.println(Arrays.toString(array));
    // start stopwatch
    Object retVal = pjp.proceed();
    // stop stopwatch
    return retVal;
}

From source file:de.bstreit.java.springaop.observablebean.PropertyChangeSupportWithInterface.java

License:Apache License

/**
 * Retrieve old and new value, invoke setter and finally fire property change
 * event./* w ww .j a  v  a  2 s.  c o m*/
 * 
 * @param pjp
 * @throws Throwable
 */
void handleSetterInvocation(ProceedingJoinPoint pjp) throws Throwable {
    // the method name is "setPropertyName", hence stripping of the "set"
    // from the beginning gives us "PropertyName"
    final String propertyName = pjp.getSignature().getName().substring(3);

    final Object oldValue = beanWrapper.getPropertyValue(propertyName);
    final Object newValue = pjp.getArgs()[0];

    // perform the setting
    pjp.proceed();

    // fire property change, if no exception occurred
    pcs.firePropertyChange(propertyName, oldValue, newValue);
}

From source file:de.codecentric.capturereplay.CaptureReplayAdvice.java

License:Apache License

@Around("execution(@de.codecentric.capturereplay.Capturable * *(..))")
public Object aroundCapturableMethod(ProceedingJoinPoint pjp) throws Throwable {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    if (Mode.CAPTURE.equals(mode)) {
        Object returnValue = pjp.proceed();
        dataMapper.writeCapturedData(signature, returnValue, pjp.getArgs());
        return returnValue;
    } else if (Mode.REPLAY.equals(mode)) {
        return dataMapper.getCapturedData(signature.getMethod().getName(), pjp.getArgs());
    } else if (Mode.DISABLED.equals(mode)) {
        return pjp.proceed();
    } else {// www .  j  a  va  2 s. c o  m
        throw new IllegalCaptureReplayUsageException(
                String.format("Capturing/replaying is switched off. You should not use %s directly.",
                        this.getClass().getSimpleName()));
    }
}

From source file:de.escidoc.core.aa.security.aop.SecurityInterceptor.java

License:Open Source License

/**
 * Around advice to perform the authorization of the current request.
 * <p/>//  www  .ja  va  2 s  .  c  o  m
 * This method is called every time the Interceptor is intercepting a method call.
 * <p/>
 * It does the following steps: <ul> <li>Fetch the credentials (techUser, handle) of the current user from class
 * {@code UserContext}.</li> <li>Checks the technical username. Has to be either <ul>
 * <li>{@code ShibbolethUser}, which means that the service has been invoked from via a webservice, </li>
 * <li>{@code internal}, which means that the service has been called internally from another component and
 * {@code INTERNAL_INTERCEPTION} is turned off, or</li> <li>{@code authorization}, which means that the
 * service has been called internally from the authorization component.</li> </ul> <li>In case the technical
 * username is {@code internal}, no further security checks are done, the intercepted method is invoked and its
 * return value is returned to the originally invoking method.</li> <li>In case the technical username is
 * {@code ShibbolethUser}, the following steps are executed.</li> <li>The private method
 * {@code doAuthentication} is called, which returns the "real" username for the handle fetched from
 * {@code UserContext}.</li> <li>The private method {@code doAuthorisation} is called, which calls the
 * XACML engine with the current input parameters in order to decide whether invoking the intercepted method is
 * permitted or denied. In case of denial, an exception is thrown.</li> <li>The intercepted method is invoked,
 * returning some return values.</li> <li>If the return values are a list of objects, these have to filtered before
 * returned to the invoking service. For this the private method {@code doFiltering} is called, which returns
 * the (filtered) return value of the intercepted method.</li> <li>The (filtered) return value of the intercepted
 * method is returned back to the invoking service.</li> </ul>
 *
 * @param joinPoint The current {@link ProceedingJoinPoint}.
 * @throws Throwable Thrown in case of an error.
 * @return
 */
@Around("execution(public * de.escidoc.core.*.service.*.*(..))"
        + " && !within(de.escidoc.core.aa.service.EscidocUserDetailsService)"
        + " && !within(de.escidoc.core.common.util.aop..*)")
public Object authorize(final ProceedingJoinPoint joinPoint) throws Throwable {
    final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    final Method calledMethod = methodSignature.getMethod();
    final String target = getTargetInterface(joinPoint);
    final String methodName = calledMethod.getName();
    final String handle = UserContext.getHandle();

    // -------------------
    // --- Preparation ---
    // -------------------

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(StringUtility.concatenateWithColonToString("The callee", target));
        LOGGER.debug(StringUtility.concatenateWithColonToString("Method name", methodName));
        LOGGER.debug(StringUtility.concatenateWithColonToString("The handle/password", handle));
    }

    final Object[] arguments = joinPoint.getArgs();
    if (LOGGER.isDebugEnabled()) {
        if (arguments.length > 0) {
            LOGGER.debug(StringUtility.concatenateWithColon("First Argument", arguments[0]).toString());
        } else {
            LOGGER.debug("Method called without arguments.");
        }
    }

    // ---------------------
    // --- Authorization ---
    // ---------------------
    // authorization is not performed if the current request is executed as
    // an internal user. Only external users are authorized.

    if (!UserContext.isInternalUser()) {

        // Calls from the authorization component to other components run
        // with privileges of the internal authorization user (superuser).
        // They will not be further intercepted.
        UserContext.runAsInternalUser();
        doAuthorisation(target, methodName, arguments);

        // --------------------
        // --- Continuation ---
        // --------------------
        // if everything is fine, finally call the method.
        // This method runs with privileges of an internal user that will
        // not be
        // further intercepted, as the access to the resource has been
        // granted,
        // now.
    }

    try {
        return proceed(joinPoint);
    } catch (final ResourceNotFoundException e) {
        // see issue 475, 500
        // this exception may be thrown if the user tries to access
        // a versionized resource without providing the version number.
        // If the access is denied for the latest version, the business
        // logic is asked to retrieve the latest release. If no release
        // exists, a Resource not found exception is thrown containing
        // an error message indicating the missing release.
        // As this is an authorization failure, this kind of
        // ResourceNotFoundException must be caught and a
        // AuthorizationException has to be thrown, instead
        if (UserContext.isRetrieveRestrictedToReleased()
                && ERR_MSG_LATEST_RELEASE_NOT_FOUND.equals(e.getMessage())) {
            throw createAuthorizationException(target, methodName, arguments);
        } else {
            throw e;
        }
    }
}

From source file:de.escidoc.core.common.util.aop.StatisticInterceptor.java

License:Open Source License

/**
 * Around advice to create a statistic record for the current method call.<br>
 *
 * @param joinPoint The current {@link ProceedingJoinPoint}.
 * @return Returns the changed result.//w w  w  . j  ava2s .  c  o  m
 * @throws Throwable Thrown in case of an error.
 */
@Around("execution(public * de.escidoc.core.*.service.*.*(..))"
        + " && !within(de.escidoc.core.aa.service.EscidocUserDetailsService)"
        + " && !execution(* de.escidoc.core..*.SemanticStoreHandler*.*(..))"
        + " && !execution(* de.escidoc.core..*.StatisticService*.*(..))"
        + " && !execution(* de.escidoc.core.common..*.*(..))")
// enable this aspect only if you need
public Object createStatisticRecord(final ProceedingJoinPoint joinPoint) throws Throwable {
    final long invocationStartTime = System.currentTimeMillis();
    boolean successful = true;
    boolean internal = false;
    String exceptionName = null;
    String exceptionSource = null;
    try {
        // insert internal (0)/external (1) info
        if (!UserContext.isExternalUser()) {
            internal = true;
        }
        return proceed(joinPoint);
    } catch (final Exception e) {
        successful = false;
        exceptionName = e.getClass().getName();
        final StackTraceElement[] elements = e.getStackTrace();
        if (elements != null && elements.length > 0) {
            final StackTraceElement element = elements[0];
            exceptionSource = StringUtility.format(element.getClassName(), element.getMethodName(),
                    element.getLineNumber());
        } else {
            exceptionSource = Constants.UNKNOWN;
        }
        if (e instanceof EscidocException) {
            throw e;
        } else {
            // this should not occur. To report this failure, the exception is wrapped by a SystemException
            throw new SystemException("Service throws unexpected exception. ", e);
        }
    } finally {
        // get callee and method info
        final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // get interface info
        // create a new statistic data record stored in thread local for this scope
        final StatisticRecordBuilder statisticRecordBuilder = StatisticRecordBuilder.createStatisticRecord();
        handleObjectIds(statisticRecordBuilder, methodSignature.getMethod().getName(), joinPoint.getArgs());
        final String interfaceInfo = VALUE_INTERFACE_REST;
        final StatisticRecord statisticRecord = statisticRecordBuilder
                .withParameter(PARAM_HANDLER,
                        methodSignature.getDeclaringTypeName().replaceAll("\\.interfaces", "")
                                .replaceAll("Interface$", ""))
                .withParameter(PARAM_REQUEST, methodSignature.getMethod().getName())
                .withParameter(PARAM_INTERFACE, interfaceInfo).withParameter(PARAM_INTERNAL, internal)
                .withParameter(PARAM_SUCCESSFUL, successful).withParameter(PARAM_EXCEPTION_NAME, exceptionName)
                .withParameter(PARAM_EXCEPTION_SOURCE, exceptionSource)
                .withParameter(PARAM_USER_ID, UserContext.getId()).withParameter(PARAM_ELAPSED_TIME,
                        String.valueOf(System.currentTimeMillis() - invocationStartTime))
                .build();
        this.statisticService.createStatisticRecord(statisticRecord);
    }
}

From source file:de.gmorling.methodvalidation.spring.ValidationInterceptor.java

License:Apache License

@Around("execution(public * *(..)) && @within(de.gmorling.methodvalidation.spring.AutoValidating)")
public Object validateMethodInvocation(ProceedingJoinPoint pjp) throws Throwable {
    Object result;//from w w w . j ava  2s.  com
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    MethodValidator methodValidator = validator.unwrap(MethodValidator.class);

    Set<MethodConstraintViolation<Object>> parametersViolations = methodValidator
            .validateAllParameters(pjp.getTarget(), signature.getMethod(), pjp.getArgs());
    if (!parametersViolations.isEmpty()) {
        throw new MethodConstraintViolationException(parametersViolations);
    }

    result = pjp.proceed(); //Execute the method

    Set<MethodConstraintViolation<Object>> returnValueViolations = methodValidator
            .validateReturnValue(pjp.getTarget(), signature.getMethod(), result);
    if (!returnValueViolations.isEmpty()) {
        throw new MethodConstraintViolationException(returnValueViolations);
    }

    return result;
}

From source file:de.huxhorn.lilith.tracing.TracingAspect.java

License:Open Source License

public Object trace(ProceedingJoinPoint call) throws Throwable {
    if (logger == null) {
        setLoggerName(null);//from   w w  w  . j  a  v a2s .co  m
        // this initializes the logger
    }
    Signature signature = call.getSignature();
    Class<?> clazz = signature.getDeclaringType();
    Object theTarget = call.getTarget();
    if (theTarget != null) {
        clazz = theTarget.getClass();
    }
    String fullClassName = clazz.getName();
    String methodName = signature.getName();
    StringBuilder msg = new StringBuilder();
    if (showingModifiers) {
        msg.append(Modifier.toString(signature.getModifiers())).append(' ');
    }
    if (usingShortClassName) {
        msg.append(clazz.getSimpleName());
    } else {
        msg.append(fullClassName);
    }
    msg.append('.').append(methodName);
    String methodBaseName = msg.toString();
    if (signature instanceof MethodSignature) {
        MethodSignature methodSignature = (MethodSignature) signature;
        msg.append('(');
        if (showingParameterValues) {
            Object[] args = call.getArgs();
            boolean first = true;
            for (Object arg : args) {
                if (first) {
                    first = false;
                } else {
                    msg.append(", ");
                }
                msg.append(SafeString.toString(arg, SafeString.StringWrapping.ALL,
                        SafeString.StringStyle.GROOVY, SafeString.MapStyle.GROOVY));
            }
        } else {
            Method method = methodSignature.getMethod();
            Class<?>[] parameterTypes = method.getParameterTypes();
            boolean first = true;
            for (Class<?> param : parameterTypes) {
                if (first) {
                    first = false;
                } else {
                    msg.append(", ");
                }
                msg.append(param.getSimpleName());
            }
            if (method.isVarArgs()) {
                int length = msg.length();
                msg.delete(length - 2, length); // cut of existing []
                msg.append("...");
            }
        }
        msg.append(')');
    }
    String methodSignatureString = msg.toString();

    String previousClass = MDC.get(TRACED_CLASS_MDC_KEY);
    String previousMethod = MDC.get(TRACED_METHOD_MDC_KEY);
    long nanoSeconds = 0;
    try {
        MDC.put(TRACED_CLASS_MDC_KEY, fullClassName);
        MDC.put(TRACED_METHOD_MDC_KEY, methodName);
        if (logger.isInfoEnabled(ENTERING_MARKER))
            logger.info(ENTERING_MARKER, "{} entered.", methodSignatureString);
        Object result;
        nanoSeconds = System.nanoTime();
        result = call.proceed();
        nanoSeconds = System.nanoTime() - nanoSeconds;
        profile(methodBaseName, methodSignatureString, nanoSeconds);
        if (result == null || !showingParameterValues) {
            if (logger.isInfoEnabled(EXITING_MARKER))
                logger.info(EXITING_MARKER, "{} returned.", methodSignatureString);
        } else {
            if (logger.isInfoEnabled(EXITING_MARKER))
                logger.info(EXITING_MARKER, "{} returned {}.", methodSignatureString, result);
        }
        return result;
    } catch (Throwable t) {
        nanoSeconds = System.nanoTime() - nanoSeconds;
        profile(methodBaseName, methodSignatureString, nanoSeconds);
        if (logger.isInfoEnabled(THROWING_MARKER))
            logger.info(THROWING_MARKER, "{} failed.", methodSignatureString, t);
        throw t; // rethrow
    } finally {
        if (previousClass == null) {
            MDC.remove(TRACED_CLASS_MDC_KEY);
        } else {
            MDC.put(TRACED_CLASS_MDC_KEY, previousClass);
        }
        if (previousMethod == null) {
            MDC.remove(TRACED_METHOD_MDC_KEY);
        } else {
            MDC.put(TRACED_METHOD_MDC_KEY, previousMethod);
        }
    }
}

From source file:de.hybris.platform.acceleratorservices.dataimport.batch.aop.ExceptionHandlerAspect.java

License:Open Source License

/**
 * Invokes a method and wraps all Exceptions in a {@link BatchException}.
 * /*  w  ww  .  j  a va 2  s .co m*/
 * @param pjp
 * @return result of the invocation
 * @throws Throwable
 */
public Object execute(final ProceedingJoinPoint pjp) throws Throwable {
    final BatchHeader header = AspectUtils.getHeader(pjp.getArgs());
    try {
        return pjp.proceed();
    } catch (final Exception e) {
        throw new BatchException(e.getMessage(), header, e);
    }
}