com.sun.source.tree.ClassTree Java Examples

The following examples show how to use com.sun.source.tree.ClassTree. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a setter method for a field.
 *
 * @param clazz the class to create the setter within
 * @param field field to create setter for
 * @return the setter method
 * @since 0.20
 */
public MethodTree createSetter(ClassTree clazz, VariableTree field) {
    assert clazz != null && field != null;
    TreeMaker make = copy.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    boolean isStatic = field.getModifiers().getFlags().contains(Modifier.STATIC);
    if (isStatic)
        mods.add(Modifier.STATIC);
    CharSequence name = field.getName();
    assert name.length() > 0;
    CodeStyle cs = DiffContext.getCodeStyle(copy);
    String propName = removeFieldPrefixSuffix(field, cs);
    String setterName = CodeStyleUtils.computeSetterName(field.getName(), isStatic, cs);
    String paramName = addParamPrefixSuffix(propName, cs);
    List<VariableTree> params = Collections.singletonList(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), paramName, field.getType(), null));
    BlockTree body = make.Block(Collections.singletonList(make.ExpressionStatement(make.Assignment(make.MemberSelect(isStatic? make.Identifier(clazz.getSimpleName()) : make.Identifier("this"), name), make.Identifier(paramName)))), false); //NOI18N
    return make.Method(make.Modifiers(mods), setterName, make.Type(copy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), params, Collections.<ExpressionTree>emptyList(), body, null);
}
 
Example #2
Source File: ApplicationSubclassGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ClassTree createMethods(Collection<String> classNames, MethodTree getClasses,
        TreeMaker maker, ClassTree modified,
        CompilationController controller) throws IOException
{
    WildcardTree wildCard = maker.Wildcard(Tree.Kind.UNBOUNDED_WILDCARD,
            null);
    ParameterizedTypeTree wildClass = maker.ParameterizedType(
            maker.QualIdent(Class.class.getCanonicalName()),
            Collections.singletonList(wildCard));
    ParameterizedTypeTree wildSet = maker.ParameterizedType(
            maker.QualIdent(Set.class.getCanonicalName()),
            Collections.singletonList(wildClass));

    String methodBody = MiscPrivateUtilities.collectRestResources(classNames, restSupport, false);
    
    return MiscUtilities.createAddResourceClasses(maker, modified, controller, methodBody, false);
}
 
Example #3
Source File: ComputeImports.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitClass(ClassTree node, Map<String, Object> p) {
    if (getCurrentPath().getParentPath().getLeaf().getKind() != Kind.NEW_CLASS) {
        filterByAcceptedKind(node.getExtendsClause(), ElementKind.CLASS);
        for (Tree intf : node.getImplementsClause()) {
            filterByAcceptedKind(intf, ElementKind.INTERFACE, ElementKind.ANNOTATION_TYPE);
        }
    }

    scan(node.getModifiers(), p);
    scan(node.getTypeParameters(), p, true);
    scan(node.getExtendsClause(), p, true);
    scan(node.getImplementsClause(), p, true);
    scan(node.getMembers(), p);

    return null;
}
 
Example #4
Source File: NewArrayPretty.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
void run(String code) throws IOException {
    String src = "public class Test {" + code + ";}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));

    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCVariableDecl var =
                (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);

        if (!code.equals(var.toString())) {
            System.err.println("Expected: " + code);
            System.err.println("Obtained: " + var.toString());
            throw new RuntimeException("strings do not match!");
        }
    }
}
 
Example #5
Source File: WrappingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testVariableInitWrapped() throws Exception {
    String code = "package hierbas.del.litoral;\n\n" +
        "import java.util.concurrent.atomic.AtomicBoolean;\n\n" +
        "public class Test {\n" +
        "    public void t() {\n" +
        "        new AtomicBoolean();\n" + 
        "    }\n" +
        "}\n";
    runWrappingTest(code, new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ExpressionStatementTree init = (ExpressionStatementTree) method.getBody().getStatements().get(0);
            VariableTree nue = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "ab", make.Type("java.util.concurrent.atomic.AtomicBoolean"), init.getExpression());
            workingCopy.rewrite(init, nue);
        }
    }, FmtOptions.wrapAssignOps, WrapStyle.WRAP_IF_LONG.name());
}
 
