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:de.randi2.aspects.LogAspects.java

License:Open Source License

/**
 * Log randomize./*  w w w .  j  a va 2 s .c o  m*/
 * 
 * @param pjp
 *            the pjp
 * 
 * @return the object
 * 
 * @throws Throwable
 *             the throwable
 */
@Around("execution(public * de.randi2.services.*.randomize*(..))")
public Object logRandomize(ProceedingJoinPoint pjp) throws Throwable {
    Object o = pjp.proceed();
    logService.logRandomize(ActionType.RANDOMIZE,
            SecurityContextHolder.getContext().getAuthentication().getName(), Trial.class.cast(o),
            ((TrialSubject) pjp.getArgs()[1]));
    return o;
}

From source file:de.randi2.aspects.RightAndRolesAspects.java

License:Open Source License

/**
 * This around advice grant the rights for an new domain object and register
 * a new user with his special rights. It matches all executions of save
 * methods in the de.randi2.dao package.
 * /*from   ww  w  .  j a  v a  2s.c  o m*/
 * @param pjp
 *            the proceeding join point
 * @throws Throwable
 */
@Around("execution(public void de.randi2.dao.*.create*(de.randi2.model.AbstractDomainObject))")
@Transactional(propagation = Propagation.REQUIRED)
public void afterSaveNewDomainObject(ProceedingJoinPoint pjp) throws Throwable {
    pjp.proceed();
    for (Object o : pjp.getArgs()) {
        //special case for self registration
        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")
                && o instanceof Login) {
            SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken(
                    "anonymousUser", o, new ArrayList<GrantedAuthority>(((Login) o).getAuthorities())));
        }
        Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (o instanceof Login) {
            roleAndRights.registerPerson(((Login) o));
        }
        logger.debug("Register Object (" + o.getClass().getSimpleName() + " id="
                + ((AbstractDomainObject) o).getId() + ")");
        roleAndRights.grantRights(((AbstractDomainObject) o), login.getPerson().getTrialSite());
    }

}

From source file:de.randi2.aspects.SecurityAspects.java

License:Open Source License

/**
 * Aroung Aspect to secure the randomize prozess.
 * //from  w  ww.j a  v a 2s.c  o m
 * @param pjp
 *            the pjp
 * 
 * @return the object
 * 
 * @throws Throwable
 *             the throwable
 */
@Around("execution(public * de.randi2.services.*.randomize*(..))")
@Transactional(propagation = Propagation.REQUIRED)
public Object secRandomize(ProceedingJoinPoint pjp) throws Throwable {
    boolean allowedReadTrial = false;
    Trial trial = (Trial) pjp.getArgs()[0];
    TrialSubject subject = (TrialSubject) pjp.getArgs()[1];

    try {
        Acl acl = aclService.readAclById(new ObjectIdentityHibernate(Trial.class, trial.getId()),
                sidsOf(new PrincipalSid(SecurityContextHolder.getContext().getAuthentication())));
        allowedReadTrial = acl.isGranted(
                permissionsOf(PermissionHibernate.READ, PermissionHibernate.ADMINISTRATION),
                sidsOf(new PrincipalSid(SecurityContextHolder.getContext().getAuthentication())), false);

        if (allowedReadTrial) {
            acl = aclService.readAclById(new ObjectIdentityHibernate(TrialSubject.class, subject.getId()),
                    sidsOf(new PrincipalSid(SecurityContextHolder.getContext().getAuthentication())));
            boolean allowedRandomize = acl.isGranted(
                    permissionsOf(PermissionHibernate.CREATE, PermissionHibernate.ADMINISTRATION),
                    sidsOf(new PrincipalSid(SecurityContextHolder.getContext().getAuthentication())), false);
            if (allowedRandomize) {
                return pjp.proceed();
            }

        }
    } catch (NotFoundException e) {
        logger.info("The user (" + SecurityContextHolder.getContext().getAuthentication().getName()
                + ")have no permission to randomize in this trial!");
    }
    throw new AccessDeniedException("You have not the permission to randomize in this trial!");
}

From source file:duokan.aop.ServiceMonitor.java

License:Apache License

