Example usage for org.aspectj.lang ProceedingJoinPoint getTarget

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

Introduction

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

Prototype

Object getTarget();

Source Link

Document

Returns the target object.

Usage

From source file:org.apache.ignite.compute.gridify.aop.aspectj.GridifySetToSetAspectJAspect.java

License:Apache License

/**
 * Aspect implementation which executes grid-enabled methods on remote
 * nodes.//  w w w. j  a va  2s  . c  o m
 *
 * @param joinPnt Join point provided by AspectJ AOP.
 * @return Method execution result.
 * @throws Throwable If execution failed.
 */
@SuppressWarnings({ "ProhibitedExceptionDeclared", "ProhibitedExceptionThrown", "CatchGenericClass" })
@Around("execution(@org.apache.ignite.compute.gridify.GridifySetToSet * *(..)) && !cflow(call(* org.apache.ignite.compute.ComputeJob.*(..)))")
public Object gridify(ProceedingJoinPoint joinPnt) throws Throwable {
    Method mtd = ((MethodSignature) joinPnt.getSignature()).getMethod();

    GridifySetToSet ann = mtd.getAnnotation(GridifySetToSet.class);

    assert ann != null : "Intercepted method does not have gridify annotation.";

    // Since annotations in Java don't allow 'null' as default value
    // we have accept an empty string and convert it here.
    // NOTE: there's unintended behavior when user specifies an empty
    // string as intended grid name.
    // NOTE: the 'ann.gridName() == null' check is added to mitigate
    // annotation bugs in some scripting languages (e.g. Groovy).
    String gridName = F.isEmpty(ann.gridName()) ? null : ann.gridName();

    if (G.state(gridName) != STARTED)
        throw new IgniteCheckedException("Grid is not locally started: " + gridName);

    GridifyNodeFilter nodeFilter = null;

    if (!ann.nodeFilter().equals(GridifyNodeFilter.class))
        nodeFilter = ann.nodeFilter().newInstance();

    // Check method return type.
    checkMethodSignature(mtd);

    GridifyArgumentBuilder argBuilder = new GridifyArgumentBuilder();

    // Creates task argument.
    GridifyRangeArgument arg = argBuilder.createTaskArgument(mtd.getDeclaringClass(), mtd.getName(),
            mtd.getReturnType(), mtd.getParameterTypes(), mtd.getParameterAnnotations(), joinPnt.getArgs(),
            joinPnt.getTarget());

    if (!ann.interceptor().equals(GridifyInterceptor.class)) {
        // Check interceptor first.
        if (!ann.interceptor().newInstance().isGridify(ann, arg))
            return joinPnt.proceed();
    }

    // Proceed locally for negative threshold parameter.
    if (ann.threshold() < 0)
        return joinPnt.proceed();

    // Analyse where to execute method (remotely or locally).
    if (arg.getInputSize() != UNKNOWN_SIZE && arg.getInputSize() <= ann.threshold())
        return joinPnt.proceed();

    // Check is split to jobs allowed for input method argument with declared splitSize.
    checkIsSplitToJobsAllowed(arg, ann);

    try {
        Ignite ignite = G.ignite(gridName);

        return execute(ignite.compute(), joinPnt.getSignature().getDeclaringType(), arg, nodeFilter,
                ann.threshold(), ann.splitSize(), ann.timeout());
    } catch (Throwable e) {
        for (Class<?> ex : ((MethodSignature) joinPnt.getSignature()).getMethod().getExceptionTypes()) {
            // Descend all levels down.
            Throwable cause = e.getCause();

            while (cause != null) {
                if (ex.isAssignableFrom(cause.getClass()))
                    throw cause;

                cause = cause.getCause();
            }

            if (ex.isAssignableFrom(e.getClass()))
                throw e;
        }

        throw new GridifyRuntimeException("Undeclared exception thrown: " + e.getMessage(), e);
    }
}

From source file:org.apache.ignite.compute.gridify.aop.aspectj.GridifySetToValueAspectJAspect.java

License:Apache License

/**
 * Aspect implementation which executes grid-enabled methods on remote
 * nodes./*from ww  w .jav  a2  s .  c  o m*/
 *
 * @param joinPnt Join point provided by AspectJ AOP.
 * @return Method execution result.
 * @throws Throwable If execution failed.
 */