Example #6
Source File: JavacParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testStartPositionForMethodWithoutModifiers() throws IOException {

    String code = "package t; class Test { <T> void t() {} }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree mt = (MethodTree) clazz.getMembers().get(0);
    Trees t = Trees.instance(ct);
    int start = (int) t.getSourcePositions().getStartPosition(cut, mt);
    int end = (int) t.getSourcePositions().getEndPosition(cut, mt);

    assertEquals("testStartPositionForMethodWithoutModifiers",
            "<T> void t() {}", code.substring(start, end));
}
 
Example #7
Source File: GeneratorUtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testGetterNamingConvention0() throws Exception {//#165241
    performTest("package test;\npublic class Test {\nprivate int eMai;\npublic Test(){\n}\n }\n", new GetterSetterTask(34, false), new Validator() {

        public void validate(CompilationInfo info) {
            ClassTree ct = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);

            for (Tree member : ct.getMembers()) {
                if (member.getKind() == Kind.METHOD) {
                    String name = ((MethodTree) member).getName().toString();
                    if (!name.equals("<init>")) {
                        assertEquals(name, "seteMai");
                    }
                }
            }
        }
    });
}
 
Example #8
Source File: AbstractMethodGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Adds method to class.
 * <p>
 * <b>Should be called outside EDT.</b>
 */
protected static void addMethod(final MethodModel methodModel, FileObject fileObject, final String className) throws IOException {
    if (fileObject != null && methodModel != null){
        JavaSource javaSource = JavaSource.forFileObject(fileObject);
        javaSource.runModificationTask(new Task<WorkingCopy>() {
            public void run(WorkingCopy workingCopy) throws IOException {
                workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                TypeElement typeElement = workingCopy.getElements().getTypeElement(className);
                boolean generateDefaultBody = (typeElement.getKind() != ElementKind.INTERFACE) && !methodModel.getModifiers().contains(Modifier.ABSTRACT);
                MethodTree methodTree = MethodModelSupport.createMethodTree(workingCopy, methodModel, generateDefaultBody);
                ClassTree classTree = workingCopy.getTrees().getTree(typeElement);
                ClassTree newClassTree = workingCopy.getTreeMaker().addClassMember(classTree, methodTree);
                workingCopy.rewrite(classTree, newClassTree);
            }
        }).commit();
    }
}
 
Example #9
Source File: BreadCrumbsNodeImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static String className(TreePath path) {
    ClassTree ct = (ClassTree) path.getLeaf();
    
    if (path.getParentPath().getLeaf().getKind() == Kind.NEW_CLASS) {
        NewClassTree nct = (NewClassTree) path.getParentPath().getLeaf();
        
        if (nct.getClassBody() == ct) {
            return simpleName(nct.getIdentifier());
        }
    } else if (path.getParentPath().getLeaf() == path.getCompilationUnit()) {
        ExpressionTree pkg = path.getCompilationUnit().getPackageName();
        String pkgName = pkg != null ? pkg.toString() : null;
        if (pkgName != null && !pkgName.contentEquals(ERR_NAME)) {
            return pkgName + '.' + ct.getSimpleName().toString();
        }
    }
    
    return ct.getSimpleName().toString();
}
 
Example #10
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeClass(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ClassTree ct = (ClassTree) parent.getLeaf();
    
    if (ct.getExtendsClause() == error) {
        types.add(ElementKind.CLASS);
        return null;
    }
    
    for (Tree t : ct.getImplementsClause()) {
        if (t == error) {
            types.add(ElementKind.INTERFACE);
            return null;
        }
    }
    
    //XXX: annotation types...
    
    return null;
}
 
