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.maydesk.base.util.AspectChangedValueHandler.java

License:Mozilla Public License

@Around(value = "execution(* storeInputProperty(..))")
public void handleStoreInputProperty(ProceedingJoinPoint point) throws Throwable {
    point.proceed();/* www .  j a  v  a2s.  co  m*/
    if (point.getArgs()[1] instanceof IChangeSupportable) {
        IChangeSupportable cs = (IChangeSupportable) point.getArgs()[1];
        String propertyName = (String) point.getArgs()[2];
        System.out.println("XXX " + propertyName + " XXXXXXXXXXXXXXXXXXXXXXXXX");
        if (propertyName.equals(cs.getPropertyName())) {
            Object newInput = point.getArgs()[4];
            ((Component) cs).processInput(propertyName, newInput);
            Object newValue = cs.getValue();
            PDBinding changeSupport = cs.getChangeSupport();
            if (changeSupport != null) {
                changeSupport.doChange(cs, newValue);
            }
        }
    }
}

From source file:com.mpobjects.rtcalltree.rec.AspectJRecorder.java

License:Apache License

/**
 * @param aJoinPoint//from   w w w.j  a v a 2 s . c  o  m
 * @return
 */
protected MutableCalltreeEntry createEntry(ProceedingJoinPoint aJoinPoint) {
    final Signature signature = aJoinPoint.getSignature();
    String className = signature.getDeclaringTypeName();
    final String methodName = signature.getName();
    final Object target = aJoinPoint.getTarget();
    if (target != null) {
        if (!Proxy.isProxyClass(target.getClass())) {
            className = target.getClass().getName();
        }
    }
    CalltreeEntryImpl entry = new CalltreeEntryImpl(className, methodName);
    /* Spring AOP throws exceptions on getFileName() etc. instead of just returning null for SourceLocation */
    // if (aJoinPoint.getSourceLocation() != null) {
    // entry.setSourceFilename(aJoinPoint.getSourceLocation().getFileName());
    // entry.setSourceLine(aJoinPoint.getSourceLocation().getLine());
    // }
    if (argumentConverter != null && aJoinPoint.getArgs() != null) {
        entry.setParameterValues(argumentConverter.convertArguments(aJoinPoint.getArgs()));
    }
    if (signature instanceof CodeSignature) {
        entry.setParameterTypes(getTypeNames(((CodeSignature) signature).getParameterTypes()));
    }
    return entry;
}

From source file:com.mycom.products.mywebsite.backend.aspect.ServletExceptionHandlerAspect.java

License:Open Source License

