Example usage for org.aspectj.lang ProceedingJoinPoint getThis

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

Introduction

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

Prototype

Object getThis();

Source Link

Document

Returns the currently executing object.

Usage

From source file:at.ac.tuwien.infosys.jcloudscale.server.aspects.eventing.ObjectLifecycleEventAspect.java

License:Apache License

@Around("execution(public void at.ac.tuwien.infosys.jcloudscale.server.JCloudScaleServer.destroyCloudObject(..))")
public void matchObjectDestroyed(ProceedingJoinPoint pjp) throws Throwable {

    Class<?> cloudObjectType = null;
    JCloudScaleServer server = null;//w  ww  .j  a  v  a  2s.c  o m
    UUID cloudObjectId = null;
    try {
        server = (JCloudScaleServer) pjp.getThis();
        cloudObjectId = UUID.fromString((String) (pjp.getArgs()[0]));

        Object cloudObject = server.getCloudObject(cloudObjectId);
        if (cloudObject != null)
            cloudObjectType = cloudObject.getClass();
    } catch (Exception e) {
        e.printStackTrace();
        log.severe("Error while triggering ObjectDestroyedEvent: " + e.getMessage());
    }

    pjp.proceed();

    try {
        ObjectDestroyedEvent event = new ObjectDestroyedEvent();
        initializeBaseEventProperties(event);
        // XXX AbstractJCloudScaleServerRunner
        // UUID serverId = JCloudScaleServerRunner.getInstance().getId();
        UUID serverId = AbstractJCloudScaleServerRunner.getInstance().getId();
        event.setHostId(serverId);
        event.setObjectId(cloudObjectId);
        event.setObjectType(cloudObjectType);
        getMqHelper().sendEvent(event);
        log.finer("Sent object destroyed for object " + cloudObjectId);
    } catch (Exception e) {
        e.printStackTrace();
        log.severe("Error while triggering ObjectDestroyedEvent: " + e.getMessage());
    }

}

From source file:com.clicktravel.cheddar.application.retry.RetryableAspect.java

License:Apache License

private Object processMethodFailure(final ProceedingJoinPoint proceedingJoinPoint,
        final String[] exceptionHandlerNames, final Throwable thrownException) throws Throwable {
    final Method handlerMethod = getHandlerMethod(proceedingJoinPoint, thrownException.getClass(),
            exceptionHandlerNames);/*from  ww  w .j a  va2s . co  m*/
    if (handlerMethod != null) {
        logger.trace("Selected handlerMethod : " + handlerMethod.getName());
        try {
            return handlerMethod.invoke(proceedingJoinPoint.getThis(),
                    getExceptionHandlerArgs(thrownException, proceedingJoinPoint.getArgs()));
        } catch (final InvocationTargetException invocationTargetException) {
            throw invocationTargetException.getCause(); // exception thrown by handler method
        }
    } else {
        throw thrownException;
    }
}

From source file:com.clicktravel.cheddar.application.retry.RetryableAspect.java

License:Apache License

private Method getHandlerMethod(final ProceedingJoinPoint proceedingJoinPoint,
        final Class<? extends Throwable> thrownExceptionClass, final String[] handlerMethodNames) {
    final Class<?> targetClass = proceedingJoinPoint.getThis().getClass();
    final MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
    final Class<?>[] handlerParameterTypes = getExceptionHandlerParameterTypes(thrownExceptionClass,
            methodSignature.getParameterTypes());
    for (final String handlerMethodName : handlerMethodNames) {
        try {/*w ww  .j a v  a  2s .  c om*/
            return targetClass.getMethod(handlerMethodName, handlerParameterTypes);
        } catch (final ReflectiveOperationException e) {
            // Exception handler method signature does not match - Skip this exception handler
        }
    }
    return null;
}

From source file:com.clicktravel.cheddar.application.retry.RetryableAspectTest.java

License:Apache License