Example #11
Source File: Trees.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the enclosing type declaration (class, enum, interface, or annotation) for the given
 * path.
 */
static ClassTree getEnclosingTypeDeclaration(TreePath path) {
    for (; path != null; path = path.getParentPath()) {
        switch (path.getLeaf().getKind()) {
            case CLASS:
            case ENUM:
            case INTERFACE:
                // TODO: 22-Jul-17 wrong??
            case ANNOTATION_TYPE:
                return (ClassTree) path.getLeaf();
            default:
                break;
        }
    }
    throw new AssertionError();
}
 
Example #12
Source File: MemberAdditionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Void visitClass(ClassTree node, Boolean p) {
    TypeElement te = (TypeElement)model.getElement(node);
    if (te != null) {
        List<Tree> members = new ArrayList<Tree>();
        for(Tree m : node.getMembers())
            members.add(m);
        members.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test", make.PrimitiveType(TypeKind.INT), null));
        ClassTree decl = make.Class(node.getModifiers(), node.getSimpleName(), node.getTypeParameters(), node.getExtendsClause(), (List<ExpressionTree>)node.getImplementsClause(), members);
        model.setElement(decl, te);
        model.setType(decl, model.getType(node));
        model.setPos(decl, model.getPos(node));
        copy.rewrite(node, decl);
    }
    
    return null;
}
 
Example #13
Source File: InsertTask.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ClassTree modifyJavaClass( WorkingCopy workingCopy,
        TreeMaker make, ClassTree javaClass, TypeElement classElement )
{
    Collection<String> existingImports = getImports(workingCopy);
    CompilationUnitTree original = workingCopy.getCompilationUnit();
    CompilationUnitTree modified = original;
    for (String imp : manager.getImports()) {
        if (!existingImports.contains(imp)) {
            modified = make.addCompUnitImport(
                    modified, make.Import(make.Identifier(imp), false));
        }
    }
    workingCopy.rewrite(original, modified);
    return insertSecurityFetaureField(workingCopy, make, javaClass, 
            classElement);
}
 
Example #14
Source File: ClassEncapsulation.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public ChangeInfo implement() throws Exception {
    final FileObject file = handle.getFileObject();
    final JTextComponent component = EditorRegistry.lastFocusedComponent();
    if (file != null && file == getFileObject(component)) {
        final int[] position = new int[] {-1};
        JavaSource.forFileObject(file).runUserActionTask(new Task<CompilationController>() {
            @Override
            public void run(CompilationController controller) throws Exception {
                controller.toPhase(JavaSource.Phase.PARSED);
                final TreePath tp = handle.resolve(controller);
                if (tp != null && TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
                    position[0] = (int) controller.getTrees().getSourcePositions().getStartPosition(
                            tp.getCompilationUnit(),
                            (ClassTree)tp.getLeaf())+1;
                }
            }
        }, true);
        invokeRefactoring(component, position[0]);
    }
    return null;
}
 
Example #15
Source File: JavacParserTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPreferredPositionForBinaryOp() throws IOException {

    String code = "package test; public class Test {"
            + "private void test() {"
            + "Object o = null; boolean b = o != null && o instanceof String;"
            + "} private Test() {}}";

    CompilationUnitTree cut = getCompilationUnitTree(code);
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree method = (MethodTree) clazz.getMembers().get(0);
    VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
    BinaryTree cond = (BinaryTree) condSt.getInitializer();

    JCTree condJC = (JCTree) cond;
    int condStartPos = code.indexOf("&&");
    assertEquals("testPreferredPositionForBinaryOp",
            condStartPos, condJC.pos);
}
 