@Around("execution(* duokan.service.*Service.*(..))")
public Object around(ProceedingJoinPoint point) {
    long start = System.currentTimeMillis();
    Object result = null;/*from w w w .  jav a  2 s.c  o m*/
    try {
        result = point.proceed();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
    /** http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html   */
    logger.error("MethodName:{};;Arguments:{};;Result:{};;Calculated in [***[{}]***][msec]s",
            MethodSignature.class.cast(point.getSignature()).getMethod().getName(), point.getArgs(), result,
            System.currentTimeMillis() - start);
    return result;

}

From source file:edu.mayo.cts2.framework.webapp.rest.controller.MethodTimingAspect.java

License:Open Source License

/**
 * Execute.//  w w  w.  j a v a 2s.c o  m
 *
 * @param pjp the pjp
 * @return the object
 * @throws Throwable the throwable
 */
@Around("execution(public *"
        + " edu.mayo.cts2.framework.webapp.rest.controller.*.*(..,edu.mayo.cts2.framework.webapp.rest.command.QueryControl,..))")
public Object execute(final ProceedingJoinPoint pjp) throws Throwable {

    QueryControl queryControl = null;

    //this should never happen
    if (ArrayUtils.isEmpty(pjp.getArgs())) {
        throw new IllegalStateException("Pointcut failure!");
    }

    for (Object arg : pjp.getArgs()) {
        if (arg.getClass() == QueryControl.class) {
            queryControl = (QueryControl) arg;
            break;
        }
    }

    //this also should never happen
    if (queryControl == null) {
        throw new IllegalStateException("Pointcut failure!");
    }

    final AtomicLong threadId = new AtomicLong(-1);

    Future<Object> future = this.executorService.submit(new Callable<Object>() {

        @Override
        public Object call() {
            try {
                threadId.set(Thread.currentThread().getId());

                /*
                 * The model here is that we clear any previous timeout before we launch the job. A design flaw is that we
                 * can't tell if we are clearing a previous timeout that simply hadn't been cleaned up yet, or if we are
                 * clearing a timeout meant for this thread that happened before this thread even launched. The second scenario 
                 * seems unlikely as the minimum timeout is 1 second - hard to believe it would take more than 1 second to 
                 * launch this thread. Plus, this thread would have to launch in the exact window in between the timeout and 
                 * the future.cancel()
                 * 
                 * If the above scenario did defy all odds and happen , it shouldn't cause much harm, as the end result would
                 * be that this thread wouldn't see the cancelled flag - and would churn away for no reason, wasting some cpu
                 * cycles, but doing no other harm.
                 */

                Timeout.clearThreadFlag(threadId.get());
                return pjp.proceed();
            } catch (Throwable e) {

                if (e instanceof Error) {
                    throw (Error) e;
                }

                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }

                throw new RuntimeException(e);
            }
        }
    });

    long time = queryControl.getTimelimit();

    try {
        if (time < 0) {
            return future.get();
        } else {
            return future.get(time, TimeUnit.SECONDS);
        }
    } catch (ExecutionException e) {
        throw e.getCause();
    } catch (TimeoutException e) {
        try {
            //Set the flag for the processing thread to read
            Timeout.setTimeLimitExceeded(threadId.get());

            //Schedule another future to make sure we don't cause a memory leak if the thread IDs aren't being reused (though, they should be)
            //and therefore don't get cleared up by the next run.  Give the running thread 30 seconds to see the cancelled flag before this 
            //cleanup takes place.
            this.scheduledExecutorService.schedule(new Runnable() {
                @Override
                public void run() {
                    Timeout.clearThreadFlag(threadId.get());
                }
            }, 30, TimeUnit.SECONDS);

            //Interrupt the processing thread so it has an opportunity to check the flag and stop.
            future.cancel(true);
        } catch (Exception e1) {
            // don't think this is possible, but just in case...
        }
        throw ExceptionFactory.createTimeoutException(e.getMessage());
    }
}

From source file:edu.umd.ks.cm.util.spring.CmToSisExportAdvice.java

License:Educational Community License

@Transactional(readOnly = false, noRollbackFor = { DoesNotExistException.class }, rollbackFor = {
        Throwable.class })
