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:com.rover12421.shaka.smali.dexlib2.DexBackedMethodImplementationAj.java

License:Apache License

@Around("execution(* org.jf.dexlib2.dexbacked.DexBackedMethodImplementation.getInstructions(..))")
public Iterable<? extends Instruction> getInstructions(ProceedingJoinPoint joinPoint) throws Exception {
    DexBackedMethodImplementation thiz = (DexBackedMethodImplementation) joinPoint.getThis();

    int codeOffset = thiz.getCodeOffset();

    // instructionsSize is the number of 16-bit code units in the instruction list, not the number of instructions
    int instructionsSize = thiz.dexFile.readSmallUint(codeOffset + CodeItem.INSTRUCTION_COUNT_OFFSET);

    final int instructionsStartOffset = codeOffset + CodeItem.INSTRUCTION_START_OFFSET;
    final int endOffset = instructionsStartOffset + (instructionsSize * 2);

    List<Instruction> instructions = new ArrayList<>();
    DexReader reader = thiz.dexFile.readerAt(instructionsStartOffset);
    while (reader.getOffset() < endOffset) {
        Instruction instruction = DexBackedInstruction.readFrom(reader);
        instructions.add(instruction);// w ww  .ja va 2 s  . c  om
    }
    if (instructions.size() == 3 && instructions.get(0) instanceof OffsetInstruction
            && instructions.get(1).getOpcode() == Opcode.FILL_ARRAY_DATA
            && instructions.get(2).getOpcode() == Opcode.ARRAY_PAYLOAD) {
        /**
         * dalvik-obfuscator?
         * ?instructionsreader
         * dalvik-obfuscatornop?,???
         */
        LogHelper.warning("Detected dalvik-obfuscator code block : " + thiz.method.getDefiningClass() + "->"
                + thiz.method.getName());
        instructions.clear();
        reader = thiz.dexFile.readerAt(instructionsStartOffset);
        /**
         * dalvik-obfuscator?9nop?,???
         */
        for (int i = 0; i < 9; i++) {
            DexBackedInstruction10x nop = new DexBackedInstruction10x(thiz.dexFile, Opcode.NOP,
                    instructionsStartOffset + i * 2);
            instructions.add(nop);
            reader.moveRelative(2);
        }
        while (reader.getOffset() < endOffset) {
            Instruction instruction = DexBackedInstruction.readFrom(reader);
            instructions.add(instruction);
        }
    }
    return instructions;
}

From source file:com.rover12421.shaka.smali.dexlib2.DexBackedMethodImplementationAj.java

License:Apache License

@Around("execution(* org.jf.dexlib2.dexbacked.DexBackedMethodImplementation.getDebugInfo())")
public DebugInfo getDebugInfo(ProceedingJoinPoint joinPoint) {
    DexBackedMethodImplementation thiz = (DexBackedMethodImplementation) joinPoint.getThis();
    DexBackedDexFile dexFile = thiz.dexFile;
    int codeOffset = thiz.getCodeOffset();

    int debugOffset = dexFile.readInt(codeOffset + CodeItem.DEBUG_INFO_OFFSET);
    try {//from   www.  j  a  va  2 s.  c  o m
        return DebugInfo.newOrEmpty(dexFile, debugOffset, thiz);
    } catch (Throwable e) {
        return DebugInfo.newOrEmpty(dexFile, 0, thiz);
    }
}

From source file:com.solace.ExceptionHandlingAspect.java

License:Open Source License

/**
 * Will fire around methods decorated with {@link ExceptionHandled} in
 * following fashion://from ww  w  . ja v  a  2  s .  co m
 * <p>
 * <ol>
 * <li>if {@link ExceptionHandled#logExceptionStack()} is true then a
 * uniform exception will be printed to {@link Logger#error(String)}</li>
 * <li>if {@link ExceptionHandled#handlers()} is not empty the exception
 * will be:</li>
 * <ol>
 * <li>evaluated to see if it is an instance of
 * {@link ExceptionHandledBy#handleFor()} <b>OR</b> if the exception is
 * derived from a class in {@link ExceptionHandledBy#handleFor()} if
 * {@link ExceptionHandledBy#checkForDerived()} is <b>true</b></li>
 * <li>if one or both of the previous conditions are met the exception will
 * be applied to each {@link IExceptionHandler} in
 * {@link ExceptionHandledBy#handlers()}</li>
 * <li>finally, if {@link ExceptionHandledBy#rethrowAs()} is set to a class
 * derived off of {@link Exception} the new exception will be created
 * through {@link Exception#Exception(String, Throwable)} and rethrown</li>
 * </ol>
 * </ol>
 * <p>
 * It should be noted that the rethrow could be held in
 * {@link ExceptionHandled} however, at this point, we don't quite know how
 * people will want to use the advice. Until Because of this we will set one
 * at the global level to be handled after all evaluations have occurred.
 * Now if, however, a nested {@link ExceptionHandledBy} has a rethrowAs set
 * the global will be missed as the rethrow will occur inside of the loop
 * evaluation.
 * 
 * @param pjp
 *            The ProceedingJoinPoint with metadata around the method that
 *            will be called
 * @param exceptionHandled
 *            A collection of exception types to be handled. If defined we
 *            will proceed calls down to the ExceptionHandler. If none will
 *            proceed then we automatically move forward.
 * @return the object returned by the joinpoint
 * @throws Throwable
 */
