Java 类com.sun.source.tree.ClassTree 实例源码

项目:incubator-netbeans    文件:Common.java   
public static ClassTree getClassTree(
        TreeMaker make,
        WorkingCopy workingCopy,
        String name,
        String superClass,
        List<ExpressionTree> implementsList,
        Set<Modifier> modifiers) {        

    Tree extendsTree = make.QualIdent(workingCopy.getElements().getTypeElement(superClass));        
    Map<String,String> params = new HashMap<String, String>();
    params.put("param1", "String");
    MethodTree mt = Common.createMethod(make, "method", params);
    VariableTree vt = Common.createField(make, "variable", EnumSet.of(Modifier.PROTECTED), "double");
    List<Tree> members = new ArrayList<Tree>();
    members.add(mt);
    members.add(vt);
    members.add(make.Block(Collections.EMPTY_LIST, false));
    ClassTree innerClass = make.Class(
            make.Modifiers(modifiers),
            name,
            Collections.EMPTY_LIST,
            extendsTree,
            implementsList,
            members);        
    return innerClass;
}
项目:incubator-netbeans    文件:GeneratorUtilitiesTest.java   
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");
                    }
                }
            }
        }
    });
}
项目:incubator-netbeans    文件:EntityManagerGenerator.java   
private EntityManagerGenerationStrategy instantiateStrategy(Class<? extends EntityManagerGenerationStrategy> strategy, WorkingCopy workingCopy,
        TreeMaker make, ClassTree clazz, GenerationOptions options){

    EntityManagerGenerationStrategy result = null;

    try{
        result = strategy.newInstance();
        result.setClassTree(clazz);
        result.setWorkingCopy(workingCopy);
        result.setGenerationOptions(options);
        result.setTreeMaker(make);
        result.setPersistenceUnit(getPersistenceUnit());
    } catch (IllegalAccessException iae){
        throw new RuntimeException(iae); //TODO
    } catch (InstantiationException ie){
        throw new RuntimeException(ie); //TODO
    }

    return result;
}
项目:incubator-netbeans    文件:EntityManagerGenerationStrategySupportTest.java   
public void run(WorkingCopy workingCopy) throws Exception {

    workingCopy.toPhase(Phase.RESOLVED);
    CompilationUnitTree cut = workingCopy.getCompilationUnit();
    TreeMaker make = workingCopy.getTreeMaker();

    for (Tree typeDeclaration : cut.getTypeDecls()){
        if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDeclaration.getKind())){
            ClassTree clazz = (ClassTree) typeDeclaration;
            EntityManagerGenerationStrategySupport strategy =
                    (EntityManagerGenerationStrategySupport) getStrategy(workingCopy, make, clazz, new GenerationOptions());
            doAsserts(strategy);
        } else {
            fail("No class found"); // should not happen
        }
    }
}
项目:incubator-netbeans    文件:TopClassFinder.java   
/**
 * 
 * @return  list of top classes, or an empty list of none were found
 */
static List<ClassTree> findTopClasses(
                                    CompilationUnitTree compilationUnit,
                                    TreeUtilities treeUtils) {
    List<? extends Tree> typeDecls = compilationUnit.getTypeDecls();
    if ((typeDecls == null) || typeDecls.isEmpty()) {
        return Collections.<ClassTree>emptyList();
    }

    List<ClassTree> result = new ArrayList<ClassTree>(typeDecls.size());

    for (Tree typeDecl : typeDecls) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
            ClassTree clsTree = (ClassTree) typeDecl;
            if (isTestable(clsTree, treeUtils)) {
                result.add(clsTree);
            }
        }
    }

    return result;
}
项目:incubator-netbeans    文件:TestUtil.java   
/**
 * Finds a main class.
 *
 * @param  compInfo  defines scope in which the class is to be found
 * @param  className  name of the class to be found
 * @return  the found class; or <code>null</code> if the class was not
 *          found (e.g. because of a broken source file)
 */