Example #16
Source File: LocalClassScanner.java    From annotation-tools with MIT License 6 votes vote down vote up
@Override
public Void visitBlock(BlockTree node, Integer level) {
  if (level < 1) {
    // Visit blocks since a local class can only be in a block. Then visit each
    // statement of the block to see if any are the correct local class.
    for (StatementTree statement : node.getStatements()) {
      if (!found && statement.getKind() == Tree.Kind.CLASS) {
        ClassTree c = (ClassTree) statement;
        if (localClass == statement) {
          found = true;
        } else if (c.getSimpleName().equals(localClass.getSimpleName())) {
          index++;
        }
      }
    }
    super.visitBlock(node, level + 1);
  }
  return null;
}
 
Example #17
Source File: JavaFixUtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void performArithmeticTest(String orig, String nue) throws Exception {
    String code = replace("0");

    prepareTest("Test.java", code);
    ClassTree clazz = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);
    VariableTree variable = (VariableTree) clazz.getMembers().get(1);
    ExpressionTree init = variable.getInitializer();
    TreePath tp = new TreePath(new TreePath(new TreePath(new TreePath(info.getCompilationUnit()), clazz), variable), init);
    Fix fix = JavaFixUtilities.rewriteFix(info, "A", tp, orig, Collections.<String, TreePath>emptyMap(), Collections.<String, Collection<? extends TreePath>>emptyMap(), Collections.<String, String>emptyMap(), Collections.<String, TypeMirror>emptyMap(), Collections.<String, String>emptyMap());
    fix.implement();

    String golden = replace(nue);
    String out = doc.getText(0, doc.getLength());

    assertEquals(golden, out);

    LifecycleManager.getDefault().saveAll();
}
 
Example #18
Source File: NewArrayPretty.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
void run(String code) throws IOException {
    String src = "public class Test {" + code + ";}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));

    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCVariableDecl var =
                (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);

        if (!code.equals(var.toString())) {
            System.err.println("Expected: " + code);
            System.err.println("Obtained: " + var.toString());
            throw new RuntimeException("strings do not match!");
        }
    }
}
 
Example #19
Source File: AnnotationAsSuperInterface.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static Iterable<ErrorDescription> run(HintContext ctx) {
    Element e = ctx.getInfo().getTrees().getElement(ctx.getPath());

    if ( e == null || !(e instanceof TypeElement) ) {
        return null;
    }
    
    List<ErrorDescription> eds = new ArrayList<ErrorDescription>();
    
    for (Tree i : ((ClassTree) ctx.getPath().getLeaf()).getImplementsClause()) {
        Element ie = ctx.getInfo().getTrees().getElement(new TreePath(ctx.getPath(), i));

        if (ie != null && ie.getKind() == ElementKind.ANNOTATION_TYPE) {
            eds.add(ErrorDescriptionFactory.forTree(ctx, i, NbBundle.getMessage(AnnotationAsSuperInterface.class,
                                "HNT_AnnotationAsSuperInterface",  // NOI18N
                                ie.getSimpleName().toString())));
        }
    }

    return eds;
}
 
Example #20
Source File: PullUpRefactoringUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TreePath findSelectedClassMemberDeclaration(final TreePath path, final CompilationInfo javac) {
    TreePath currentPath = path;
    TreePath selection = null;
    while (currentPath != null && selection == null) {
        switch (currentPath.getLeaf().getKind()) {
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
            case NEW_CLASS:
            case METHOD:
                selection = currentPath;
                break;
            case VARIABLE:
                Element elm = javac.getTrees().getElement(currentPath);
                if (elm != null && elm.getKind().isField()) {
                    selection = currentPath;
                }
                break;
        }
        if (selection != null && javac.getTreeUtilities().isSynthetic(selection)) {
            selection = null;
        }
        if (selection == null) {
            currentPath = currentPath.getParentPath();
        }
    }
    
    if (selection == null && path != null) {
        List<? extends Tree> typeDecls = path.getCompilationUnit().getTypeDecls();
        if (!typeDecls.isEmpty() && typeDecls.get(0).getKind().asInterface() == ClassTree.class) {
            selection = TreePath.getPath(path.getCompilationUnit(), typeDecls.get(0));
        }
    }
    return selection;
}
 