@SuppressWarnings("unchecked")
@Around(value = "call(* *(..)) && @annotation(exceptionHandled)", argNames = "pjp,exceptionHandled")
public Object handle(final ProceedingJoinPoint pjp, final ExceptionHandled exceptionHandled) throws Throwable {

    Object retVal = null;

    try {

        retVal = pjp.proceed();

    } catch (Exception e) {

        if (exceptionHandled.logExceptionStack()) {
            Logger logger = null;

            if (pjp.getThis() == null)
                logger = Logger.getLogger("main");
            else
                logger = Logger.getLogger(pjp.getThis().getClass());

            logger.error("Exception caught:\nInput arguments: {}", e, buildArgsString(pjp.getArgs()));
        }

        for (ExceptionHandledBy by : exceptionHandled.handlers()) {

            for (Class<? extends Exception> eClass : by.handleFor()) {
                if (eClass.equals(e.getClass())
                        || (by.checkForDerived() && eClass.isAssignableFrom(e.getClass()))) {
                    for (Class<? extends IExceptionHandler> handlerClass : by.handlers()) {
                        IExceptionHandler handler = null;

                        if ((handler = instances.get(handlerClass)) == null) {
                            handler = handlerClass.newInstance();
                            instances.put(handlerClass, handler);
                        }

                        // invoke the IExceptionHandler by leveraging
                        // the code from the JoinPoint
                        // passed in the ProceedingJoinPoint instance
                        handler.handle(pjp.getThis(), e.getMessage(), e, pjp.getArgs());
                    }

                    if (Exception.class.isAssignableFrom(by.rethrowAs())) {
                        Class<? extends Exception> rethrowClass = (Class<? extends Exception>) by.rethrowAs();

                        LOGGER.debug("Rethrowing as {}", rethrowClass.toString());

                        Constructor<? extends Exception> ctor = rethrowClass.getConstructor(String.class,
                                Throwable.class);

                        Exception rethrow = ctor.newInstance(e.getMessage(), e);

                        throw rethrow;
                    }
                }
            }
        }

        if (Exception.class.isAssignableFrom(exceptionHandled.rethrowAs())) {
            Class<? extends Exception> rethrowClass = (Class<? extends Exception>) exceptionHandled.rethrowAs();

            LOGGER.debug("Global rethrow as {}", rethrowClass.toString());

            Constructor<? extends Exception> ctor = rethrowClass.getConstructor(String.class, Throwable.class);

            Exception rethrow = ctor.newInstance(e.getMessage(), e);

            throw rethrow;
        }
    }

    return retVal;
}

From source file:com.solace.logging.AspectJTimingAspect.java

License:Open Source License

/**
 * Will do the typical invocation of the logging instances via perf4j but
 * will do them instead of on annotated methods but on all public methods.
 * Additionally will guarantee that no instrumentation is needed for the
 * enter and exit in the typical application logs
 * //from  w  w  w .  j a  va2  s  .com
 * @param pjp
 *            a ProceedingJoinPoint compiled in via aspectj
 * @return returns the object if any
 * @throws Throwable
 */
@Around(value = "execution(public * *(..))", argNames = "pjp")
public Object doPerfLogging(final ProceedingJoinPoint pjp) throws Throwable {
    Object o = null;
    Object caller = pjp.getThis();

    Logger logger = null;
    if (pjp.getThis() != null)
        logger = Logger.getLogger(pjp.getThis().getClass());
    else
        logger = Logger.getLogger("main");

    Profiled p = DefaultProfiled.INSTANCE;

    try {
        if (logger.isDebugEnabled()) {
            logger.debug(ENTER, pjp.getSignature().toShortString());
            if (pjp.getArgs() != null && pjp.getArgs().length > 0) {
                StringBuilder sb = new StringBuilder();
                for (Object param : pjp.getArgs())
                    sb.append(param).append("; ");

                logger.debug(INPUT, sb.toString());
            }
        }
        o = super.doPerfLogging(pjp, p);
    } finally {
        if (logger.isDebugEnabled())
            logger.debug(EXIT, pjp.getSignature().toShortString());
    }
    return o;
}

