Search in sources :

Example 26 with CtAnnotation

use of spoon.reflect.declaration.CtAnnotation in project spoon by INRIA.

the class AnnotationValuesTest method testCtAnnotationAPI.

@Test
public void testCtAnnotationAPI() throws Exception {
    Factory factory = ModelUtils.createFactory();
    CtAnnotation<Annotation> annotation = factory.Core().createAnnotation();
    annotation.addValue("integers", 7);
    on(annotation).giveMeAnnotationValue("integers").isTypedBy(CtLiteral.class);
    annotation.addValue("integers", 42);
    on(annotation).giveMeAnnotationValue("integers").isTypedBy(CtNewArray.class);
    annotation.addValue("classes", String.class);
    on(annotation).giveMeAnnotationValue("classes").isTypedBy(CtFieldAccess.class);
    annotation.addValue("classes", Integer.class);
    on(annotation).giveMeAnnotationValue("classes").isTypedBy(CtNewArray.class);
    annotation.addValue("field", AnnotationValuesTest.class.getDeclaredField("i"));
    on(annotation).giveMeAnnotationValue("field").isTypedBy(CtFieldAccess.class);
}
Also used : ModelUtils.createFactory(spoon.testing.utils.ModelUtils.createFactory) Factory(spoon.reflect.factory.Factory) CtAnnotation(spoon.reflect.declaration.CtAnnotation) Annotation(java.lang.annotation.Annotation) Test(org.junit.Test)

Example 27 with CtAnnotation

use of spoon.reflect.declaration.CtAnnotation in project spoon by INRIA.

the class CtRenameLocalVariableRefactoringTest method testRenameAllLocalVariablesOfRenameTestSubject.

/**
 * The {@link CtRenameLocalVariableRefactoringTestSubject} class is loaded as spoon model. Then:
 * - It looks for each CtVariable and it's CtAnnotation and tries to rename that variable to the name defined by annotation.
 * - If the annotation name is prefixed with "-", then that refactoring should fail.
 * - If the annotation name is not prefixed, then that refactoring should pass.
 * If it behaves different then expected, then this test fails
 */
@Test
public void testRenameAllLocalVariablesOfRenameTestSubject() throws Exception {
    final Launcher launcher = new Launcher();
    final SpoonModelBuilder comp = launcher.createCompiler();
    comp.addInputSources(SpoonResourceHelper.resources("./src/test/java/" + CtRenameLocalVariableRefactoringTestSubject.class.getName().replace('.', '/') + ".java"));
    comp.build();
    final Factory factory = comp.getFactory();
    CtClass<?> varRenameClass = (CtClass<?>) factory.Type().get(CtRenameLocalVariableRefactoringTestSubject.class);
    CtTypeReference<TestTryRename> tryRename = varRenameClass.getFactory().createCtTypeReference(TestTryRename.class);
    varRenameClass.getMethods().forEach(method -> {
        // debugging support
        if (DEBUG.length == 3 && DEBUG[0].equals(method.getSimpleName()) == false)
            return;
        method.filterChildren((CtVariable var) -> true).map((CtVariable var) -> var.getAnnotation(tryRename)).forEach((CtAnnotation<TestTryRename> annotation) -> {
            String[] newNames = annotation.getActualAnnotation().value();
            CtVariable<?> targetVariable = (CtVariable<?>) annotation.getAnnotatedElement();
            for (String newName : newNames) {
                boolean renameShouldPass = newName.startsWith("-") == false;
                if (!renameShouldPass) {
                    newName = newName.substring(1);
                }
                if (targetVariable instanceof CtLocalVariable<?>) {
                    // debugging support
                    if (DEBUG.length == 3 && DEBUG[1].equals(targetVariable.getSimpleName()) && DEBUG[2].equals(newName)) {
                        // put breakpoint here and continue debugging of the buggy case
                        this.getClass();
                    }
                    checkLocalVariableRename(launcher, (CtLocalVariable<?>) targetVariable, newName, renameShouldPass);
                } else {
                // TODO test rename of other variables, e.g. parameters and catch... later
                }
            }
        });
    });
}
Also used : SpoonModelBuilder(spoon.SpoonModelBuilder) CtAnnotation(spoon.reflect.declaration.CtAnnotation) Factory(spoon.reflect.factory.Factory) CtLocalVariable(spoon.reflect.code.CtLocalVariable) CtClass(spoon.reflect.declaration.CtClass) TestTryRename(spoon.test.refactoring.testclasses.TestTryRename) CtVariable(spoon.reflect.declaration.CtVariable) Launcher(spoon.Launcher) CtRenameLocalVariableRefactoringTestSubject(spoon.test.refactoring.testclasses.CtRenameLocalVariableRefactoringTestSubject) Test(org.junit.Test)