public static ClassTree findMainClass(final CompilationInfo compInfo) {
    final String className = compInfo.getFileObject().getName();

    CompilationUnitTree compUnitTree = compInfo.getCompilationUnit();
    String shortClassName = getSimpleName(className);
    for (Tree typeDecl : compUnitTree.getTypeDecls()) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
            ClassTree clazz = (ClassTree) typeDecl;
            if (clazz.getSimpleName().toString().equals(shortClassName)) {
                return clazz;
            }
        }
    }
    return null;
}
项目:Pogamut3    文件:EnumStructureFactory.java   
@Override
public synchronized Void visitClass(ClassTree t, Void v) {
    Element el = info.getTrees().getElement(getCurrentPath());
    if (el == null) {
        return null;
    }
    TypeElement te = (TypeElement) el;
    List<VariableElement> fields = ElementFilter.fieldsIn(te.getEnclosedElements());
    enumConsts = new LinkedList<String>();
    for (VariableElement field : fields) {
        if (field.getKind() == ElementKind.ENUM_CONSTANT) {
            String name = field.getSimpleName().toString();
            enumConsts.add(name);
        }
    }
    return null;
}
项目:incubator-netbeans    文件:TestGenerator.java   
/**
 */
@Override
protected ClassTree composeNewTestClass(WorkingCopy workingCopy,
                                        String name,
                                        List<? extends Tree> members) {
    final TreeMaker maker = workingCopy.getTreeMaker();
    ModifiersTree modifiers = maker.Modifiers(
                                  Collections.<Modifier>singleton(PUBLIC));
    return maker.Class(
                modifiers,                                 //modifiers
                name,                                      //name
                Collections.<TypeParameterTree>emptyList(),//type params
                null,                                      //extends
                Collections.<ExpressionTree>emptyList(),   //implements
                members);                                  //members
}
项目:incubator-netbeans    文件:WrappingTest.java   
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());
}
项目:incubator-netbeans    文件:JUnit3TestGenerator.java   
/**
 */