@Test
public void shouldAttemptMethodAndCallExceptionHandler_withExceptionThrownAndExceptionHandlerNamed()
        throws Throwable {
    // Given/* www . ja  va2s .  c o m*/
    final RetryableAspect retryableAspect = new RetryableAspect();
    final ProceedingJoinPoint mockProceedingJoinPoint = setupSimpleProceedingJoinPointMock();
    final Retryable mockRetryable = setupSimpleRetryableMock();
    final RetryExceptionHandler retryExceptionHandler = new RetryExceptionHandler();
    final MethodSignature mockMethodSignature = mock(MethodSignature.class);
    final String exceptionHandlerName = "joinPointMethodExceptionHandlingMethod";

    RetryableConfiguration.setRetryableEnabled(false);
    when(mockProceedingJoinPoint.proceed()).thenThrow(new RetryAspectTestException());
    when(mockProceedingJoinPoint.getThis()).thenReturn(retryExceptionHandler);
    when(mockProceedingJoinPoint.getSignature()).thenReturn(mockMethodSignature);
    when(mockProceedingJoinPoint.getArgs()).thenReturn(new Object[] { "exampleArgument" });
    when(mockMethodSignature.getParameterTypes()).thenReturn(
            RetryExceptionHandler.class.getDeclaredMethod("joinPointMethod", String.class).getParameterTypes());
    when(mockRetryable.exceptionHandlers()).thenReturn(new String[] { exceptionHandlerName });

    // When
    retryableAspect.attemptMethodAndRetryIfNeeded(mockProceedingJoinPoint, mockRetryable);

    // Then
    verify(mockProceedingJoinPoint).proceed();

    assertTrue(retryExceptionHandler.exceptionHandlerBeenCalled);
}

From source file:com.clicktravel.cheddar.application.retry.RetryableAspectTest.java

License:Apache License

private ProceedingJoinPoint setupSimpleProceedingJoinPointMock() {
    final ProceedingJoinPoint mockProceedingJoinPoint = mock(ProceedingJoinPoint.class);
    final MethodSignature mockMethodSignature = mock(MethodSignature.class);

    when(mockProceedingJoinPoint.getThis()).thenReturn(mockProceedingJoinPoint);
    when(mockProceedingJoinPoint.getSignature()).thenReturn(mockMethodSignature);
    when(mockMethodSignature.getParameterTypes()).thenReturn(new Class[0]);
    return mockProceedingJoinPoint;
}

From source file:com.evolveum.midpoint.util.aspect.MidpointAspect.java

License:Apache License

/**
 * Get joinPoint class name if available
 *
 */// w w  w.  ja v  a2  s.  c  o  m
private String getClassName(ProceedingJoinPoint pjp) {
    String className = null;
    if (pjp.getThis() != null) {
        className = pjp.getThis().getClass().getName();
        className = className.replaceFirst("com.evolveum.midpoint", "..");
    }
    return className;
}

From source file:com.github.akutschera.maven.plugin.skiptest.aspect.SkipAspect.java

License:Apache License

private String getNameOfTestFrom(ProceedingJoinPoint pjp) {
    String className = pjp.getThis().getClass().getName();
    String testToExecute = pjp.getSignature().getName();
    return className + "." + testToExecute;
}

From source file:com.haulmont.cuba.core.sys.ServiceInterceptor.java

License:Apache License

@Nullable
protected ValidateServiceMethodContext getValidateServiceMethodContext(ProceedingJoinPoint ctx) {
    ValidateServiceMethodContext validatedContext = null;
    if (ctx instanceof MethodInvocationProceedingJoinPoint) {
        MethodInvocationProceedingJoinPoint methodInvocationCtx = (MethodInvocationProceedingJoinPoint) ctx;

        Method method = ((MethodSignature) ctx.getSignature()).getMethod();

        Validated validated = getValidated(method, ctx.getSignature().getDeclaringType());
        if (validated != null) {
            Object[] args = methodInvocationCtx.getArgs();
            ExecutableValidator validator = beanValidation.getValidator().forExecutables();

            validatedContext = new ValidateServiceMethodContext(validator, ctx.getThis(), method, args,
                    validated.value());/*from w  w w .  java 2s  . c  om*/
        }
    }
    return validatedContext;
}

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 ww.  j av a 2  s . c  o  m
 * @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.rover12421.shaka.apktool.lib.AndrolibAj.java

License:Apache License

@Around("execution(* brut.androlib.Androlib.buildNonDefaultSources(..))" + "&& args(appDir)")
public void buildNonDefaultSources(ProceedingJoinPoint joinPoint, ExtFile appDir) {
    /**// www  . jav  a2  s.  co  m
     * `apktool.yml`
     * ?5.0, `gradle test` ?
     * `apktool.yml`
     */
    File[] files = appDir.getAbsoluteFile().listFiles();
    if (files != null) {
        for (File file : files) {
            String name = file.getName();
            if (file.isDirectory() && metaInfo.getDexMap(name) == null && name.startsWith("smali_")) {
                String key = name.substring("smali_".length()) + ".dex";
                metaInfo.addDexMap(key, name);
            }
        }
    }

    if (metaInfo.dexMaps == null)
        return;
    for (String dex : metaInfo.dexMaps.keySet()) {
        try {
            Androlib androlib = (Androlib) joinPoint.getThis();
            File dexFile = new File(appDir, APK_DIRNAME + "/" + dex);
            dexFile.getParentFile().mkdirs();
            androlib.buildSourcesSmali(appDir, metaInfo.getDexMap(dex), dex);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}