Search in sources :

Example 76 with CtClass

use of javassist.CtClass 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 77 with CtClass

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

the class TestJavassistTransformerExecutor_transform method not_applyTransformation_if_hasStamp_returns_true.

@Test
public void not_applyTransformation_if_hasStamp_returns_true() throws Exception {
    // given
    final String className = "test.TestClass";
    final CtClass candidateClass = initializeClass();
    expect(candidateClass.getDeclaredField(startsWith(STAMP_FIELD_NAME))).andReturn(mock("stampField", CtField.class));
    final Iterator<String> classNames = classNames(className);
    configureClassPool(this.classPool).importPackage(className);
    expectLastCall();
    expect(this.classPool.get(className)).andReturn(candidateClass);
    replay(candidateClass, classNames, this.classPool, this.classTransformer);
    // when
    sut.transform(this.classTransformer, classDirectory().getAbsolutePath(), transformedClassDirectory().getAbsolutePath(), classNames);
    // then
    verify(candidateClass, classNames, this.classPool, this.classTransformer);
}
Also used : CtClass(javassist.CtClass) CtField(javassist.CtField) Test(org.junit.Test)

Example 78 with CtClass

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

the class TestJavassistTransformerExecutor_transform method continue_transform_with_next_class_if_internal_IOException_was_catched_on_writeFile.

@Test
@SuppressWarnings("unchecked")
public void continue_transform_with_next_class_if_internal_IOException_was_catched_on_writeFile() throws Exception {
    // given
    final String className = oneTestClass();
    final IOException internalException = new IOException("expected exception");
    final Iterator<String> classNames = classNames(className);
    CtClass candidateClass = stampedClass(className);
    candidateClass.writeFile(eq(transformedClassDirectory().getAbsolutePath()));
    expectLastCall().andThrow(internalException);
    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();
    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) IOException(java.io.IOException) Test(org.junit.Test)

Example 79 with CtClass

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

the class TestJavassistTransformerExecutor_transform method continue_transform_with_next_class_if_internal_CannotCompileException_was_catched_on_writeFile.

@Test
@SuppressWarnings("unchecked")
public void continue_transform_with_next_class_if_internal_CannotCompileException_was_catched_on_writeFile() throws Exception {
    // given
    final String className = oneTestClass();
    final CannotCompileException internalException = new CannotCompileException("expected exception");
    final Iterator<String> classNames = classNames(className);
    final CtClass candidateClass = stampedClass(className);
    candidateClass.writeFile(eq(transformedClassDirectory().getAbsolutePath()));
    expectLastCall().andThrow(internalException);
    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();
    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) CannotCompileException(javassist.CannotCompileException) Test(org.junit.Test)

Example 80 with CtClass

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

the class TestJavassistTransformerExecutor_transform method use_input_directory_if_output_directory_is_empty.

@Test
public void use_input_directory_if_output_directory_is_empty() throws Exception {
    // given
    final String className = oneTestClass();
    final CtClass candidateClass = stampedClass(className);
    // use input if output is not set
    candidateClass.writeFile(eq(classDirectory().getAbsolutePath()));
    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();
    replay(candidateClass, this.classPool, this.classTransformer);
    // when
    sut.transform(this.classTransformer, classDirectory().getAbsolutePath(), "   ");
    // then
    verify(candidateClass, this.classPool, this.classTransformer);
}
Also used : CtClass(javassist.CtClass) Test(org.junit.Test)

Aggregations

CtClass (javassist.CtClass)271 CtMethod (javassist.CtMethod)96 ClassPool (javassist.ClassPool)93 NotFoundException (javassist.NotFoundException)85 Test (org.junit.Test)63 CannotCompileException (javassist.CannotCompileException)62 CtField (javassist.CtField)53 IOException (java.io.IOException)35 CtConstructor (javassist.CtConstructor)26 Method (java.lang.reflect.Method)17 LoaderClassPath (javassist.LoaderClassPath)16 ClassFile (javassist.bytecode.ClassFile)14 ArrayList (java.util.ArrayList)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)11 ConstPool (javassist.bytecode.ConstPool)11 File (java.io.File)8 FileNotFoundException (java.io.FileNotFoundException)8 Collectors (java.util.stream.Collectors)8 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)7