@SuppressWarnings({ "ProhibitedExceptionDeclared", "ProhibitedExceptionThrown", "CatchGenericClass" })
@Around("execution(@org.apache.ignite.compute.gridify.GridifySetToValue * *(..)) && !cflow(call(* org.apache.ignite.compute.ComputeJob.*(..)))")
public Object gridify(ProceedingJoinPoint joinPnt) throws Throwable {
    Method mtd = ((MethodSignature) joinPnt.getSignature()).getMethod();

    GridifySetToValue ann = mtd.getAnnotation(GridifySetToValue.class);

    assert ann != null : "Intercepted method does not have gridify annotation.";

    // Since annotations in Java don't allow 'null' as default value
    // we have accept an empty string and convert it here.
    // NOTE: there's unintended behavior when user specifies an empty
    // string as intended grid name.
    // NOTE: the 'ann.gridName() == null' check is added to mitigate
    // annotation bugs in some scripting languages (e.g. Groovy).
    String gridName = F.isEmpty(ann.gridName()) ? null : ann.gridName();

    if (G.state(gridName) != STARTED)
        throw new IgniteCheckedException("Grid is not locally started: " + gridName);

    GridifyNodeFilter nodeFilter = null;

    if (!ann.nodeFilter().equals(GridifyNodeFilter.class))
        nodeFilter = ann.nodeFilter().newInstance();

    // Check is method allowed for gridify.
    checkMethodSignature(mtd);

    GridifyArgumentBuilder argBuilder = new GridifyArgumentBuilder();

    // Creates task argument.
    GridifyRangeArgument arg = argBuilder.createTaskArgument(mtd.getDeclaringClass(), mtd.getName(),
            mtd.getReturnType(), mtd.getParameterTypes(), mtd.getParameterAnnotations(), joinPnt.getArgs(),
            joinPnt.getTarget());

    if (!ann.interceptor().equals(GridifyInterceptor.class)) {
        // Check interceptor first.
        if (!ann.interceptor().newInstance().isGridify(ann, arg))
            return joinPnt.proceed();
    }

    // Proceed locally for negative threshold parameter.
    if (ann.threshold() < 0)
        return joinPnt.proceed();

    // Analyse where to execute method (remotely or locally).
    if (arg.getInputSize() != UNKNOWN_SIZE && arg.getInputSize() <= ann.threshold())
        return joinPnt.proceed();

    // Check is split to jobs allowed for input method argument with declared splitSize.
    checkIsSplitToJobsAllowed(arg, ann);

    try {
        Ignite ignite = G.ignite(gridName);

        return execute(mtd, ignite.compute(), joinPnt.getSignature().getDeclaringType(), arg, nodeFilter,
                ann.threshold(), ann.splitSize(), ann.timeout());
    } catch (Throwable e) {
        for (Class<?> ex : ((MethodSignature) joinPnt.getSignature()).getMethod().getExceptionTypes()) {
            // Descend all levels down.
            Throwable cause = e.getCause();

            while (cause != null) {
                if (ex.isAssignableFrom(cause.getClass()))
                    throw cause;

                cause = cause.getCause();
            }

            if (ex.isAssignableFrom(e.getClass()))
                throw e;
        }

        throw new GridifyRuntimeException("Undeclared exception thrown: " + e.getMessage(), e);
    }
}

From source file:org.apache.rave.synchronization.SynchronizingAspect.java

License:Apache License

@Around("synchronizePointcut()")
public Object synchronizeInvocation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
    Method method = methodSignature.getMethod();
    Object target = proceedingJoinPoint.getTarget();
    Object[] args = proceedingJoinPoint.getArgs();
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
    Synchronized annotation = getAnnotation(targetClass, method);
    Validate.notNull(annotation, "Could not find @Synchronized annotation!");

    Lock lock = getLock(targetClass, method, args, annotation);
    if (lock == null) {
        logger.debug(//w w  w  . j  a v a2s .  c o m
                "No lock obtained for call [{}] on targetClass [{}] - proceeding without synchronization on "
                        + "thread {}",
                new Object[] { method.getName(), targetClass.getName(), Thread.currentThread().getId() });
        return proceedingJoinPoint.proceed();
    } else {
        try {
            logger.debug(
                    "Lock obtained for call [{}] on targetClass [{}] - proceeding with synchronization on thread {}",
                    new Object[] { method.getName(), targetClass.getName(), Thread.currentThread().getId() });
            lock.lock();
            return proceedingJoinPoint.proceed();
        } finally {
            lock.unlock();
            lockService.returnLock(lock);
        }
    }
}