Example #21
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testIsEnumConstant() throws Exception {
    prepareTest("Test", "package test; public enum Test {B; private static final int ii = 0;}");
    ClassTree clazz = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);
    Tree b = clazz.getMembers().get(1);
    assertTrue(info.getTreeUtilities().isEnumConstant((VariableTree) b));
    Tree ii = clazz.getMembers().get(2);
    assertFalse(info.getTreeUtilities().isEnumConstant((VariableTree) ii));
}
 
Example #22
Source File: ImportAnalysis2Test.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testStringQualIdentNewlyCreatedSamePackage() throws Exception {
    testFile = new File(getWorkDir(), "hierbas/del/litoral/Test.java");
    assertTrue(testFile.getParentFile().mkdirs());
    TestUtilities.copyStringToFile(testFile,
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "\n" +
        "    A l;\n" +
        "}\n";

    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree nueClass = make.Class(make.Modifiers(EnumSet.noneOf(Modifier.class)), "A", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList());
            CompilationUnitTree nueCUT = make.CompilationUnit(FileUtil.toFileObject(getWorkDir()), "hierbas/del/litoral/A.java", Collections.<ImportTree>emptyList(), Collections.singletonList(nueClass));
            workingCopy.rewrite(null, nueCUT);
            CompilationUnitTree node = workingCopy.getCompilationUnit();
            ClassTree clazz = (ClassTree) node.getTypeDecls().get(0);
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "l", make.QualIdent("hierbas.del.litoral.A"), null);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, vt));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #23
Source File: ScanStatement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitClass(ClassTree node, Void p) {
    nesting++;
    super.visitClass(node, p);
    nesting--;
    return null;
}
 
Example #24
Source File: MethodInputParametersMustBeFinal.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
public Description matchClass(final ClassTree tree, final VisitorState state) {
  isAbstraction =
      isInterface(tree.getModifiers())
          || isAnonymousClassInAbstraction(tree)
          || isEnumInAbstraction(tree);
  return Description.NO_MATCH;
}
 
Example #25
Source File: JerseyGenerationStrategy.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
ClassTree generateOAuthMethods( String projectType,
        WorkingCopy copy, ClassTree classTree, Metadata oauthMetadata)
{
    return OAuthHelper.addOAuthMethods( projectType, copy, classTree, 
            oauthMetadata, classTree.getSimpleName().toString());
}
 
Example #26
Source File: MethodThrowsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testRemoveMid() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "import java.io.*;\n\n" +
        "public class Test {\n" +
        "    public void taragui() throws IOException, FileNotFoundException, Exception {\n" +
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "import java.io.*;\n\n" +
        "public class Test {\n" +
        "    public void taragui() throws IOException, Exception {\n" +
        "    }\n" +
        "}\n";

    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();

            for (Tree typeDecl : cut.getTypeDecls()) {
                // should check kind, here we can be sure!
                ClassTree clazz = (ClassTree) typeDecl;
                MethodTree method = (MethodTree) clazz.getMembers().get(1);
                MethodTree copy = make.removeMethodThrows(method, 1);
                workingCopy.rewrite(method, copy);
            }
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    assertEquals(golden, res);
}
 
Example #27
Source File: T6665791.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    write(test_java, test);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager manager =
            compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> units = manager.getJavaFileObjects(test_java);
    final StringWriter sw = new StringWriter();
    JavacTask task = (JavacTask) compiler.getTask(sw, manager, null, null,
            null, units);

    new TreeScanner<Boolean, Void>() {
        @Override
        public Boolean visitClass(ClassTree arg0, Void arg1) {
            sw.write(arg0.toString());
            return super.visitClass(arg0, arg1);
        }
    }.scan(task.parse(), null);

    System.out.println("output:");
    System.out.println(sw.toString());
    String found = sw.toString().replaceAll("\\s+", " ").trim();
    String expect = test.replaceAll("\\s+", " ").trim();
    if (!expect.equals(found)) {
        System.out.println("expect: " + expect);
        System.out.println("found:  " + found);
        throw new Exception("unexpected output");
    }
}
 