From source file:com.stratio.qa.aspects.IgnoreTagAspect.java

License:Apache License

/**
 * @param pjp ProceedingJoinPoint/*from   w w w  .  jav  a  2s .c  om*/
 * @param formatter formatter
 * @param reporter reporter
 * @param runtime runtime
 * @throws Throwable exception
 */
@Around(value = "addIgnoreTagPointcutScenario(formatter, reporter, runtime)")
public void aroundAddIgnoreTagPointcut(ProceedingJoinPoint pjp, Formatter formatter, Reporter reporter,
        Runtime runtime) throws Throwable {

    CucumberScenario scen = (CucumberScenario) pjp.getThis();
    Scenario scenario = (Scenario) scen.getGherkinModel();

    Class<?> sc = scen.getClass();
    Method tt = sc.getSuperclass().getDeclaredMethod("tagsAndInheritedTags");
    tt.setAccessible(true);
    Set<Tag> tags = (Set<Tag>) tt.invoke(scen);

    List<String> tagList = new ArrayList<>();
    String scenarioName = scenario.getName();
    tagList = tags.stream().map(Tag::getName).collect(Collectors.toList());

    ignoreReasons exitReason = manageTags(tagList, scenarioName);
    if (exitReason.equals(NOREASON)) {
        logger.error("Scenario '" + scenario.getName() + "' failed due to wrong use of the @ignore tag. ");
    }

    if ((!(exitReason.equals(NOTIGNORED))) && (!(exitReason.equals(NOREASON)))) {
        runtime.buildBackendWorlds(reporter, tags, scenario.getName());
        formatter.startOfScenarioLifeCycle(scenario);
        formatter.endOfScenarioLifeCycle(scenario);
        runtime.disposeBackendWorlds();
    } else {
        pjp.proceed();
    }
}

From source file:com.stratio.qa.aspects.SeleniumAspect.java

License:Apache License

/**
 * If an exception has thrown by selenium, this methods save a screen
 * capture./* w  w  w  . j  a  v a2 s  .  c  o m*/
 *
 * @param pjp ProceedingJoinPoint
 * @return Object object
 * @throws Throwable exception
 */
@Around(value = "exceptionCallPointcut()")
public Object aroundExceptionCalls(ProceedingJoinPoint pjp) throws Throwable {
    Object retVal = null;
    try {
        retVal = pjp.proceed();
        return retVal;
    } catch (Throwable ex) {
        WebDriver driver = null;
        if (ex instanceof WebDriverException) {
            logger.info("Got a selenium exception");
            if (!(pjp.getThis() instanceof WebDriver)) {
                throw ex;
            }
            driver = (WebDriver) pjp.getThis();
        } else if ((pjp.getTarget() instanceof SeleniumAssert) && (ex instanceof AssertionError)) {
            logger.info("Got a SeleniumAssert response");
            SeleniumAssert as = (SeleniumAssert) pjp.getTarget();
            Class<?> c = as.getClass().getSuperclass();
            Field actual = c.getDeclaredField("actual");
            actual.setAccessible(true);
            Object realActual = actual.get(as);

            if (realActual instanceof WebDriver) {
                driver = (WebDriver) actual.get(as);
            } else if (realActual instanceof ArrayList) {
                if (((ArrayList) realActual).get(0) instanceof RemoteWebElement) {
                    driver = ((RemoteWebElement) ((ArrayList) realActual).get(0)).getWrappedDriver();
                }
            } else if ((realActual instanceof PreviousWebElements) || (realActual instanceof Boolean)
                    || (realActual instanceof String) || (realActual == null)) {
                driver = ((CommonG) ((SeleniumAssert) pjp.getTarget()).getCommonspec()).getDriver();
            } else if (realActual instanceof RemoteWebElement) {
                driver = ((RemoteWebElement) actual.get(as)).getWrappedDriver();
            }
        }
        if (driver != null) {
            logger.info("Trying to capture screenshots...");
            CommonG common = null;
            if ((pjp.getThis() instanceof ThenGSpec) && (((ThenGSpec) pjp.getThis()).getCommonSpec() != null)) {
                common = ((ThenGSpec) pjp.getThis()).getCommonSpec();
            } else if ((pjp.getTarget() instanceof SeleniumAssert)
                    && ((SeleniumAssert) pjp.getTarget()).getCommonspec() != null) {
                common = ((CommonG) ((SeleniumAssert) pjp.getTarget()).getCommonspec());
            } else {
                logger.info("Got no Selenium driver to capture a screen");
                throw ex;
            }
            common.captureEvidence(driver, "framehtmlSource", "assert");
            common.captureEvidence(driver, "htmlSource", "assert");
            common.captureEvidence(driver, "screenCapture", "assert");
            logger.info("Screenshots are available at target/executions");
        } else {
            logger.info("Got no Selenium driver to capture a screen");
        }
        throw ex;
    }
}