protected ClassTree composeNewTestClass(WorkingCopy workingCopy,
                                        String name,
                                        List<? extends Tree> members) {
    final TreeMaker maker = workingCopy.getTreeMaker();
    ModifiersTree modifiers = maker.Modifiers(
                                  Collections.<Modifier>singleton(PUBLIC));
    Tree extendsClause = getClassIdentifierTree(TEST_CASE, workingCopy);
    return maker.Class(
                modifiers,                                 //modifiers
                name,                                      //name
                Collections.<TypeParameterTree>emptyList(),//type params
                extendsClause,                             //extends
                Collections.<ExpressionTree>emptyList(),   //implements
                members);                                  //members
}
项目:incubator-netbeans    文件:JavaFixUtilitiesTest.java   
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();
}
项目:javaide    文件:JavaInputAstVisitor.java   
public void visitAnnotationType(ClassTree node) {
    sync(node);
    builder.open(ZERO);
    visitAndBreakModifiers(node.getModifiers(), Direction.VERTICAL, Optional.<BreakTag>absent());
    builder.open(ZERO);
    token("@");
    token("interface");
    builder.breakOp(" ");
    visit(node.getSimpleName());
    builder.close();
    builder.close();
    if (node.getMembers() == null) {
        builder.open(plusFour);
        token(";");
        builder.close();
    } else {
        addBodyDeclarations(node.getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
    }
    builder.guessToken(";");
}
项目:incubator-netbeans    文件:ImplementSerializable.java   
public ChangeInfo implement(){
    CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>(){
        public void cancel() {}

        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TypeElement clazz = classHandle.resolve(workingCopy);

            if (clazz != null){    
                ClassTree clazzTree = workingCopy.getTrees().getTree(clazz);
                GenerationUtils genUtils = GenerationUtils.newInstance(workingCopy);
                ClassTree modifiedClazz = genUtils.addImplementsClause(clazzTree, "java.io.Serializable"); // NOI18N
                workingCopy.rewrite(clazzTree, modifiedClazz);
            }
        }
    };

    JavaSource javaSource = JavaSource.forFileObject(fileObject);

    try{
        javaSource.runModificationTask(task).commit();
    } catch (IOException e){
        JPAProblemFinder.LOG.log(Level.SEVERE, e.getMessage(), e);
    }
    return null;
}
项目:incubator-netbeans    文件:GeneratorUtilities.java   
/**
 * 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);
}
项目:incubator-netbeans    文件:GenerationUtilsTest.java   
public void testEnsureNoArgConstructorMakesConstructorPublic() throws Exception {
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "    private TestClass() {" +
            "    }" +
            "}");
    runModificationTask(testFO, new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws Exception {
            GenerationUtils genUtils = GenerationUtils.newInstance(copy);
            ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0);
            ClassTree newClassTree = genUtils.ensureNoArgConstructor(classTree);
            copy.rewrite(classTree, newClassTree);
        }
    }).commit();
    runUserActionTask(testFO, new Task<CompilationController>() {
        public void run(CompilationController controller) throws Exception {
            TypeElement typeElement = SourceUtils.getPublicTopLevelElement(controller);
            assertTrue(SourceUtils.getNoArgConstructor(controller, typeElement).getModifiers().contains(Modifier.PUBLIC));
        }
    });
}
项目:incubator-netbeans    文件:TreePathHandleTest.java   
public void testEmptyMod() throws Exception {
    FileObject file = FileUtil.createData(sourceRoot, "test/test.java");

    writeIntoFile(file, "package test; public class test { String a; }");

    JavaSource js = JavaSource.forFileObject(file);

    SourceUtilsTestUtil.compileRecursively(sourceRoot);

    js.runUserActionTask(new  Task<CompilationController>() {
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(Phase.RESOLVED);

            TypeElement test = parameter.getElements().getTypeElement("test.test");

            TreePath path  = parameter.getTrees().getPath(test);
            TreePath field = new TreePath(path, ((ClassTree) path.getLeaf()).getMembers().get(1));
            TreePath mods  = new TreePath(field, ((VariableTree) field.getLeaf()).getModifiers());

            assertSame(mods.getLeaf(), TreePathHandle.create(mods, parameter).resolve(parameter).getLeaf());
        }
    }, true);
}
项目:incubator-netbeans    文件:AnnotationAsSuperInterface.java   
@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;
}
项目:openjdk-jdk10    文件:TypeAnnotationsPretty.java   
private void runMethod(String code) throws IOException {
    String src = prefix +
            code + "}" +
            postfix;

    try (JavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
                null, Arrays.asList(new MyFileObject(src)));


        for (CompilationUnitTree cut : ct.parse()) {
            JCTree.JCMethodDecl meth =
                    (JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
            checkMatch(code, meth);
        }
    }
}
项目:incubator-netbeans    文件:CreateMethodFix.java   
private static BlockTree createDefaultMethodBody(WorkingCopy wc, TreePath targetTree, TypeMirror returnType, String name) {
    TreeUtilities tu = wc.getTreeUtilities();
    TypeElement targetClazz = (TypeElement)wc.getTrees().getElement(targetTree);
    StatementTree st = tu.parseStatement("{class ${abstract " + (returnType != null ? returnType.toString() : "void") + " " + ("<init>".equals(name) ? targetClazz.getSimpleName() : name) + "();}}", new SourcePositions[1]); //NOI18N
    Trees trees = wc.getTrees();
    List<? extends Tree> members = ((ClassTree) targetTree.getLeaf()).getMembers();
    Scope scope = members.isEmpty() ? trees.getScope(targetTree) : trees.getScope(new TreePath(targetTree, members.get(0)));
    tu.attributeTree(st, scope);
    Tree first = null;
    for(Tree t : ((ClassTree)((BlockTree)st).getStatements().get(0)).getMembers()) {
        if (t.getKind() == Tree.Kind.METHOD && !"<init>".contentEquals(((MethodTree)t).getName())) { //NOI19N
            first = t;
            break;
        }
    }
    ExecutableElement ee = (ExecutableElement) wc.getTrees().getElement(new TreePath(targetTree, first));
    return GeneratorUtilities.get(wc).createAbstractMethodImplementation(targetClazz, ee).getBody();
}
项目:incubator-netbeans    文件:IntroduceConstantFix.java   
/**
 * Creates an 'introduce constant' fix.
 *
 * Note: the fix will not reference CompilationInfo and will remember only handles to TreePaths.
 *
 * @param resolved the path for expression or variable declaration to convert
 * @param info compilation context
 * @param value the actual expression or a variable initializer.
 * @param guessedName proposed name
 * @param numDuplicates number of other duplicates
 * @param offset offset for the hint
 * @param variableRewrite if variable name should be changed (?)
 * @param cancel cancel flag
 * @return
 */