Example #28
Source File: GeneratorUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testOverrideAnnotation2() throws Exception {
    performTest("package test;\npublic class Test extends C implements B { }\ninterface A {public void test1(); public void test4();}\ninterface B {public void test2();}\nabstract class C implements A {public abstract void test3(); public abstract void test4();}\n", "1.6", new AddAllAbstractMethodsTask(30), new Validator() {
        public void validate(CompilationInfo info) {
            ClassTree ct = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);

            for (Tree member : ct.getMembers()) {
                MethodTree m = (MethodTree) member;

                if ("test1".equals(m.getName().toString())) {
                    assertFalse(m.getModifiers().getAnnotations().isEmpty());
                }

                if ("test2".equals(m.getName().toString())) {
                    assertFalse(m.getModifiers().getAnnotations().isEmpty());
                }

                if ("test3".equals(m.getName().toString())) {
                    assertFalse(m.getModifiers().getAnnotations().isEmpty());
                }

                if ("test4".equals(m.getName().toString())) {
                    assertFalse(m.getModifiers().getAnnotations().isEmpty());
                }
            }
        }
    });
}
 
Example #29
Source File: JavacParserTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
void testErrorRecoveryForEnhancedForLoop142381() throws IOException {

    String code = "package test; class Test { " +
            "private void method() { " +
            "java.util.Set<String> s = null; for (a : s) {} } }";

    final List<Diagnostic<? extends JavaFileObject>> errors =
            new LinkedList<Diagnostic<? extends JavaFileObject>>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
            new DiagnosticListener<JavaFileObject>() {
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            errors.add(diagnostic);
        }
    }, null, null, Arrays.asList(new MyFileObject(code)));

    CompilationUnitTree cut = ct.parse().iterator().next();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    StatementTree forStatement =
            ((MethodTree) clazz.getMembers().get(0)).getBody().getStatements().get(1);

    assertEquals("testErrorRecoveryForEnhancedForLoop142381",
            Kind.ENHANCED_FOR_LOOP, forStatement.getKind());
    assertFalse("testErrorRecoveryForEnhancedForLoop142381", errors.isEmpty());
}
 
Example #30
Source File: MemberAdditionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testClassImplementingList() throws Exception {
    performTest("ClassImplementingList");

    source.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(Phase.RESOLVED);
            ClassTree topLevel = findTopLevelClass(copy);
            SourceUtilsTestUtil2.run(copy, new AddSimpleField(), topLevel);
        }
    }).commit();

    JavaSourceAccessor.getINSTANCE().revalidate(source);
    
    CompilationInfo check = SourceUtilsTestUtil.getCompilationInfo(source, Phase.RESOLVED);
    CompilationUnitTree cu = check.getCompilationUnit();

    assertEquals(check.getDiagnostics().toString(), 1, check.getDiagnostics().size());
    assertEquals("compiler.err.does.not.override.abstract", check.getDiagnostics().get(0).getCode());
    
    ClassTree newTopLevel = findTopLevelClass(check);
    Element clazz = check.getTrees().getElement(TreePath.getPath(cu, newTopLevel));
    Element pack = clazz.getEnclosingElement();
    
    assertEquals(ElementKind.PACKAGE, pack.getKind());
    assertEquals("test", ((PackageElement) pack).getQualifiedName().toString());
    assertEquals(clazz.getEnclosedElements().toString(), 1 + 1/*syntetic default constructor*/, clazz.getEnclosedElements().size());
}