From source file:org.apache.rave.synchronization.SynchronizingAspectTest.java

License:Apache License

private ProceedingJoinPoint prepareJoinPoint(String expectedDiscriminator, String expectedId,
        TestService service, Method expectedMethod, TestObject argument, Object[] joinPointArgs)
        throws Throwable {
    MethodSignature methodSignature = createMock(MethodSignature.class);
    expect(methodSignature.getMethod()).andReturn(expectedMethod);
    replay(methodSignature);//from  ww w  . ja  v  a 2s .c o  m

    ProceedingJoinPoint joinPoint = createMock(ProceedingJoinPoint.class);
    expect(joinPoint.getSignature()).andReturn(methodSignature);
    expect(joinPoint.getTarget()).andReturn(service);
    expect(joinPoint.getArgs()).andReturn(joinPointArgs);
    expect(joinPoint.proceed()).andReturn(expectedMethod.invoke(service, argument));
    replay(joinPoint);

    Lock lock = new ReentrantLock();
    expect(lockService.borrowLock(expectedDiscriminator, expectedId)).andReturn(lock);
    lockService.returnLock(lock);
    replay(lockService);
    return joinPoint;
}

From source file:org.apache.syncope.core.logic.LogicInvocationHandler.java

License:Apache License

@Around("execution(* org.apache.syncope.core.logic.AbstractLogic+.*(..))")
public Object around(final ProceedingJoinPoint joinPoint) throws Throwable {
    Class<?> clazz = joinPoint.getTarget().getClass();

    Object[] input = joinPoint.getArgs();

    String category = clazz.getSimpleName();

    MethodSignature ms = (MethodSignature) joinPoint.getSignature();
    Method method = ms.getMethod();

    String event = joinPoint.getSignature().getName();

    AuditElements.Result result = null;
    Object output = null;/* w w  w . j av a  2s  .c om*/
    Object before = null;

    try {
        LOG.debug("Before {}.{}({})", clazz.getSimpleName(), event,
                input == null || input.length == 0 ? "" : Arrays.asList(input));

        try {
            before = ((AbstractLogic) joinPoint.getTarget()).resolveBeanReference(method, input);
        } catch (UnresolvedReferenceException ignore) {
            LOG.debug("Unresolved bean reference ...");
        }

        output = joinPoint.proceed();
        result = AuditElements.Result.SUCCESS;

        LOG.debug("After returning {}.{}: {}", clazz.getSimpleName(), event, output);
        return output;
    } catch (Throwable t) {
        output = t;
        result = AuditElements.Result.FAILURE;

        LOG.debug("After throwing {}.{}", clazz.getSimpleName(), event);
        throw t;
    } finally {
        notificationManager.createTasks(AuditElements.EventCategoryType.LOGIC, category, null, event, result,
                before, output, input);

        auditManager.audit(AuditElements.EventCategoryType.LOGIC, category, null, event, result, before, output,
                input);
    }
}

From source file:org.apache.syncope.core.rest.controller.ControllerHandler.java

License:Apache License