public CourseInfo updateSisCourseInfo(ProceedingJoinPoint pjp, ContextInfo contextInfo) throws Throwable {

    //Check the inbound course for a special attribute flag
    //which says not to use this advice
    CourseInfo inboundCourse = (CourseInfo) pjp.getArgs()[0];

    //Remove the flag if it's there and save state
    boolean outputToSis = true;
    if (CM20.attributeInfoToMap(inboundCourse.getAttributes()).containsKey(DO_NOT_OUTPUT_TO_SIS)) {
        inboundCourse.getAttributes().remove(DO_NOT_OUTPUT_TO_SIS);
        outputToSis = false;/*w  ww  .ja  v  a2 s. co m*/
    }

    //Proceed with the call
    CourseInfo courseInfo = (CourseInfo) pjp.proceed();

    // If the enablePushToSis environment variable is false, do not write course to SIS
    // (allows us to turn off push for public environment)
    if (!enablePushToSis)
        outputToSis = false;

    //Only output if the course did not have that attribute
    if (outputToSis)
        doUpdateSisCourseInfo(courseInfo, contextInfo);

    // Only do the Audit if parameter passed is true KSCM-1016
    //      boolean outputToWF = true;
    //        if (!enableWFDoc)
    //           outputToWF = false;
    //      
    //      if(outputToWF)
    //         doWorkflowDocument(courseInfo); 
    // End KSCM-1016

    return courseInfo;
}

From source file:edu.umd.ks.cm.util.spring.CmToSisExportAdvice.java

License:Educational Community License

@Transactional(readOnly = false, noRollbackFor = { DoesNotExistException.class }, rollbackFor = {
        Throwable.class })
public void updateSisCourseInfoCluSetUpdate(ProceedingJoinPoint pjp, ContextInfo contextInfo) throws Throwable {
    if (true) {/*from w w w . j a  va2  s .  c o m*/
        return;
    }
    // If the enablePushToSis environment variable is false, do not write course to SIS
    // (allows us to turn off push for public environment)
    if (!enablePushToSis) {
        return;
    }

    Object[] args = pjp.getArgs();
    String newCluSetId = (String) args[0]; // Modified cluSetId
    CluSetInfo newCluSetInfo = (CluSetInfo) args[1]; // Modified cluSetInfo

    // Make sure it's a CluSet we care about (Hardcoded)
    String cluSetName = newCluSetInfo.getName();

    // "cluSetName" will now be a long description name (was just the code before)
    // So, get and check the new map which contains hardcoded set description names.

    Map<String, String> CoreGenCluSetCodeToDescriptionMap = coreGenedClusetMapper
            .getCodeToDescriptionMap(contextInfo);

    Boolean weCare = CoreGenCluSetCodeToDescriptionMap.containsValue(cluSetName);
    if (weCare) {

        // Obtain new Ids
        Set<String> newCluIds = new HashSet<String>(newCluSetInfo.getCluIds());
        List<String> listNewCluIds = newCluSetInfo.getCluIds();

        // Obtain old ("current") Ids via luService call         
        List<String> listOldCluIds = luService.getAllCluIdsInCluSet(newCluSetId, contextInfo);
        Set<String> oldCluIds = new HashSet<String>(listOldCluIds);

        // Removed Courses (old - new)
        Set<String> removedCluIds = new HashSet<String>(oldCluIds);
        removedCluIds.removeAll(newCluIds);
        System.out.println("Removed these clu IDs: " + removedCluIds);
        for (String cluId : removedCluIds) {
            // Translate from VerIndId to current Ver Id to get current courseInfo obj
            VersionDisplayInfo vdi = courseService
                    .getCurrentVersion(CourseServiceConstants.COURSE_NAMESPACE_URI, cluId, contextInfo);
            CourseInfo courseInfo = courseService.getCourse(vdi.getId(), contextInfo);
            //sisCmDao.updateSisCourseInfo(courseInfo, "P");//FIXME we should test to see if there is a pushed record before we update vs create
        }

        // Added Courses (new - old)
        Set<String> addedCluIds = new HashSet<String>(newCluIds);
        addedCluIds.removeAll(oldCluIds);
        System.out.println("Added these clu IDs: " + addedCluIds);
        for (String cluId : addedCluIds) {
            // Translate from VerIndId to current Ver Id to get current courseInfo obj
            VersionDisplayInfo vdi = courseService
                    .getCurrentVersion(CourseServiceConstants.COURSE_NAMESPACE_URI, cluId, contextInfo);
            CourseInfo courseInfo = courseService.getCourse(vdi.getId(), contextInfo);
            //sisCmDao.updateSisCourseInfo(courseInfo, "P");//FIXME we should test to see if there is a pushed record before we update vs create                        
        }
    } // end if weCare
}