From source file:com.tacitknowledge.flip.aspectj.FlipAbstractAspect.java

License:Apache License

/**
 * Intercept calls to the methods marked with {@link Flippable} annotation.
 * Firstly it processes the method parameters marked with {@link FlipParam} 
 * annotation. Each parameter value is replaced with the value declared in
 * {@link FlipParam#disabledValue()} if the feature declared in {@link FlipParam#feature() }
 * is disabled./*from www .j av  a2s.  com*/
 * After properties evaluation this method checks if the feature marked in
 * {@link Flippable#feature() } is disabled then the value from {@link Flippable#disabledValue() }
 * is returned.
 * 
 * @param flip the {@link Flippable} annotation instance which marks the method to intercept.
 * @param pjp the object obtained from AspectJ method interceptor.
 * @return the processed value of the method depending from feature state.
 * @throws Throwable 
 */
@Around(value = "anyMethod() && @annotation(flip)", argNames = "flip")
public Object aroundFlippableMethods(ProceedingJoinPoint pjp, Flippable flip) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method method = methodSignature.getMethod();

    if (isFeatureEnabled(flip.feature())) {
        Annotation[][] paramAnnotations = method.getParameterAnnotations();
        Object[] params = pjp.getArgs();
        Class[] paramTypes = method.getParameterTypes();

        for (int i = 0; i < paramAnnotations.length; i++) {
            FlipParam flipParam = findFlipParamAnnoattion(paramAnnotations[i]);
            if (!isFeatureEnabled(flipParam.feature())) {
                params[i] = getProcessedDisabledValue(paramTypes[i], flipParam.disabledValue(), pjp.getThis());
            }
        }

        return pjp.proceed(params);
    } else {
        return getProcessedDisabledValue(method.getReturnType(), flip.disabledValue(), pjp.getThis());
    }
}

From source file:com.variacode.utils.object.changelistener.ObservableObjectAspect.java

License:Apache License

@Around("execution(* *.set*(..)) && @within(annotation)")
public Object setMethod(ProceedingJoinPoint joinPoint, Observe annotation) throws Throwable {
    ObserverSingleton.INSTANCE.change(new Change(annotation.stream(),
            Introspector.decapitalize(joinPoint.toShortString()
                    .replaceFirst("execution\\(" + joinPoint.getThis().getClass().getSimpleName() + ".set", "")
                    .replaceAll("\\.", "").replaceAll("\\)", "").replaceAll("\\(", "")),
            joinPoint.getArgs()[0], joinPoint.getThis()));
    return joinPoint.proceed();
}

From source file:com.virtusa.isq.vtaf.aspects.AspectClass.java

License:Apache License

/**
 * Advice the joinpoint.//from  w ww. ja v a2  s  . c  o  m
 *
 * @param joinPoint the join point
 */
public final void advice(final ProceedingJoinPoint joinPoint) {

    caller = (SeleniumTestBase) joinPoint.getThis();
    try {
        initiateRecoveryThread(caller, onerrorMethodNames);
        joinPoint.proceed();
        cancelRecoveryThread();
    } catch (WebDriverException e) {
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:com.willowtreeapps.respeeker.ResPeeker.java

License:Apache License

@Around("setContentView()")
public Object aroundSetContentView(ProceedingJoinPoint joinPoint) throws Throwable {
    Object result = joinPoint.proceed();

    Activity context = (Activity) joinPoint.getThis();
    int layoutRes = (Integer) joinPoint.getArgs()[0];
    View view = context.findViewById(android.R.id.content);

    attachTouchListener(view);//  www  . j av  a2 s  .com

    ViewPeeker.put(view, layoutRes);

    Configurator configurator = new Configurator(context);
    Properties properties = configurator.getProperties();
    Log.v("__ResPeeker__", "config <<" + propertiesToString(properties) + ">>");

    return result;
}