static IntroduceFieldFix createConstant(TreePath resolved, CompilationInfo info, TreePath value, String guessedName, int numDuplicates, int offset, boolean variableRewrite, AtomicBoolean cancel) {
    CodeStyle cs = CodeStyle.getDefault(info.getFileObject());
    boolean isConstant = checkConstantExpression(info, value);
    TreePath constantTarget = isConstant ? findAcceptableConstantTarget(info, resolved) : null;
    if (!isConstant || constantTarget == null || cancel.get()) {
        return null;
    }
    TreePathHandle h = TreePathHandle.create(resolved, info);
    String varName;
    if (variableRewrite) {
        varName = guessedName;
    } else {
        String proposed = Utilities.toConstantName(guessedName);
        varName = Utilities.makeNameUnique(info, info.getTrees().getScope(constantTarget), proposed, cs.getStaticFieldNamePrefix(), cs.getStaticFieldNameSuffix());
    }
    ClassTree clazz = (ClassTree)constantTarget.getLeaf();
    Element el = info.getTrees().getElement(constantTarget);
    if (el == null || !(el.getKind().isClass() || el.getKind().isInterface())) {
        return null;
    }
    IntroduceConstantFix fix = new IntroduceConstantFix(h, info.getJavaSource(), varName, numDuplicates, offset, TreePathHandle.create(constantTarget, info));
    fix.setTargetIsInterface(clazz.getKind() == Tree.Kind.INTERFACE);
    return fix;
}
项目:NullAway    文件:NullAway.java   
/**
 * @param fieldSymbol the field
 * @param initTreePath TreePath to the initializer method / block
 * @param state visitor state
 * @return true if the field is always initialized (by some other initializer) before the
 *     initializer corresponding to initTreePath executes
 */