From source file:edu.utah.further.dts.impl.aspect.DtsTransactionAspect.java

License:Apache License

/**
 * Execute DTS session wrapping for an applicable join point.
 * //from  ww w . j  a va 2s.c o m
 * @param jp
 *            proceeding join point
 * @param dtsTransactionalAnnotation
 *            DTS-transactionality annotation
 * @return proceeding joint point's return value
 * @throws Throwable
 *             if wrapped method invocation throws an exception
 */
private Object wrapInDtsSession(final ProceedingJoinPoint jp, final DtsTransactional dtsTransactionalAnnotation)
        throws Throwable {
    // Fetch join point parameters
    final String methodName = jp.getSignature().getDeclaringTypeName() + "." + jp.getSignature().getName();
    final DtsPropagation propagation = dtsTransactionalAnnotation.propagation();

    // Validate session boundaries
    final boolean sessionOpen = connectionFactory.isSessionOpen();
    if ((propagation == DtsPropagation.NEVER) && sessionOpen) {
        throw new IllegalStateException("DTS session boundaries violation: method " + methodName
                + " declares propagation " + propagation + " but there is currently an open DTS session");
    }
    if ((propagation == DtsPropagation.MANDATORY) && !sessionOpen) {
        throw new IllegalStateException("DTS session boundaries violation: method " + methodName
                + " declares propagation " + propagation + " but there is currently no open DTS session");
    }

    // Wrap method invocation in a DTS session if needed
    final boolean needToCreateNewSession = !sessionOpen && (propagation == DtsPropagation.REQUIRED);
    if (needToCreateNewSession) {
        if (log.isDebugEnabled()) {
            log.debug("Starting session for " + methodName + ", propagation " + propagation);
        }
        connectionFactory.startSession();
    }

    // Treat both happy and failed paths. If an exception is thrown, save it
    // in throwable; then close the session; then process throwable
    Throwable throwable = null;
    Object retval = null;
    try {
        retval = jp.proceed();
    } catch (final Throwable t) {
        throwable = t;
    }

    if (needToCreateNewSession) {
        if (log.isDebugEnabled()) {
            log.debug("Closing session for " + methodName);
        }
        connectionFactory.closeSession();
    }

    // ========================
    // Exception handling
    // ========================
    if (throwable != null) {
        // Discover if there's an options argument to the method; otherwise
        // always throw an exception
        final Object[] args = jp.getArgs();
        DtsOptions options = discoverDtsOptionsMethodArgument(args);
        if (options == null) {
            options = newDefaultOptions();
        }

        // Decide if to throw a FURTHeR-wrapped exception
        DtsUtil.wrapAndThrowApelonException(options.isThrowExceptionOnFailure(), throwable);

        // If not, throw the raw exception
        throw throwable;
    }
    return retval;
}

From source file:fi.helsinki.opintoni.aop.logging.LoggingAspect.java

License:Open Source License

@Around("loggingPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (shouldSkip(joinPoint)) {
        return joinPoint.proceed();
    }/*from   w ww  . j  a v a  2 s  . c o m*/

    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
                joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}

From source file:fm.pattern.valex.annotations.ValidationAdvisor.java

License:Apache License

private Object around(ProceedingJoinPoint pjp, boolean throwException, Class<?>... groups) throws Throwable {
    Object[] arguments = pjp.getArgs();
    if (arguments.length == 0) {
        return pjp.proceed();
    }/* w  w  w .j  a  v a2  s . c  om*/

    Result<Object> result = validate(pjp.getArgs()[0], groups);
    if (result.rejected()) {
        if (throwException) {
            throw result.getException();
        }
        return result;
    }

    return pjp.proceed();
}