@Around("execution(* org.apache.syncope.core.rest.controller.AbstractController+.*(..))")
public Object around(final ProceedingJoinPoint joinPoint) throws Throwable {
    final Class<?> clazz = joinPoint.getTarget().getClass();

    final Object[] input = joinPoint.getArgs();

    final String category = clazz.getSimpleName();

    final MethodSignature ms = (MethodSignature) joinPoint.getSignature();
    Method method = ms.getMethod();

    final String event = joinPoint.getSignature().getName();

    AuditElements.Result result = null;
    Object output = null;/*from w  w w . j av  a 2s .co  m*/
    Object before = null;

    try {
        LOG.debug("Before {}.{}({})", clazz.getSimpleName(), event,
                input == null || input.length == 0 ? "" : Arrays.asList(input));

        try {
            before = ((AbstractController) joinPoint.getTarget()).resolveBeanReference(method, input);
        } catch (UnresolvedReferenceException ignore) {
            LOG.debug("Unresolved bean reference ...");
        }

        output = joinPoint.proceed();
        result = AuditElements.Result.SUCCESS;

        LOG.debug("After returning {}.{}: {}", clazz.getSimpleName(), event, output);
        return output;
    } catch (Throwable t) {
        output = t;
        result = AuditElements.Result.FAILURE;

        LOG.debug("After throwing {}.{}", clazz.getSimpleName(), event);
        throw t;
    } finally {
        notificationManager.createTasks(AuditElements.EventCategoryType.REST, category, null, event, result,
                before, output, input);

        auditManager.audit(AuditElements.EventCategoryType.REST, category, null, event, result, before, output,
                input);
    }
}

From source file:org.apache.wicket.metrics.WicketMetrics.java

License:Apache License

/**
 * Renders the class name of the given join point
 * /*from ww  w .  j  a  v  a 2  s.c om*/
 * @param joinPoint
 *            the join point to get the class of
 * @return the class name representation
 */
public String renderClassName(ProceedingJoinPoint joinPoint) {
    return joinPoint != null && joinPoint.getTarget() != null
            ? "/" + joinPoint.getTarget().getClass().getName().replace('.', '_')
            : "";
}

From source file:org.betaconceptframework.astroboa.engine.service.security.aspect.SecureContentServiceAspect.java

License:Open Source License