private boolean fieldInitializedByPreviousInitializer(
    Symbol fieldSymbol, TreePath initTreePath, VisitorState state) {
  TreePath enclosingClassPath = initTreePath.getParentPath();
  ClassTree enclosingClass = (ClassTree) enclosingClassPath.getLeaf();
  Multimap<Tree, Element> tree2Init = initTree2PrevFieldInit.get(enclosingClass);
  if (tree2Init == null) {
    tree2Init = computeTree2Init(enclosingClassPath, state);
    initTree2PrevFieldInit.put(ASTHelpers.getSymbol(enclosingClass), tree2Init);
  }
  return tree2Init.containsEntry(initTreePath.getLeaf(), fieldSymbol);
}
项目:openjdk-jdk10    文件:T6404194.java   
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1          2          3
            //      01234567890123456 7890 123456789012345
            return "@SuppressWarning(\"foo\") @Deprecated class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null, compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    ClassTree classTree = (ClassTree)toplevel.getTypeDecls().get(0);
    List<? extends Tree> annotations = classTree.getModifiers().getAnnotations();
    Tree tree1 = annotations.get(0);
    Tree tree2 = annotations.get(1);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree1);
    if (pos != 0)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree1);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getStartPosition(toplevel, tree2);
    if (pos != 24)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree2, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree2);
    if (pos != 35)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree2, pos));
}
项目:incubator-netbeans    文件:ApplicationManagedResourceTransactionInjectableInWeb.java   
public ClassTree generate() {

    ClassTree modifiedClazz = getClassTree();
    String body = "";

    FieldInfo em = getEntityManagerFieldInfo();
    if (!em.isExisting()){
        FieldInfo emf = getEntityManagerFactoryFieldInfo();
        if (!emf.isExisting()){
            modifiedClazz = getTreeMaker().insertClassMember(getClassTree(), getIndexForField(getClassTree()), createEntityManagerFactory(emf.getName()));
        }
        body += getEmInitCode(em, emf);
    }

    body += getMethodBody(em);

    ModifiersTree methodModifiers = getTreeMaker().Modifiers(
            getGenerationOptions().getModifiers(),
            Collections.<AnnotationTree>emptyList()
            );

    MethodTree newMethod = getTreeMaker().Method(
            methodModifiers,
            computeMethodName(),
            getTreeMaker().PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            getParameterList(),
            Collections.<ExpressionTree>emptyList(),
            "{ " + body + "}",
            null
            );

    return getTreeMaker().addClassMember(modifiedClazz, importFQNs(newMethod));
}
项目:incubator-netbeans    文件:InvertBooleanTest.java   
private void performFieldTest(final String newName) throws Exception {
    final InvertBooleanRefactoring[] r = new InvertBooleanRefactoring[1];
    FileObject testFile = src.getFileObject("test/Test.java");

    JavaSource.forFileObject(testFile).runUserActionTask(new Task<CompilationController>() {

        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(JavaSource.Phase.RESOLVED);
            CompilationUnitTree cut = parameter.getCompilationUnit();

            VariableTree var = (VariableTree) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(1);

            TreePath tp = TreePath.getPath(cut, var);
            r[0] = new InvertBooleanRefactoring(TreePathHandle.create(tp, parameter));
            r[0].setNewName(newName);
        }
    }, true);

    RefactoringSession rs = RefactoringSession.create("Session");
    Thread.sleep(1000);
    r[0].prepare(rs);
    rs.doRefactoring(true);

    IndexingManager.getDefault().refreshIndex(src.getURL(), null);
    SourceUtils.waitScanFinished();
    assertEquals(false, TaskCache.getDefault().isInError(src, true));
}
项目:incubator-netbeans    文件:IsOverriddenVisitor.java   
IsOverriddenVisitor(CompilationInfo info, AtomicBoolean cancel) {
    super(cancel);
    this.info = info;

    type2Declaration = new HashMap<ElementHandle<TypeElement>, List<ElementHandle<ExecutableElement>>>();
    declaration2Tree = new HashMap<ElementHandle<ExecutableElement>, MethodTree>();
    declaration2Class = new HashMap<ElementHandle<TypeElement>, ClassTree>();

    type2Handle = new HashMap<TypeElement, ElementHandle<TypeElement>>();
}
项目:incubator-netbeans    文件:TreeUtilitiesTest.java   
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));
}
项目:incubator-netbeans    文件:ImportAnalysis2Test.java   
public void testParameterizedType() throws Exception {
    clearWorkDir();
    beginTx();
    assertTrue(new File(getWorkDir(), "test").mkdirs());
    testFile = new File(getWorkDir(), "test/Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package test;\n" +
        "\n" +
        "public abstract class Test {\n" +
        "}\n"
        );
    String golden =
        "package test;\n" +
        "\n" +
        "import java.util.Map;\n" +
        "\n" +
        "public abstract class Test implements Map<String, String> {\n" +
        "\n" +
        "    Entry e;\n" +
        "}\n";

    ClasspathInfo cpInfo = ClasspathInfoAccessor.getINSTANCE().create (ClassPathSupport.createClassPath(System.getProperty("sun.boot.class.path")), ClassPath.EMPTY, ClassPath.EMPTY, ClassPath.EMPTY, ClassPath.EMPTY, ClassPathSupport.createClassPath(getSourcePath()), ClassPath.EMPTY, null, true, false, false, true, false, null);
    JavaSource src = JavaSource.create(cpInfo, FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree node = workingCopy.getCompilationUnit();
            ClassTree clazz = (ClassTree) node.getTypeDecls().get(0);
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "e", make.QualIdent("java.util.Map.Entry"), null);
            workingCopy.rewrite(clazz, make.addClassMember(make.addClassImplementsClause(clazz, make.Type("java.util.Map<String, String>")), vt));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:JpaControllerUtil.java   
public static ClassTree addVariable(ClassTree classTree, WorkingCopy wc, String name, TypeInfo type, int modifiers, Object initializer, AnnotationInfo[] annotations) {
    Tree typeTree = createType(wc, type);
    ModifiersTree modTree = createModifiers(wc, modifiers, annotations);
    TreeMaker make = wc.getTreeMaker();
    VariableTree tree = make.Variable(modTree, name, typeTree, make.Literal(initializer));
    return make.addClassMember(classTree, tree);
}
项目:incubator-netbeans    文件:SourceUtils.java   
/**
 * A convenience method for converting a <code>ClassTree</code> to the 
 * corresponding <code>TypeElement</code>, if any.
 */
static TypeElement classTree2TypeElement(CompilationController controller, ClassTree classTree) {
    assert controller != null;
    assert classTree != null;

    TreePath classTreePath = controller.getTrees().getPath(controller.getCompilationUnit(), classTree);
    return (TypeElement)controller.getTrees().getElement(classTreePath);
}
项目:incubator-netbeans    文件:GenerationUtilsTest.java   
public void testCreateAnnotation() throws Exception {
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "}");
    runModificationTask(testFO, new Task<WorkingCopy>() {
        public void run(WorkingCopy copy) throws Exception {
            GenerationUtils genUtils = GenerationUtils.newInstance(copy);
            ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0);
            AnnotationTree annotationTree = genUtils.createAnnotation("java.lang.SuppressWarnings",
                    Collections.singletonList(genUtils.createAnnotationArgument(null, "unchecked")));
            ClassTree newClassTree = genUtils.addAnnotation(classTree, annotationTree);
            annotationTree = genUtils.createAnnotation("java.lang.annotation.Retention",
                    Collections.singletonList(genUtils.createAnnotationArgument(null, "java.lang.annotation.RetentionPolicy", "RUNTIME")));
            newClassTree = genUtils.addAnnotation(newClassTree, annotationTree);
            copy.rewrite(classTree, newClassTree);
        }
    }).commit();
    runUserActionTask(testFO, new Task<CompilationController>() {
        public void run(CompilationController controller) throws Exception {
            TypeElement typeElement = SourceUtils.getPublicTopLevelElement(controller);
            assertEquals(2, typeElement.getAnnotationMirrors().size());
            SuppressWarnings suppressWarnings = typeElement.getAnnotation(SuppressWarnings.class);
            assertNotNull(suppressWarnings);
            assertEquals(1, suppressWarnings.value().length);
            assertEquals("unchecked", suppressWarnings.value()[0]);
            Retention retention = typeElement.getAnnotation(Retention.class);
            assertNotNull(retention);
            assertEquals(RetentionPolicy.RUNTIME, retention.value());
        }
    });
}
项目:openjdk-jdk10    文件:T6402077.java   
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2
            //      0123456789012345678901234
            return "class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null,
                                              compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    Tree tree = ((ClassTree)toplevel.getTypeDecls().get(0)).getMembers().get(0);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree);
    if (pos != 13)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree, pos));
}
项目:incubator-netbeans    文件:ArraysTest.java   
public void testCLike1() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    Integer a[] = null;\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    Float a = null;\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();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            VariableTree var = (VariableTree) clazz.getMembers().get(1);
            workingCopy.rewrite(var.getType(), make.Type("Float"));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:ElementScanningTask.java   