Example 28 with CtAnnotation

use of spoon.reflect.declaration.CtAnnotation in project spoon by INRIA.

the class PackageTest method testAddAnnotationToPackage.

@Test
public void testAddAnnotationToPackage() throws Exception {
    // contract: Created package-info should used imports in auto-import
    final Launcher spoon = new Launcher();
    spoon.addInputResource("./src/test/java/spoon/test/pkg/testclasses/Foo.java");
    spoon.getEnvironment().setAutoImports(true);
    File outputDir = new File("./target/spoon-packageinfo");
    spoon.getEnvironment().setSourceOutputDirectory(outputDir);
    spoon.buildModel();
    CtAnnotationType annotationType = (CtAnnotationType) spoon.getFactory().Annotation().get(GlobalAnnotation.class);
    CtAnnotation annotation = spoon.getFactory().Core().createAnnotation();
    annotation.setAnnotationType(annotationType.getReference());
    CtPackage ctPackage = spoon.getFactory().Package().get("spoon.test.pkg.testclasses");
    ctPackage.addAnnotation(annotation);
    JavaOutputProcessor outputProcessor = spoon.createOutputWriter();
    outputProcessor.process(ctPackage);
    File packageInfo = new File(outputDir, "spoon/test/pkg/testclasses/package-info.java");
    assertTrue(packageInfo.exists());
    canBeBuilt(packageInfo, 8);
    List<String> lines = Files.readAllLines(packageInfo.toPath());
    assertFalse(lines.isEmpty());
    for (String s : lines) {
        if (s.trim().startsWith("import")) {
            assertEquals("import spoon.test.annotation.testclasses.GlobalAnnotation;", s.trim());
        }
        if (s.trim().startsWith("@")) {
            assertEquals("@GlobalAnnotation", s.trim());
        }
    }
}
Also used : CtAnnotation(spoon.reflect.declaration.CtAnnotation) GlobalAnnotation(spoon.test.annotation.testclasses.GlobalAnnotation) Launcher(spoon.Launcher) CtAnnotationType(spoon.reflect.declaration.CtAnnotationType) CtPackage(spoon.reflect.declaration.CtPackage) File(java.io.File) JavaOutputProcessor(spoon.support.JavaOutputProcessor) Test(org.junit.Test)

Example 29 with CtAnnotation

use of spoon.reflect.declaration.CtAnnotation in project spoon by INRIA.

the class DefaultJavaPrettyPrinter method printPackageInfo.

@Override
public String printPackageInfo(CtPackage pack) {
    reset();
    elementPrinterHelper.writeComment(pack);
    // we don't want to get all imports coming from content of package
    for (CtAnnotation annotation : pack.getAnnotations()) {
        this.importsContext.computeImports(annotation);
    }
    elementPrinterHelper.writeAnnotations(pack);
    if (!pack.isUnnamedPackage()) {
        elementPrinterHelper.writePackageLine(pack.getQualifiedName());
    }
    elementPrinterHelper.writeImports(this.importsContext.getAllImports());
    return printer.getPrinterHelper().toString();
}
Also used : CtAnnotation(spoon.reflect.declaration.CtAnnotation)

Example 30 with CtAnnotation

use of spoon.reflect.declaration.CtAnnotation in project spoon by INRIA.

the class GenericsTest method testBugCommonCollection.