private Object grantOrDenyAccessToContentObject(ProceedingJoinPoint proceedingJoinPoint,
        String contentObjectIdOrSystemName, Object[] methodParameters,
        ResourceRepresentationType contentObjectOutput) {
    if (contentObjectIdIsNotNull(contentObjectIdOrSystemName)) {
        SecurityContext activeSecurityContext = AbstractSecureContentObjectAspect.retrieveSecurityContext();

        //Retrieve jcr node which corresponds to requested content object
        Node contentObjectNode = null;

        try {//from w  w w  . ja  v  a2  s .  co  m

            if (!(proceedingJoinPoint.getTarget() instanceof ContentServiceImpl)) {
                return generateEmptyOutcome(contentObjectOutput);
            }

            contentObjectNode = ((ContentServiceImpl) proceedingJoinPoint.getTarget())
                    .getContentObjectNodeByIdOrSystemName(contentObjectIdOrSystemName);

            //contentObject = (ContentObject) proceedingJoinPoint.proceed(methodParameters);

            if (contentObjectNode == null) {
                return generateEmptyOutcome(contentObjectOutput);
            }

            String userId = activeSecurityContext.getIdentity();

            // if the authenticated user has not been granted the role: ROLE_CMS_INTERNAL_VIEWER 
            // then we allow her to read only published content objects i.e. those that their status is equal to "published" or "publishedAndArchived".
            // As of today a published content object overrules any "read" security option to prevent complexities in security rule handling 
            // and remove the extra effort required for the publisher of content objects 
            // It is not very convenient to require to change the "read" security option of published content objects to "ALL" to allow to be read by REPOSITORY 
            // and then when publication status ends revert back to previous security settings. 
            // Additionally "ALL" should be interpreted as "REPOSITORY PHYSICAL PERSONS or REPOSITORY USERS WHICH ARE EXPLICITLY GRANTED THE PERMISSION TO VIEW THE REPOSITORY, 
            // i.e. those in role ROLE_CMS_INTERNAL_VIEWER".
            // Anonymous is not an actual user registered in the identity store. It is a convention introduced in order to cope with the security rule that we always need some user 
            // in order to permit access to content. So for any user that tries to see the repository without logging in, the front-end system, e.g. the web application, should
            // silently perform a virtual login as the anonymous user.
            //
            // Through the above convention it becomes really easy to publish and un-publish content objects. 
            // The idea is that if someone publishes a content object then she implicitly removes any read restrictions.
            // All other restrictions apply and furthermore read restrictions are still there and remain valid when status is not set to "published" any more.
            // We may revisit this convention if the use of the repository reveals another way of interpreting anonymous requests and published objects
            //
            // Be aware that since the anonymous is a virtual user it is not granted any roles. So allowing users that are not granted the role:ROLE_CMS_INTERNAL_VIEWER 
            // to view only published content objects is sufficient and we do not actually need to check whether the user is the anonymous.

            // However we explicitly check if the user identity is the anonymous in order to prevent cases where some administrator by mistake or on purpose 
            // registers the anonymous as a real user and assigns it the role ROLE_CMS_INTERNAL_VIEWER. 
            // This would result in letting all not logged in Internet users to view internal unpublished content. So we introduce the extra rule that 
            // anonymous is only viewing published objects despite any roles that may have been assigned to it.

            //if (StringUtils.equals(userId, IdentityPrincipal.ANONYMOUS) ||
            if (!AbstractSecureContentObjectAspect.userHasRole(activeSecurityContext,
                    CmsRoleAffiliationFactory.INSTANCE
                            .getCmsRoleAffiliationForActiveRepository(CmsRole.ROLE_CMS_INTERNAL_VIEWER))) {

                //Any user that is NOT GRANTED the role:ROLE_CMS_INTERNAL_VIEWER can access ONLY PUBLISHED or PublishedAndArchived content objects
                //StringProperty profileContentObjectStatusProperty = (StringProperty)contentObject.getCmsProperty("profile.contentObjectStatus");

                //if (profileContentObjectStatusProperty == null || profileContentObjectStatusProperty.hasNoValues()){
                if (!contentObjectNode.hasProperty("profile/contentObjectStatus")) {
                    logger.debug(
                            "User {} has not been granted access to content object {} because she has not been granted role ROLE_CMS_INTERNAL_VIEWER and "
                                    + " content object status is either null or has no values",
                            userId, contentObjectIdOrSystemName);
                    return generateEmptyOutcome(contentObjectOutput);
                }

                //String profileContentObjectStatus = profileContentObjectStatusProperty.getSimpleTypeValue();
                String profileContentObjectStatus = contentObjectNode.getProperty("profile/contentObjectStatus")
                        .getString();

                if (StringUtils.equals(ContentObjectStatus.published.toString(), profileContentObjectStatus)
                        || StringUtils.equals(ContentObjectStatus.publishedAndArchived.toString(),
                                profileContentObjectStatus)) {
                    logger.debug(
                            "User {} has been granted access to content object {} because she has not been granted role ROLE_CMS_INTERNAL_VIEWER but "
                                    + " content object status is {}",
                            new Object[] { userId, contentObjectIdOrSystemName, profileContentObjectStatus });

                    //
                    if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                            && methodParameters != null && methodParameters.length > 1
                            && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                        //User has provided object system name. replace it with object identifier
                        methodParameters[0] = contentObjectNode
                                .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                    }

                    return proceedingJoinPoint.proceed(methodParameters);
                }

                logger.debug(
                        "User {} has not been granted access to content object {} because she has not been granted role ROLE_CMS_INTERNAL_VIEWER and "
                                + " content object status '{}' is not published or published and archived",
                        new Object[] { userId, contentObjectIdOrSystemName, profileContentObjectStatus });

                return generateEmptyOutcome(contentObjectOutput);

            } else if (!AbstractSecureContentObjectAspect.userHasRole(activeSecurityContext,
                    CmsRoleAffiliationFactory.INSTANCE
                            .getCmsRoleAffiliationForActiveRepository(CmsRole.ROLE_ADMIN))) { // for USER with ROLE_ADMIN we do not impose any security constraint

                // we will generate criteria to generate the following security restriction
                // (@betaconcept:OwnerCmsIdentifier = UUIDOfUserExecutingTheQuery OR
                // betaconcept:CanBeReadBy = 'REPOSITORY' OR (betaconcept:CanBeReadBy != 'NONE'
                // AND (betaconcept:CanBeReadBy = "USR_" + userId OR
                // betaconcept:CanBeReadBy = "GRP_" + userGroupId1 OR
                // betaconcept:CanBeReadBy = "GRP_" + userGroupId2 ....)))

                //User has role ROLE_CMS_INTERNAL_VIEWER

                //Check if user owns this content object
                //RepositoryUser owner = contentObject.getOwner();

                Subject subject = activeSecurityContext.getSubject();

                if (subject != null
                        && CollectionUtils.isNotEmpty(subject.getPrincipals(RepositoryUserIdPrincipal.class))
                        && contentObjectNode.hasProperty(CmsBuiltInItem.OwnerCmsIdentifier.getJcrName())) {
                    RepositoryUserIdPrincipal ownerIdPrincipal = subject
                            .getPrincipals(RepositoryUserIdPrincipal.class).iterator().next();

                    String ownerId = contentObjectNode
                            .getProperty(CmsBuiltInItem.OwnerCmsIdentifier.getJcrName()).getString();

                    if (StringUtils.equals(ownerId, ownerIdPrincipal.getName())) {
                        logger.debug(
                                "User {} has been granted access to content object {} because she owns the content object",
                                userId, contentObjectIdOrSystemName);

                        if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                                && methodParameters != null && methodParameters.length > 1
                                && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                            //User has provided object system name. replace it with object identifier
                            methodParameters[0] = contentObjectNode
                                    .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                        }

                        return proceedingJoinPoint.proceed(methodParameters);
                    }
                }

                //TODO : In case RepositoryUserIdPrincipal is not available, is it safe to just do the following check
                //  owner.getExternalId() == userId

                //User does not own content object. Check access right defined in property
                //accessibility.canBeReadBy
                //StringProperty accessibilityCanBeReadByProperty = (StringProperty) contentObject.getCmsProperty("accessibility.canBeReadBy");

                //if (accessibilityCanBeReadByProperty == null || accessibilityCanBeReadByProperty.hasNoValues()){
                if (!contentObjectNode.hasProperty("accessibility/canBeReadBy")) {
                    logger.debug(
                            "User {} has not been granted access to content object {} because although she does not own content objects and  "
                                    + " content object does not have any value to property accessibility.canBeReadBy ",
                            userId, contentObjectIdOrSystemName);
                    return generateEmptyOutcome(contentObjectOutput);
                }

                //List<String> canBeReadBy = accessibilityCanBeReadByProperty.getSimpleTypeValues();
                Value[] canBeReadByArr = contentObjectNode.getProperty("accessibility/canBeReadBy").getValues();

                List<String> canBeReadBy = new ArrayList<String>();
                for (Value value : canBeReadByArr) {
                    canBeReadBy.add(value.getString());
                }

                //If canBeReadBy contains REPOSITORY value then access is granted
                if (canBeReadBy.contains(ContentAccessMode.ALL.toString())) {
                    logger.debug(
                            "User {} has been granted access to content object {} because although she does not own content object, "
                                    + " content object property accessibility.canBeReadBy contains value REPOSITORY :{}",
                            new Object[] { userId, contentObjectIdOrSystemName, canBeReadBy.toString() });

                    if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                            && methodParameters != null && methodParameters.length > 1
                            && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                        //User has provided object system name. replace it with object identifier
                        methodParameters[0] = contentObjectNode
                                .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                    }

                    return proceedingJoinPoint.proceed(methodParameters);
                }

                //If canBeReadBy contains NONE value then access is denied
                if (canBeReadBy.contains(ContentAccessMode.NONE.toString())) {
                    logger.debug(
                            "User {} has not been granted access to content object {} because she does not own content object and  "
                                    + " content object property accessibility.canBeReadBy contains value NONE :{}",
                            new Object[] { userId, contentObjectIdOrSystemName, canBeReadBy.toString() });
                    return generateEmptyOutcome(contentObjectOutput);
                }

                //canBeReadBy contains neither REPOSITORY nor NONE
                //access is granted only if either to any of the user groups or explicitly to the user itself
                // so we add the user id into the list of group ids. All ids are appropriately prefixed by either URS_ or GRP_ to
                // distinguish between user and group ids

                // Security in each content object is defined by four lists stored as part of each object (i.e. a special complex property of each content object).
                //    The four lists define which user or role (role may be a role group also) can respectively read, update, delete and tag the object.
                //    Each of the four lists inside each object contain a mixed set of the userIds and Roles  which 
                // So we get the user roles prefixed by "GRP_" in order to discriminate them from user ids which are prefixed with "USR_"
                List<String> prefixedRoles = activeSecurityContext.getAllRoles();

                prefixedRoles.add(userId);

                for (String prefixedRole : prefixedRoles) {
                    if (canBeReadBy.contains(prefixedRole)) {
                        logger.debug(
                                "User {} has been granted access to content object {} because although she does not own content object,   "
                                        + " content object property accessibility.canBeReadBy contains role {} ",
                                new Object[] { userId, contentObjectIdOrSystemName, prefixedRole });

                        if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                                && methodParameters != null && methodParameters.length > 1
                                && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                            //User has provided object system name. replace it with object identifier
                            methodParameters[0] = contentObjectNode
                                    .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                        }

                        return proceedingJoinPoint.proceed(methodParameters);
                    }
                }

                logger.debug(
                        "User {} has not been granted access to content object {} because she does not own content object and  "
                                + " content object property accessibility.canBeReadBy does not contain any role which has been assigned to user. \nAccessibility.CanBeReadBy values {}"
                                + "\n Granted Roles to user {}",
                        new Object[] { userId, contentObjectIdOrSystemName, canBeReadBy, prefixedRoles });
                return generateEmptyOutcome(contentObjectOutput);
            } else {
                logger.debug(
                        "User {} has been granted access to content object {} because she has been granted role ROLE_ADMIN ",
                        new Object[] { userId, contentObjectIdOrSystemName });

                if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                        && methodParameters != null && methodParameters.length > 1
                        && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                    //User has provided object system name. replace it with object identifier
                    methodParameters[0] = contentObjectNode
                            .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                }

                return proceedingJoinPoint.proceed(methodParameters);
            }
        } catch (CmsException e) {
            throw e;
        } catch (Throwable e) {
            throw new CmsException(e);
        }
    } else {
        //No point to proceed to actual method since no content object id is provided
        logger.debug("No content object exists with id {} therefore no restrictions are imposed",
                contentObjectIdOrSystemName);
        return generateEmptyOutcome(contentObjectOutput);
    }

}