@Override
public Context visitClass(ClassTree node, Void p) {
    Element e = this.trees.getElement(this.getCurrentPath());
    if (e != null) {
        long pos = this.sourcePositions.getStartPosition(cu, node);
        ctx.pos.put(e, pos);
    }
    return super.visitClass(node, p);
}
项目:incubator-netbeans    文件:ScanLocalVars.java   
@Override
public Void visitClass(ClassTree node, Void p) {
    nesting++;
    super.visitClass(node, p);
    nesting--;
    return null;
}
项目:incubator-netbeans    文件:ClassImplementsTest.java   
public void testRenameInImpl() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "import java.util.*;\n\n" +
        "public class Test<E> extends Object implements List {\n" +
        "    public void taragui() {\n" +
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "import java.util.*;\n\n" +
        "public class Test<E> extends Object implements Seznam {\n" +
        "    public void taragui() {\n" +
        "    }\n" +
        "}\n";

    JavaSource src = getJavaSource(testFile);
    Task 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;
                IdentifierTree ident = (IdentifierTree) clazz.getImplementsClause().get(0);
                workingCopy.rewrite(ident, make.setLabel(ident, "Seznam"));
            }
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:Utilities.java   
public static Collection<? extends Element> getForwardReferences(TreePath path, int pos, SourcePositions sourcePositions, Trees trees) {
    HashSet<Element> refs = new HashSet<Element>();
    while(path != null) {
        switch(path.getLeaf().getKind()) {
            case BLOCK:
                if (path.getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION)
                    break;
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
                return refs;
            case VARIABLE:
                refs.add(trees.getElement(path));
                TreePath parent = path.getParentPath();
                if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getLeaf().getKind())) {
                    boolean isStatic = ((VariableTree)path.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC);
                    for(Tree member : ((ClassTree)parent.getLeaf()).getMembers()) {
                        if (member.getKind() == Tree.Kind.VARIABLE && sourcePositions.getStartPosition(path.getCompilationUnit(), member) >= pos &&
                                (isStatic || !((VariableTree)member).getModifiers().getFlags().contains(Modifier.STATIC)))
                            refs.add(trees.getElement(new TreePath(parent, member)));
                    }
                }
                return refs;
            case ENHANCED_FOR_LOOP:
                EnhancedForLoopTree efl = (EnhancedForLoopTree)path.getLeaf();
                if (sourcePositions.getEndPosition(path.getCompilationUnit(), efl.getExpression()) >= pos)
                    refs.add(trees.getElement(new TreePath(path, efl.getVariable())));                        
        }
        path = path.getParentPath();
    }
    return refs;
}
项目:incubator-netbeans    文件:JUnit4TestGenerator.java   
/**
 */