@Test
public void testBugCommonCollection() throws Exception {
    try {
        CtClass<?> type = build("spoon.test.generics", "BugCollection");
        CtField<?> INSTANCE = type.getElements(new NamedElementFilter<>(CtField.class, "INSTANCE")).get(0);
        // assertTrue(INSTANCE.getDefaultExpression().getType().getActualTypeArguments().get(0)
        // instanceof CtAnnonTypeParameterReference);
        assertEquals("public static final spoon.test.generics.ACLass<?> INSTANCE = new spoon.test.generics.ACLass();", INSTANCE.toString());
        CtField<?> INSTANCE2 = type.getElements(new NamedElementFilter<>(CtField.class, "INSTANCE2")).get(0);
        INSTANCE2.setAnnotations(new ArrayList<CtAnnotation<?>>());
        assertEquals("public static final spoon.test.generics.ACLass<?> INSTANCE2 = new spoon.test.generics.ACLass();", INSTANCE2.toString());
        CtClass<?> ComparableComparator = type.getPackage().getElements(new NamedElementFilter<>(CtClass.class, "ComparableComparator")).get(0);
        assertTrue(ComparableComparator.toString().startsWith("class ComparableComparator<E extends java.lang.Comparable<? super E>>"));
        CtField<?> x = type.getElements(new NamedElementFilter<>(CtField.class, "x")).get(0);
        CtTypeReference<?> ref = x.getType();
        DefaultJavaPrettyPrinter pp = new DefaultJavaPrettyPrinter(new StandardEnvironment());
        // qualifed name
        assertEquals("java.util.Map$Entry", ref.getQualifiedName());
        // toString uses DefaultJavaPrettyPrinter
        assertEquals("java.util.Map.Entry", ref.toString());
        // now visitCtTypeReference
        assertEquals(java.util.Map.class, ref.getDeclaringType().getActualClass());
        pp.visitCtTypeReference(ref);
        assertEquals("java.util.Map.Entry", pp.getResult().toString());
        CtField<?> y = type.getElements(new NamedElementFilter<>(CtField.class, "y")).get(0);
        assertEquals("java.util.Map.Entry<?, ?> y;", y.toString());
        CtField<?> z = type.getElements(new NamedElementFilter<>(CtField.class, "z")).get(0);
        assertEquals("java.util.Map.Entry<java.lang.String, java.lang.Integer> z;", z.toString());
        // now as local variables
        CtLocalVariable<?> lx = type.getElements(new NamedElementFilter<>(CtLocalVariable.class, "lx")).get(0);
        assertEquals("java.util.Map.Entry lx", lx.toString());
        CtLocalVariable<?> ly = type.getElements(new NamedElementFilter<>(CtLocalVariable.class, "ly")).get(0);
        assertEquals("java.util.Map.Entry<?, ?> ly", ly.toString());
        CtLocalVariable<?> lz = type.getElements(new NamedElementFilter<>(CtLocalVariable.class, "lz")).get(0);
        assertEquals("java.util.Map.Entry<java.lang.String, java.lang.Integer> lz", lz.toString());
        CtLocalVariable<?> it = type.getElements(new NamedElementFilter<>(CtLocalVariable.class, "it")).get(0);
        assertEquals("java.util.Iterator<java.util.Map.Entry<?, ?>> it", it.toString());
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}
Also used : CtAnnotation(spoon.reflect.declaration.CtAnnotation) NamedElementFilter(spoon.reflect.visitor.filter.NamedElementFilter) DefaultJavaPrettyPrinter(spoon.reflect.visitor.DefaultJavaPrettyPrinter) StandardEnvironment(spoon.support.StandardEnvironment) MainTest(spoon.test.main.MainTest) Test(org.junit.Test)

Aggregations

CtAnnotation (spoon.reflect.declaration.CtAnnotation)43 Test (org.junit.Test)37 Launcher (spoon.Launcher)35 Factory (spoon.reflect.factory.Factory)30 Annotation (java.lang.annotation.Annotation)20 CtClass (spoon.reflect.declaration.CtClass)19 GlobalAnnotation (spoon.test.annotation.testclasses.GlobalAnnotation)19 TypeAnnotation (spoon.test.annotation.testclasses.TypeAnnotation)19 AnnotationDefaultAnnotation (spoon.test.annotation.testclasses.AnnotationDefaultAnnotation)18 InnerAnnotation (spoon.test.annotation.testclasses.Foo.InnerAnnotation)18 MiddleAnnotation (spoon.test.annotation.testclasses.Foo.MiddleAnnotation)18 OuterAnnotation (spoon.test.annotation.testclasses.Foo.OuterAnnotation)18 SuperAnnotation (spoon.test.annotation.testclasses.SuperAnnotation)18 CtMethod (spoon.reflect.declaration.CtMethod)12 CtTypeReference (spoon.reflect.reference.CtTypeReference)8 CtType (spoon.reflect.declaration.CtType)6 AnnotationsRepeated (spoon.test.annotation.testclasses.AnnotationsRepeated)6 AbstractFilter (spoon.reflect.visitor.filter.AbstractFilter)4 NamedElementFilter (spoon.reflect.visitor.filter.NamedElementFilter)4 SpoonException (spoon.SpoonException)3