Search in sources :

Example 1 with JavassistBuildException

use of javassist.build.JavassistBuildException in project javassist-maven-plugin by icon-Systemhaus-GmbH.

the class JavassistTransformerExecutor method transform.

/**
 * Transform each class passed via {@link Iterator} of class names.
 * <p>
 * Use the passed {@code className} iterator, load each one as {@link CtClass}, filter the valid
 * candidates and apply transformation to each one.
 * </p>
 * <p>
 * <strong>Limitation:</strong> do not search inside .jar files.
 * </p>
 * <p>
 * Any unexpected (internal catched) {@link Exception} will be re-thrown in an
 * {@link RuntimeException}.
 * </p>
 *
 * @param transformer The transformer that will apply transformations could be {@code null}.
 * @param inputDir The root directory where the classes to transform will selected from could
 *          be {@code null} or empty. If it is {@code null} or empty nothing will be transformed.
 * @param outputDir The output directory where the transformed classes will stored could be
 *          {@code null} or empty. If it is {@code null} or empty the {@code inputDir} will be
 *          used.
 * @param classNames could be {@code null} or empty. If it is {@code null} or empty nothing will
 *          be transformed.
 *
 * @see #initializeClass(ClassPool, CtClass)
 * @see IClassTransformer#shouldTransform(CtClass)
 * @see IClassTransformer#applyTransformations(CtClass)
 */
public final void transform(final IClassTransformer transformer, final String inputDir, final String outputDir, final Iterator<String> classNames) {
    if (null == transformer) {
        return;
    }
    if (null == inputDir || inputDir.trim().isEmpty()) {
        return;
    }
    if (null == classNames || !classNames.hasNext()) {
        return;
    }
    final String inDirectory = inputDir.trim();
    try {
        final ClassPool classPool = configureClassPool(buildClassPool(), inDirectory);
        final String outDirectory = evaluateOutputDirectory(outputDir, inDirectory);
        int classCounter = 0;
        while (classNames.hasNext()) {
            final String className = classNames.next();
            if (null == className) {
                continue;
            }
            try {
                LOGGER.debug("Got class name {}", className);
                classPool.importPackage(className);
                final CtClass candidateClass = classPool.get(className);
                initializeClass(classPool, candidateClass);
                if (!hasStamp(candidateClass) && transformer.shouldTransform(candidateClass)) {
                    transformer.applyTransformations(candidateClass);
                    applyStamp(candidateClass);
                    // #48
                    for (final CtClass nestedClass : candidateClass.getNestedClasses()) {
                        if (!nestedClass.isModified() || hasStamp(nestedClass)) {
                            continue;
                        }
                        final CtClass nestedCtClass = classPool.get(nestedClass.getName());
                        initializeClass(classPool, nestedCtClass);
                        applyStamp(nestedCtClass);
                        nestedCtClass.writeFile(outDirectory);
                    }
                    candidateClass.writeFile(outDirectory);
                    LOGGER.debug("Class {} instrumented by {}", className, getClass().getName());
                    ++classCounter;
                }
            } catch (final NotFoundException e) {
                LOGGER.warn("Class {} could not be resolved due to dependencies not found on " + "current classpath (usually your class depends on \"provided\"" + " scoped dependencies).", className);
            } catch (final IOException ex) {
                // EOFException ...
                LOGGER.error("Class {} could not be instrumented due to initialize FAILED.", className, ex);
            } catch (final CannotCompileException ex) {
                LOGGER.error("Class {} could not be instrumented due to initialize FAILED.", className, ex);
            } catch (final JavassistBuildException ex) {
                LOGGER.error("Class {} could not be instrumented due to initialize FAILED.", className, ex);
            }
        }
        LOGGER.info("#{} classes instrumented by {}", classCounter, getClass().getName());
    } catch (final NotFoundException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) JavassistBuildException(javassist.build.JavassistBuildException) NotFoundException(javassist.NotFoundException) IOException(java.io.IOException) CannotCompileException(javassist.CannotCompileException)

Example 2 with JavassistBuildException

use of javassist.build.JavassistBuildException in project javassist-maven-plugin by icon-Systemhaus-GmbH.

the class MethodCallClassTransformer method applyTransformations.

@Override
public void applyTransformations(final CtClass classToTransform) throws JavassistBuildException {
    if (null == classToTransform) {
        return;
    }
    try {
        classToTransform.instrument(new ExprEditor() {

            @Override
            public void edit(final MethodCall method) throws CannotCompileException {
                final String statement = getStatement(method.getClassName(), method.getMethodName());
                if (statement != null) {
                    try {
                        method.replace(statement);
                    } catch (final CannotCompileException e) {
                        throw new CannotCompileException(String.format("Compile statement '%1$s' FAILED with: %2$s", statement, e.getMessage()), e);
                    }
                }
            }
        });
        // insert internal introspection state field
        final CtField introspectedField = new CtField(CtClass.booleanType, ALREADY_INTROSPECTED_FIELD_NAME, classToTransform);
        introspectedField.setModifiers(AccessFlag.PUBLIC | AccessFlag.STATIC | AccessFlag.FINAL);
        classToTransform.addField(introspectedField, Initializer.constant(true));
    } catch (CannotCompileException e) {
        throw new JavassistBuildException(e);
    }
}
Also used : CtField(javassist.CtField) ExprEditor(javassist.expr.ExprEditor) JavassistBuildException(javassist.build.JavassistBuildException) CannotCompileException(javassist.CannotCompileException) MethodCall(javassist.expr.MethodCall)

Example 3 with JavassistBuildException

use of javassist.build.JavassistBuildException in project javassist-maven-plugin by icon-Systemhaus-GmbH.

the class TestJavassistTransformerExecutor_transform method continue_transform_with_next_class_if_internal_JavassistBuildException_was_catched_on_applyTransformations.

@Test
@SuppressWarnings("unchecked")
public void continue_transform_with_next_class_if_internal_JavassistBuildException_was_catched_on_applyTransformations() throws Exception {
    // given
    final String className = oneTestClass();
    final JavassistBuildException internalException = new JavassistBuildException("expected exception");
    final Iterator<String> classNames = classNames(className);
    CtClass candidateClass = initializeClass();
    expect(candidateClass.getDeclaredField(startsWith(STAMP_FIELD_NAME))).andReturn(null);
    configureClassPool(this.classPool).importPackage(className);
    expectLastCall();
    expect(this.classPool.get(className)).andReturn(candidateClass);
    expect(this.classTransformer.shouldTransform(same(candidateClass))).andReturn(true);
    this.classTransformer.applyTransformations(same(candidateClass));
    expectLastCall().andThrow(internalException);
    replay(classNames, candidateClass, this.classPool, this.classTransformer);
    // when
    sut.transform(this.classTransformer, classDirectory().getAbsolutePath(), transformedClassDirectory().getAbsolutePath(), classNames);
    // then
    verify(classNames, candidateClass, this.classPool, this.classTransformer);
}
Also used : CtClass(javassist.CtClass) JavassistBuildException(javassist.build.JavassistBuildException) Test(org.junit.Test)

Aggregations

JavassistBuildException (javassist.build.JavassistBuildException)3 CannotCompileException (javassist.CannotCompileException)2 CtClass (javassist.CtClass)2 IOException (java.io.IOException)1 ClassPool (javassist.ClassPool)1 CtField (javassist.CtField)1 NotFoundException (javassist.NotFoundException)1 ExprEditor (javassist.expr.ExprEditor)1 MethodCall (javassist.expr.MethodCall)1 Test (org.junit.Test)1