@Override
protected ClassTree finishSuiteClass(ClassTree tstClass,
                                     TreePath tstClassTreePath,
                                     List<Tree> tstMembers,
                                     List<String> suiteMembers,
                                     boolean membersChanged,
                                     ClassMap classMap,
                                     WorkingCopy workingCopy) {

    ModifiersTree currModifiers = tstClass.getModifiers();
    ModifiersTree modifiers = fixSuiteClassModifiers(tstClass,
                                                     tstClassTreePath,
                                                     currModifiers,
                                                     suiteMembers,
                                                     workingCopy);
    if (!membersChanged) {
        if (modifiers != currModifiers) {
            workingCopy.rewrite(currModifiers, modifiers);
        }
        return tstClass;
    }

    return workingCopy.getTreeMaker().Class(
            modifiers,
            tstClass.getSimpleName(),
            tstClass.getTypeParameters(),
            tstClass.getExtendsClause(),
            (List<? extends ExpressionTree>) tstClass.getImplementsClause(),
            tstMembers);
}
项目:NullAway    文件:RxNullabilityPropagator.java   
private void handleFilterAnonClass(
    StreamTypeRecord streamType,
    MethodInvocationTree observableDotFilter,
    ClassTree annonClassBody,
    VisitorState state) {
  for (Tree t : annonClassBody.getMembers()) {
    if (t instanceof MethodTree && ((MethodTree) t).getName().toString().equals("test")) {
      filterMethodOrLambdaSet.add(t);
      observableCallToInnerMethodOrLambda.put(observableDotFilter, (MethodTree) t);
      handleChainFromFilter(streamType, observableDotFilter, t, state);
    }
  }
}
项目:incubator-netbeans    文件:PullUpTest.java   
private void performPullUpIface(FileObject source, final int position, final int iface, final boolean makeAbstract, Problem... expectedProblems) throws IOException, IllegalArgumentException, InterruptedException {
    final PullUpRefactoring[] r = new PullUpRefactoring[1];
    JavaSource.forFileObject(source).runUserActionTask(new Task<CompilationController>() {
        @Override
        public void run(CompilationController info) throws Exception {
            info.toPhase(JavaSource.Phase.RESOLVED);
            CompilationUnitTree cut = info.getCompilationUnit();

            final ClassTree classTree = (ClassTree) cut.getTypeDecls().get(0);
            final TreePath classPath = info.getTrees().getPath(cut, classTree);
            TypeElement classEl = (TypeElement) info.getTrees().getElement(classPath);

            TypeMirror superclass = classEl.getInterfaces().get(iface);
            TypeElement superEl = (TypeElement) info.getTypes().asElement(superclass);

            MemberInfo[] members = new MemberInfo[1];
            Tree member = classTree.getMembers().get(position);
            Element el = info.getTrees().getElement(new TreePath(classPath, member));
            members[0] = MemberInfo.create(el, info);
            members[0].setMakeAbstract(makeAbstract);

            r[0] = new PullUpRefactoring(TreePathHandle.create(classEl, info));
            r[0].setTargetType(ElementHandle.create(superEl));
            r[0].setMembers(members);
        }
    }, true);

    RefactoringSession rs = RefactoringSession.create("Session");
    List<Problem> problems = new LinkedList<Problem>();

    addAllProblems(problems, r[0].preCheck());
    if (!problemIsFatal(problems)) {
        addAllProblems(problems, r[0].prepare(rs));
    }
    if (!problemIsFatal(problems)) {
        addAllProblems(problems, rs.doRefactoring(true));
    }

    assertProblems(Arrays.asList(expectedProblems), problems);
}
项目:incubator-netbeans    文件:ImportAnalysis2Test.java   
public void testType2() throws Exception {
    clearWorkDir();
    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" +
        "    int[] 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();
            CompilationUnitTree node = workingCopy.getCompilationUnit();
            ClassTree clazz = (ClassTree) node.getTypeDecls().get(0);
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "l", make.Type("int[]"), null);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, vt));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}