@Around(value = "methodAnnotatedWithHandleServletException(servletException) && publicMethod() && !initBinderMethod()")
public String handleExeptionforServletMethods(ProceedingJoinPoint joinPoint,
        HandleServletException servletException) throws Throwable {
    String pageSuccessReturn = null;
    String errorView = servletException.errorView();
    PageMode pageMode = servletException.pageMode();
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    ValidateEntity validationMapper = method.getAnnotation(ValidateEntity.class);
    Model model = null;/*w w w. java2  s  .  co  m*/
    Errors errors = null;
    Object validationTarget = null;
    Object[] arguments = joinPoint.getArgs();
    for (Object arg : arguments) {
        if (arg != null) {
            if (arg instanceof BindingAwareModelMap) {
                model = (Model) arg;
            }
            if (validationMapper != null && arg instanceof BeanPropertyBindingResult) {
                errors = (Errors) arg;
            }
            if (validationMapper != null && arg instanceof BaseBean) {
                validationTarget = arg;
            }
        }
    }
    try {
        if (validationMapper != null) {
            BaseValidator validator = appContext.getBean(validationMapper.validator());
            validator.setPageMode(pageMode);
            validator.validate(validationTarget, errors);
            if (errors.hasErrors()) {
                throw new ValidationFailedException(BaseBean.LOG_PREFIX + "Validation failed for '"
                        + validationTarget.getClass().getSimpleName() + "'." + BaseBean.LOG_SUFFIX);
            }
        }
        pageSuccessReturn = (String) joinPoint.proceed();
    } catch (Exception e) {
        errorLogger.error(BaseBean.LOG_BREAKER_OPEN);
        errorLogger.error(e.getMessage(), e);
        if (errorLogger.isDebugEnabled()) {
            if (e instanceof ValidationFailedException) {
                Map<String, String> validationErrors = new HashMap<>();
                List<FieldError> errorFields = errors.getFieldErrors();
                errorFields.forEach(item -> {
                    if (!validationErrors.containsKey(item.getField())) {
                        validationErrors.put(item.getField(), item.getDefaultMessage());
                    }
                });
                validationErrors.entrySet().forEach(entry -> {
                    errorLogger.debug(entry.getKey() + " ==> " + entry.getValue());
                });
            }
        }
        errorLogger.error(BaseBean.LOG_BREAKER_CLOSE);
        if (model != null) {
            model.addAttribute("pageMode", pageMode);
        }
        if (e instanceof ValidationFailedException) {
            if (errorView.length() == 0) {
                errorView = "error/500";
            } else {
                if (model != null && errors != null) {
                    model.addAttribute("pageMode", pageMode);
                    Map<String, String> validationErrors = new HashMap<>();
                    List<FieldError> errorFields = errors.getFieldErrors();
                    errorFields.forEach(item -> {
                        if (!validationErrors.containsKey(item.getField())) {
                            validationErrors.put(item.getField(), item.getDefaultMessage());
                        }
                    });
                    model.addAttribute("validationErrors", validationErrors);
                    model.addAttribute("pageMessage",
                            new PageMessage("Validation Error",
                                    messageSource.getMessage("Validation.common.Page.ValidationErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        } else if (e instanceof DuplicatedEntryException) {
            if (errorView.length() == 0) {
                errorView = "error/208";
            } else {
                if (model != null) {
                    model.addAttribute("pageMessage",
                            new PageMessage("Duplicated",
                                    messageSource
                                            .getMessage("Serverity.common.Page.DuplicatedRecordErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        } else if (e instanceof ConsistencyViolationException) {
            if (errorView.length() == 0) {
                errorView = "error/226";
            } else {
                if (model != null) {
                    model.addAttribute("pageMessage",
                            new PageMessage("Rejected",
                                    messageSource.getMessage(
                                            "Serverity.common.Page.ConsistencyViolationErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        } else if (e instanceof BusinessException) {
            if (errorView.length() == 0) {
                errorView = "error/500";
            } else {
                if (model != null) {
                    model.addAttribute("pageMessage",
                            new PageMessage("Application Error",
                                    messageSource.getMessage("Serverity.common.Page.ApplicationErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        } else {
            if (errorView.length() == 0) {
                errorView = "error/500";
            } else {
                if (model != null) {
                    model.addAttribute("pageMessage",
                            new PageMessage("Server Error",
                                    messageSource.getMessage("Serverity.common.Page.ServerErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        }
    }
    if (errorView.length() == 0) {
        errorView = "error/500";
    }
    return pageSuccessReturn == null ? errorView : pageSuccessReturn;

}

From source file:com.mycompany.aspect.InterceptorLog.java

@Around("execution(* execution(*com.mycompany.dao.SobaDaoImp.addStudentAround (..))")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("logAround() metoda je pozvana!");
    System.out.println("presretanje metode : " + joinPoint.getSignature().getName());
    System.out.println("presretanje : " + Arrays.toString(joinPoint.getArgs()));
    System.out.println("Around before metoda jepozvana");
    joinPoint.proceed();/*from   w ww .j a va 2 s . c o  m*/
    System.out.println("Around metoda je pozvana!");
    System.out.println("******");
}

From source file:com.netflix.bdp.s3mper.listing.ConsistentListingAspect.java

License:Apache License

/**
 * Updates the metastore when a FileSystem.create(...) method is called.
 * /*from   w  ww  .j  a va 2s  .  c  om*/
 * @param pjp
 * @return
 * @throws Throwable 
 */
@Around("create() && !within(ConsistentListingAspect)")
public Object metastoreUpdate(final ProceedingJoinPoint pjp) throws Throwable {
    if (disabled) {
        return pjp.proceed();
    }

    Configuration conf = ((FileSystem) pjp.getTarget()).getConf();
    updateConfig(conf);

    Object result = pjp.proceed();

    Path path = null;

    if (result instanceof Boolean && !((Boolean) result)) {
        return result;
    }

    try {
        //Locate the path parameter in the arguments
        for (Object arg : pjp.getArgs()) {
            if (arg instanceof Path) {
                path = (Path) arg;
                break;
            }
        }

        metastore.add(path, trackDirectories && pjp.getSignature().getName().contains("mkdir"));
    } catch (TimeoutException t) {
        log.error("Timeout occurred adding path to metastore: " + path, t);

        alertDispatcher.timeout("metastoreUpdate", Collections.singletonList(path));

        if (failOnTimeout) {
            throw t;
        }
    } catch (Exception e) {
        log.error("Failed to add path to metastore: " + path, e);

        if (shouldFail(conf)) {
            throw e;
        }
    }

    return result;
}

From source file:com.netflix.bdp.s3mper.listing.ConsistentListingAspect.java

License:Apache License

/**
 * Ensures that all the entries in the metastore also exist in the FileSystem listing.
 * /*w  w w  .  j a v a  2  s  .com*/
 * @param pjp
 * @return
 * @throws Throwable 
 */
@Around("list() && !cflow(delete()) && !within(ConsistentListingAspect)")
public Object metastoreCheck(final ProceedingJoinPoint pjp) throws Throwable {

    FileSystem fs = (FileSystem) pjp.getThis();

    if (disabled) {
        return pjp.proceed();
    }

    Configuration conf = ((FileSystem) pjp.getTarget()).getConf();
    updateConfig(conf);

    FileStatus[] s3Listing = (FileStatus[]) pjp.proceed();
    FileStatus[] originalListing = null;
    if (darkload) {
        originalListing = s3Listing.clone();
    }

    List<Path> pathsToCheck = new ArrayList<Path>();

    Object pathArg = pjp.getArgs()[0];

    //Locate paths in the arguments
    if (pathArg instanceof Path) {
        pathsToCheck.add((Path) pathArg);
    } else if (pathArg instanceof List) {
        pathsToCheck.addAll((List) pathArg);
    } else if (pathArg.getClass().isArray()) {
        pathsToCheck.addAll(Arrays.asList((Path[]) pathArg));
    }

    //HACK: This is just to prevent the emr metrics from causing consisteny failures
    for (StackTraceElement e : Thread.currentThread().getStackTrace()) {
        if (e.getClassName().contains("emr.metrics")) {
            log.debug("Ignoring EMR metrics listing for paths: " + pathsToCheck);
            return s3Listing;
        }
    }
    //END HACK

    long recheck = recheckCount;
    long delay = recheckPeriod;

    try {
        if (isTask(conf) && !checkTaskListings) {
            log.info("Skipping consistency check for task listing");
            return s3Listing;
        }

        if (isTask(conf)) {
            recheck = taskRecheckCount;
            delay = taskRecheckPeriod;
        }
    } catch (Exception e) {
        log.error("Error checking for task side listing", e);
    }

    try {
        List<FileInfo> metastoreListing = metastore.list(pathsToCheck);

        List<Path> missingPaths = ImmutableList.of();
        if (statOnMissingFile) {
            missingPaths = checkListing(metastoreListing, s3Listing);

            if (!missingPaths.isEmpty()) {
                List<FileStatus> fullListing = new ArrayList<FileStatus>();
                fullListing.addAll(Arrays.asList(s3Listing));
                for (Path path : missingPaths) {
                    FileStatus status = fs.getFileStatus(path);
                    fullListing.add(status);
                }
                s3Listing = fullListing.toArray(new FileStatus[0]);
            }
        } else {

            int checkAttempt;

            for (checkAttempt = 0; checkAttempt <= recheck; checkAttempt++) {
                missingPaths = checkListing(metastoreListing, s3Listing);

                if (delistDeleteMarkedFiles) {
                    s3Listing = delistDeletedPaths(metastoreListing, s3Listing);
                }

                if (missingPaths.isEmpty()) {
                    break;
                }

                //Check if acceptable threshold of data has been met.  This is a little
                //ambigious becuase S3 could potentially have more files than the
                //metastore (via out-of-band access) and throw off the ratio
                if (fileThreshold < 1 && metastoreListing.size() > 0) {
                    float ratio = s3Listing.length / (float) metastoreListing.size();

                    if (ratio > fileThreshold) {
                        log.info(format(
                                "Proceeding with incomplete listing at ratio %f (%f as acceptable). Still missing paths: %s",
                                ratio, fileThreshold, missingPaths));

                        missingPaths.clear();
                        break;
                    }
                }

                if (recheck == 0) {
                    break;
                }

                log.info(format("Rechecking consistency in %d (ms).  Files missing %d. Missing paths: %s",
                        delay, missingPaths.size(), missingPaths));
                Thread.sleep(delay);
                s3Listing = (FileStatus[]) pjp.proceed();
            }

            if (!missingPaths.isEmpty()) {
                alertDispatcher.alert(missingPaths);

                if (shouldFail(conf)) {
                    throw new S3ConsistencyException(
                            "Consistency check failed. See go/s3mper for details. Missing paths: "
                                    + missingPaths);
                } else {
                    log.error("Consistency check failed.  See go/s3mper for details. Missing paths: "
                            + missingPaths);
                }
            } else {
                if (checkAttempt > 0) {
                    log.info(format("Listing achieved consistency after %d attempts", checkAttempt));
                    alertDispatcher.recovered(pathsToCheck);
                }
            }
        }
    } catch (TimeoutException t) {
        log.error("Timeout occurred listing metastore paths: " + pathsToCheck, t);

        alertDispatcher.timeout("metastoreCheck", pathsToCheck);

        if (failOnTimeout) {
            throw t;
        }
    } catch (Exception e) {
        log.error("Failed to list metastore for paths: " + pathsToCheck, e);

        if (shouldFail(conf)) {
            throw e;
        }
    }

    return darkload ? originalListing : s3Listing;
}

From source file:com.netflix.bdp.s3mper.listing.ConsistentListingAspect.java

License:Apache License

/**
 * Rename listing records based on a rename call from the FileSystem.
 *
 * @param pjp/*from www  .  j a  v a  2  s.c  om*/
 * @return
 * @throws Throwable
 */
@Around("rename() && !within(ConsistentListingAspect)")
public Object metastoreRename(final ProceedingJoinPoint pjp) throws Throwable {
    if (disabled) {
        return pjp.proceed();
    }

    Configuration conf = ((FileSystem) pjp.getTarget()).getConf();
    updateConfig(conf);
    FileSystem fs = (FileSystem) pjp.getTarget();

    Path srcPath = (Path) pjp.getArgs()[0];
    Path dstPath = (Path) pjp.getArgs()[1];

    Preconditions.checkNotNull(srcPath);
    Preconditions.checkNotNull(dstPath);

    RenameInfo renameInfo = new RenameInfo(fs, srcPath, dstPath);
    metadataRename(conf, fs, renameInfo);

    Object obj = pjp.proceed();
    if ((Boolean) obj) {
        // Everything went fine delete the old metadata.
        // If not then we'll keep the metadata to prevent incomplete listings.
        // Manual cleanup will be required in the case of failure.
        metadataCleanup(conf, fs, renameInfo);
    }
    return obj;
}

From source file:com.netflix.bdp.s3mper.listing.ConsistentListingAspect.java

License:Apache License

/**
 * Deletes listing records based on a delete call from the FileSystem.
 * //from ww w .  j av a  2 s . com
 * @param pjp
 * @return
 * @throws Throwable 
 */
@Around("delete() && !within(ConsistentListingAspect)")
public Object metastoreDelete(final ProceedingJoinPoint pjp) throws Throwable {
    if (disabled) {
        return pjp.proceed();
    }

    Configuration conf = ((FileSystem) pjp.getTarget()).getConf();
    updateConfig(conf);

    Path deletePath = (Path) pjp.getArgs()[0];

    boolean recursive = false;

    if (pjp.getArgs().length > 1) {
        recursive = (Boolean) pjp.getArgs()[1];
    }

    try {
        FileSystem s3fs = (FileSystem) pjp.getTarget();

        Set<Path> filesToDelete = new HashSet<Path>();
        filesToDelete.add(deletePath);

        List<FileInfo> metastoreFiles = metastore.list(Collections.singletonList(deletePath));

        for (FileInfo f : metastoreFiles) {
            filesToDelete.add(f.getPath());
        }

        try {
            if (s3fs.getFileStatus(deletePath).isDir() && recursive) {
                filesToDelete.addAll(recursiveList(s3fs, deletePath));
            }
        } catch (Exception e) {
            log.info("A problem occurred deleting path: " + deletePath + " " + e.getMessage());
        }

        for (Path path : filesToDelete) {
            metastore.delete(path);
        }
    } catch (TimeoutException t) {
        log.error("Timeout occurred deleting metastore path: " + deletePath, t);

        alertDispatcher.timeout("metastoreDelete", Collections.singletonList(deletePath));

        if (failOnTimeout) {
            throw t;
        }
    } catch (Exception e) {
        log.error("Error deleting paths from metastore: " + deletePath, e);

        if (shouldFail(conf)) {
            throw e;
        }
    }

    return pjp.proceed();
}

From source file:com.netflix.genie.web.aspect.HealthCheckMetricsAspect.java

License:Apache License

/**
 * Intercept call to the Health endpoint publish a timer tagged with error, status.
 *
 * @param joinPoint joinPoint for the actual call to invoke()
 * @return Health, as returned by the actual invocation
 * @throws Throwable as thrown by joinPoint.proceed()
 *//*from   w  ww.  j  ava2s . c  o  m*/
@Around("execution(" + "  org.springframework.boot.actuate.health.Health"
        + "  org.springframework.boot.actuate.health.HealthEndpoint.health()" + ")")
@SuppressWarnings("checkstyle:IllegalThrows") // For propagating Throwable from joinPoint.proceed()
public Health healthEndpointInvokeMonitor(final ProceedingJoinPoint joinPoint) throws Throwable {
    final long start = System.nanoTime();
    final Health health;
    Status status = Status.UNKNOWN;
    final Set<Tag> tags = Sets.newHashSet();
    try {
        health = (Health) joinPoint.proceed(joinPoint.getArgs());
        status = health.getStatus();
    } catch (final Throwable t) {
        tags.add(Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, t.getClass().getCanonicalName()));
        throw t;
    } finally {
        final long turnaround = System.nanoTime() - start;
        tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, status.toString()));
        log.debug("HealthEndpoint.invoke() completed in {} ns", turnaround);
        this.registry.timer(HEALTH_ENDPOINT_TIMER_NAME, tags).record(turnaround, TimeUnit.NANOSECONDS);
    }
    return health;
}

From source file:com.netflix.genie.web.aspect.HealthCheckMetricsAspect.java

License:Apache License

/**
 * Intercept call to HealthIndicator beans loaded and publish a timer tagged with error, if any.
 *
 * @param joinPoint joinPoint for the actual call to health()
 * @return Health, as returned by the actual invocation
 * @throws Throwable as thrown by joinPoint.proceed()
 *//* ww w. j a v  a  2s .c om*/
@Around("execution(" + "  org.springframework.boot.actuate.health.Health"
        + "  org.springframework.boot.actuate.health.HealthIndicator.health()" + ")")
@SuppressWarnings("checkstyle:IllegalThrows") // For propagating Throwable from joinPoint.proceed()
public Health healthIndicatorHealthMonitor(final ProceedingJoinPoint joinPoint) throws Throwable {
    final long start = System.nanoTime();
    final Health h;
    Throwable throwable = null;
    try {
        h = (Health) joinPoint.proceed(joinPoint.getArgs());
    } catch (final Throwable t) {
        throwable = t;
        throw t;
    } finally {
        final long turnaround = System.nanoTime() - start;
        recordHealthIndicatorTurnaround(turnaround, joinPoint, throwable);
    }
    return h;
}