From source file:org.biopax.validator.impl.ExceptionsAspect.java

License:Open Source License

/**
 * This captures the exceptions that occur 
 * during the model build and, more important,
 * associates the just created model//w ww.j a v  a  2  s.  com
 * with the corresponding validation result
 * (this is the earliest possibility to do so)!
 * 
 * @param jp
 */
@Around("execution(void org.biopax.paxtools.io.SimpleIOHandler.createAndBind(*)) " + "&& args(model)")
public void adviseCreateAndBind(ProceedingJoinPoint jp, Model model) {
    SimpleIOHandler reader = (SimpleIOHandler) jp.getTarget();

    // associate the model with the reader (and validation results)
    validator.indirectlyAssociate(reader, model);

    try {
        jp.proceed();
    } catch (Throwable ex) {
        reportException(ex, reader, "syntax.error", "SimpleIOHandler.createAndBind interceptor", null);
    }
}

From source file:org.biopax.validator.impl.ExceptionsAspect.java

License:Open Source License

@Around("execution(private void org.biopax.paxtools.io.SimpleIOHandler.bindValue(..))"
        + " && args(triple, model)")
public void adviseBindValue(ProceedingJoinPoint jp, Triple triple, Model model) {
    if (log.isDebugEnabled())
        log.debug("adviseBindValue, triple: " + triple);

    SimpleIOHandler reader = (SimpleIOHandler) jp.getTarget();
    // try to find the best object to report about...
    Object o = reader;//from  w  w  w . j  av  a 2  s  .  com
    BioPAXElement el = model.getByID(triple.domain);
    if (el != null) {
        o = el;
        PropertyEditor<?, ?> editor = reader.getEditorMap().getEditorForProperty(triple.property,
                el.getModelInterface());
        if (editor == null) {
            // auto-fix (for some)
            if (triple.property.equals("taxonXref")) {
                report(el, "unknown.property", "SimpleIOHandler.bindValue interceptor", true,
                        triple.property + " - replaced with 'xref'");
                triple.property = "xref";
            } else {
                report(el, "unknown.property", "SimpleIOHandler.bindValue interceptor", false,
                        triple.property + " - skipped");
            }
        }
    }

    try {
        jp.proceed();
    } catch (Throwable t) {
        reportException(t, o, "syntax.error", "SimpleIOHandler.bindValue interceptor", triple.toString());
    }
}