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

项目:incubator-netbeans    文件:JavaSourceHelper.java   
public static void addFields(WorkingCopy copy, String[] names, Object[] types, Object[] initialValues, Modifier[] modifiers) {

        TreeMaker maker = copy.getTreeMaker();
        ClassTree classTree = getTopLevelClassTree(copy);
        ClassTree modifiedTree = classTree;
        String[] annotations = new String[0];
        Object[] annotationAttrs = new Object[0];

        for (int i = 0; i < names.length; i++) {
            String name = names[i];
            Object type = types[i];
            Object initialValue = initialValues[i];
            // get around Retouche lack support for non-java.lang type Literal ???
            if (initialValue instanceof Enum) {
                continue;
            }

            Tree typeTree = createTypeTree(copy, type);

            ModifiersTree modifiersTree = createModifiersTree(copy, modifiers, annotations, annotationAttrs);
            ExpressionTree init = initialValue == null ? null : maker.Literal(initialValue);
            VariableTree variableTree = maker.Variable(modifiersTree, name, typeTree, init);
            modifiedTree = maker.insertClassMember(modifiedTree, 0, variableTree);
        }
        copy.rewrite(classTree, modifiedTree);
    }
项目:incubator-netbeans    文件:EqualsHashCodeGenerator.java   
private static MethodTree createHashCodeMethod(WorkingCopy wc, Iterable<? extends VariableElement> hashCodeFields, Scope scope) {
    TreeMaker make = wc.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);        

    int startNumber = generatePrimeNumber(2, 10);
    int multiplyNumber = generatePrimeNumber(10, 100);
    List<StatementTree> statements = new ArrayList<>();
    //int hash = <startNumber>;
    statements.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "hash", make.PrimitiveType(TypeKind.INT), make.Literal(startNumber))); //NOI18N        
    for (VariableElement ve : hashCodeFields) {
        TypeMirror tm = ve.asType();
        ExpressionTree variableRead = prepareExpression(wc, HASH_CODE_PATTERNS, tm, ve, scope);
        statements.add(make.ExpressionStatement(make.Assignment(make.Identifier("hash"), make.Binary(Tree.Kind.PLUS, make.Binary(Tree.Kind.MULTIPLY, make.Literal(multiplyNumber), make.Identifier("hash")), variableRead)))); //NOI18N
    }
    statements.add(make.Return(make.Identifier("hash"))); //NOI18N        
    BlockTree body = make.Block(statements, false);
    ModifiersTree modifiers = prepareModifiers(wc, mods,make);

    return make.Method(modifiers, "hashCode", make.PrimitiveType(TypeKind.INT), Collections.<TypeParameterTree> emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
/**
 * Creates a public static {@code main(String[])} method
 * with the body taken from settings.
 *
 * @param  maker  {@code TreeMaker} to use for creating the method
 * @return  created {@code main(...)} method,
 *          or {@code null} if the method body would be empty
 */
private MethodTree createMainMethod(TreeMaker maker) {
    String initialMainMethodBody = getInitialMainMethodBody();
    if (initialMainMethodBody.length() == 0) {
        return null;
    }

    ModifiersTree modifiers = maker.Modifiers(
            createModifierSet(Modifier.PUBLIC, Modifier.STATIC));
    VariableTree param = maker.Variable(
                    maker.Modifiers(Collections.<Modifier>emptySet()),
                    "argList",                                      //NOI18N
                    maker.Identifier("String[]"),                   //NOI18N
                    null);            //initializer - not used in params
    MethodTree mainMethod = maker.Method(
          modifiers,                            //public static
          "main",                               //method name "main"//NOI18N
          maker.PrimitiveType(TypeKind.VOID),   //return type "void"
          Collections.<TypeParameterTree>emptyList(),     //type params
          Collections.<VariableTree>singletonList(param), //method param
          Collections.<ExpressionTree>emptyList(),        //throws-list
          '{' + initialMainMethodBody + '}',    //body text
          null);                                //only for annotations

    return mainMethod;
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testPositionForEnumModifiers() throws IOException {
    final String theString = "public";
    String code = "package test; " + theString + " enum Test {A;}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ModifiersTree mt = clazz.getModifiers();
    int spos = code.indexOf(theString);
    int epos = spos + theString.length();
    assertEquals("testPositionForEnumModifiers",
            spos, pos.getStartPosition(cut, mt));
    assertEquals("testPositionForEnumModifiers",
            epos, pos.getEndPosition(cut, mt));
}
项目:incubator-netbeans    文件:ClassStructure.java   
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    GeneratorUtilities gu = GeneratorUtilities.get(wc);
    TreePath path = ctx.getPath();
    final ClassTree cls = (ClassTree) path.getLeaf();
    gu.importComments(cls, wc.getCompilationUnit());
    final TreeMaker treeMaker = wc.getTreeMaker();
    ModifiersTree mods = cls.getModifiers();
    if (mods.getFlags().contains(Modifier.ABSTRACT)) {
        Set<Modifier> modifiers = EnumSet.copyOf(mods.getFlags());
        modifiers.remove(Modifier.ABSTRACT);
        ModifiersTree nmods = treeMaker.Modifiers(modifiers, mods.getAnnotations());
        gu.copyComments(mods, nmods, true);
        gu.copyComments(mods, nmods, false);
        mods = nmods;
    }
    Tree nue = treeMaker.Interface(mods, cls.getSimpleName(), cls.getTypeParameters(), cls.getImplementsClause(), cls.getMembers());
    gu.copyComments(cls, nue, true);
    gu.copyComments(cls, nue, false);
    wc.rewrite(path.getLeaf(), nue);
}
项目:incubator-netbeans    文件:RemoveInvalidModifier.java   
private ModifiersTree getModifierTree(TreePath treePath) {
    Kind kind = treePath.getLeaf().getKind();
    switch (kind) {
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            return ((ClassTree) treePath.getLeaf()).getModifiers();
        case VARIABLE:
            return ((VariableTree) treePath.getLeaf()).getModifiers();
        case METHOD:
            return ((MethodTree) treePath.getLeaf()).getModifiers();
        default:
            throw new UnsupportedOperationException("kind " + kind + " not yet suppported");
    }
}
项目:incubator-netbeans    文件:GenerationUtils.java   
/**
 * Creates a new public property setter method.
 *
 * @param  modifiersTree the method modifiers; cannot be null.
 * @param  propertyType the property type; cannot be null.
 * @param  propertyName the property name; cannot be null.
 * @return the new method; never null.
 */
public MethodTree createPropertySetterMethod(ModifiersTree modifiersTree, String propertyName, Tree propertyType) {
    Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
    Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
    Parameters.notNull("propertyType", propertyType); // NOI18N

    TreeMaker make = getTreeMaker();
    return make.Method(
            modifiersTree,
            createPropertyAccessorName(propertyName, false),
            make.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.singletonList(createVariable(propertyName, propertyType)),
            Collections.<ExpressionTree>emptyList(),
            "{ this." + propertyName + " = " + propertyName + "; }", // NOI18N
            null);
}
项目:incubator-netbeans    文件:GenerationUtils.java   
/**
 * Creates a constructor which assigns its parameters to fields with the
 * same names. For example it can be used to generate:
 *
 * <pre>
 * public void Constructor(String field1, Object field2) {
 *     this.field1 = field1;
 *     this.field2 = field2;
 * }
 * </pre>
 *
 * @param  modifiersTree the constructor modifiers.
 * @param  constructorName the constructor name; cannot be null, it's not used inside except for assertion since 2007 (or before, TODO: remove?)
 * @param  parameters the constructor parameters; cannot be null.
 * @return the new constructor; never null.
 */
public MethodTree createAssignmentConstructor(ModifiersTree modifiersTree, String constructorName, List<VariableTree> parameters) {
    Parameters.notNull("modifiersTree", modifiersTree);
    Parameters.javaIdentifier("constructorName", constructorName); // NOI18N
    Parameters.notNull("parameters", parameters); // NOI18N

    StringBuilder body = new StringBuilder(parameters.size() * 30);
    body.append("{"); // NOI18N
    for (VariableTree parameter : parameters) {
        String parameterName = parameter.getName().toString();
        body.append("this." + parameterName + " = " + parameterName + ";"); // NOI18N
    }
    body.append("}"); // NOI18N

    TreeMaker make = getTreeMaker();
    return make.Constructor(
            modifiersTree,
            Collections.<TypeParameterTree>emptyList(),
            parameters,
            Collections.<ExpressionTree>emptyList(),
            body.toString());
}
项目:incubator-netbeans    文件:JUnit4TestGenerator.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    文件:ImplementAllAbstractMethods.java   
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    WorkingCopy wc = ctx.getWorkingCopy();
    Tree.Kind k = ctx.getPath().getLeaf().getKind();
    if (!TreeUtilities.CLASS_TREE_KINDS.contains(k)) {
        // TODO: report
        return;
    }
    ClassTree ct = (ClassTree)ctx.getPath().getLeaf();
    ModifiersTree mt = ct.getModifiers();
    Set<Modifier> mods = new HashSet<>(mt.getFlags());
    mods.remove(Modifier.FINAL);
    mods.add(Modifier.ABSTRACT);
    ModifiersTree newMt = wc.getTreeMaker().Modifiers(mods, mt.getAnnotations());
    wc.rewrite(mt, newMt);
}
项目:incubator-netbeans    文件:AddJavaFXPropertyMaker.java   
private MethodTree createGetter(ModifiersTree mods, TypeMirror valueType) {
    StringBuilder getterName = GeneratorUtils.getCapitalizedName(config.getName());
    getterName.insert(0, valueType.getKind() == TypeKind.BOOLEAN ? "is" : "get");
    ReturnTree returnTree = make.Return(make.MethodInvocation(Collections.EMPTY_LIST, make.MemberSelect(make.Identifier(config.getName()), hasGet ? "get" : "getValue"), Collections.EMPTY_LIST));
    BlockTree getterBody = make.Block(Collections.singletonList(returnTree), false);
    Tree valueTree;
    if (valueType.getKind() == TypeKind.DECLARED) {
        valueTree = make.QualIdent(((DeclaredType) valueType).asElement());
    } else if (valueType.getKind().isPrimitive()) {
        valueTree = make.PrimitiveType(valueType.getKind());
    } else {
        valueTree = make.Identifier(valueType.toString());
    }
    MethodTree getter = make.Method(mods, getterName, valueTree, Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST, getterBody, null);
    return getter;
}
项目:incubator-netbeans    文件:AddJavaFXPropertyMaker.java   
private MethodTree createSetter(ModifiersTree mods, TypeMirror valueType) {
    StringBuilder getterName = GeneratorUtils.getCapitalizedName(config.getName());
    getterName.insert(0, "set");
    Tree valueTree;
    if (valueType.getKind() == TypeKind.DECLARED) {
        valueTree = make.QualIdent(((DeclaredType) valueType).asElement());
    } else if (valueType.getKind().isPrimitive()) {
        valueTree = make.PrimitiveType(valueType.getKind());
    } else {
        valueTree = make.Identifier(valueType.toString());
    }
    StatementTree statement = make.ExpressionStatement(make.MethodInvocation(Collections.EMPTY_LIST, make.MemberSelect(make.Identifier(config.getName()), hasGet ? "set" : "setValue"), Collections.singletonList(make.Identifier("value"))));
    BlockTree getterBody = make.Block(Collections.singletonList(statement), false);
    VariableTree var = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "value", valueTree, null);
    MethodTree getter = make.Method(mods, getterName, make.PrimitiveType(TypeKind.VOID), Collections.EMPTY_LIST, Collections.singletonList(var), Collections.EMPTY_LIST, getterBody, null);
    return getter;
}
项目:incubator-netbeans    文件:LoggerNotStaticFinal.java   
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    VariableTree vt = (VariableTree) tp.getLeaf();
    ModifiersTree mt = vt.getModifiers();
    Set<Modifier> modifiers = EnumSet.noneOf(Modifier.class);

    modifiers.addAll(mt.getFlags());
    modifiers.add(Modifier.FINAL);
    modifiers.add(Modifier.STATIC);

    ModifiersTree newMod = wc.getTreeMaker().Modifiers(modifiers, mt.getAnnotations());

    wc.rewrite(mt, newMod);
}
项目:incubator-netbeans    文件:ApplicationManagedResourceTransactionInjectableInEJB.java   
public ClassTree generate() {

    ClassTree modifiedClazz = getClassTree();

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

    FieldInfo em = getEntityManagerFieldInfo();
    if (!em.isExisting()){
        modifiedClazz = createEntityManager(Initialization.INIT);
    }

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

    return getTreeMaker().addClassMember(modifiedClazz, importFQNs(newMethod));
}
项目:incubator-netbeans    文件:MakeClassPublic.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);
                TreeMaker make = workingCopy.getTreeMaker();

                Set<Modifier> flags = new HashSet<Modifier>(clazzTree.getModifiers().getFlags());
                flags.add(Modifier.PUBLIC);
                ModifiersTree newModifiers = make.Modifiers(flags, clazzTree.getModifiers().getAnnotations());
                workingCopy.rewrite(clazzTree.getModifiers(), newModifiers);
            }
        }
    };

    JavaSource javaSource = JavaSource.forFileObject(fileObject);

    try{
        javaSource.runModificationTask(task).commit();
    } catch (IOException e){
        JPAProblemFinder.LOG.log(Level.SEVERE, e.getMessage(), e);
    }
    return null;
}
项目:javaide    文件:JavaInputAstVisitor.java   
/**
 * Formats a union type declaration in a catch clause.
 */
private void visitUnionType(VariableTree declaration) {
    UnionTypeTree type = (UnionTypeTree) declaration.getType();
    builder.open(ZERO);
    sync(declaration);
    visitAndBreakModifiers(
            declaration.getModifiers(), Direction.HORIZONTAL, Optional.<BreakTag>absent());
    List<? extends Tree> union = type.getTypeAlternatives();
    boolean first = true;
    for (int i = 0; i < union.size() - 1; i++) {
        if (!first) {
            builder.breakOp(" ");
            token("|");
            builder.space();
        } else {
            first = false;
        }
        scan(union.get(i), null);
    }
    builder.breakOp(" ");
    token("|");
    builder.space();
    Tree last = union.get(union.size() - 1);
    declareOne(
            DeclarationKind.NONE,
            Direction.HORIZONTAL,
            Optional.<ModifiersTree>absent(),
            last,
            VarArgsOrNot.NO, // VarArgsOrNot.valueOf(declaration.isVarargs()),
            ImmutableList.<AnnotationTree>of(), // declaration.varargsAnnotations(),
            declaration.getName(),
            "",
            // declaration.extraDimensions(),
            "=",
            Optional.fromNullable(declaration.getInitializer()),
            Optional.<String>absent(),
            Optional.<ExpressionTree>absent(),
            Optional.<TypeWithDims>absent());
    builder.close();
}
项目:incubator-netbeans    文件:ApplicationManagedResourceTransactionInJ2SE.java   
public ClassTree generate() {


    String body = "";

    FieldInfo em = getEntityManagerFieldInfo();

    if (!em.isExisting()) {
        body += getEmInitCode(getEntityManagerFactoryFieldInfo());
    }

    body += getInvocationCode(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(getClassTree(), importFQNs(newMethod));
}
项目:incubator-netbeans    文件:Utilities.java   
public static @NonNull Collection<? extends TreePath> resolveFieldGroup(@NonNull CompilationInfo info, @NonNull TreePath variable) {
    Tree leaf = variable.getLeaf();

    if (leaf.getKind() != Kind.VARIABLE) {
        return Collections.singleton(variable);
    }

    TreePath parentPath = variable.getParentPath();
    Iterable<? extends Tree> children;

    switch (parentPath.getLeaf().getKind()) {
        case BLOCK: children = ((BlockTree) parentPath.getLeaf()).getStatements(); break;
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            children = ((ClassTree) parentPath.getLeaf()).getMembers(); break;
        case CASE:  children = ((CaseTree) parentPath.getLeaf()).getStatements(); break;
        default:    children = Collections.singleton(leaf); break;
    }

    List<TreePath> result = new LinkedList<TreePath>();
    ModifiersTree currentModifiers = ((VariableTree) leaf).getModifiers();

    for (Tree c : children) {
        if (c.getKind() != Kind.VARIABLE) continue;

        if (((VariableTree) c).getModifiers() == currentModifiers) {
            result.add(new TreePath(parentPath, c));
        }
    }

    return result;
}
项目:incubator-netbeans    文件:TreeDuplicator.java   
@Override
public Tree visitMethod(MethodTree tree, Void p) {
    MethodTree n = make.Method((ModifiersTree) tree.getModifiers(),
            tree.getName().toString(), (ExpressionTree) tree.getReturnType(),
            tree.getTypeParameters(), tree.getParameters(),
            tree.getThrows(), tree.getBody(),
            (ExpressionTree) tree.getDefaultValue());
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
项目:incubator-netbeans    文件:TreeDuplicator.java   
@Override
public Tree visitModifiers(ModifiersTree tree, Void p) {
    ModifiersTree n = make.Modifiers(tree.getFlags(), tree.getAnnotations());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
项目:incubator-netbeans    文件:WorkingCopy.java   
/**
 * Resolves all fields that belong to the same field group. 
 */
private static @NonNull List<? extends Tree> collectFieldGroup(@NonNull CompilationInfo info, 
        @NonNull TreePath parentPath, Tree leaf) {
    Iterable<? extends Tree> children;

    switch (parentPath.getLeaf().getKind()) {
        case BLOCK: children = ((BlockTree) parentPath.getLeaf()).getStatements(); break;
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            children = ((ClassTree) parentPath.getLeaf()).getMembers(); break;
        case CASE:  children = ((CaseTree) parentPath.getLeaf()).getStatements(); break;
        default:    children = Collections.singleton(leaf); break;
    }

    List<Tree> result = new LinkedList<>();
    ModifiersTree currentModifiers = ((VariableTree) leaf).getModifiers();

    for (Tree c : children) {
        if (c.getKind() != Kind.VARIABLE) continue;

        if (((VariableTree) c).getModifiers() == currentModifiers) {
            result.add(c);
        }
    }

    return result;
}
项目:incubator-netbeans    文件:JavaSourceHelper.java   
public static void addClassAnnotation(WorkingCopy copy, String[] annotations, Object[] annotationAttrs) {
    TreeMaker maker = copy.getTreeMaker();
    ClassTree tree = getTopLevelClassTree(copy);

    ModifiersTree modifiers = tree.getModifiers();

    for (int i = 0; i < annotations.length; i++) {
        List<ExpressionTree> attrTrees = null;
        Object attr = annotationAttrs[i];

        if (attr != null) {
            attrTrees = new ArrayList<ExpressionTree>();

            if (attr instanceof ExpressionTree) {
                attrTrees.add((ExpressionTree) attr);
            } else {
                attrTrees.add(maker.Literal(attr));
            }
        } else {
            attrTrees = Collections.<ExpressionTree>emptyList();
        }

        AnnotationTree newAnnotation = maker.Annotation(maker.Identifier(annotations[i]), attrTrees);

        if (modifiers != null) {
            modifiers = maker.addModifiersAnnotation(modifiers, newAnnotation);
        }
    }

    copy.rewrite(tree.getModifiers(), modifiers);
}
项目:incubator-netbeans    文件:ModifiersTest.java   
/**
 * Original:
 * 
 * public static void method() {
 * }
 * 
 * Result:
 * 
 * void method() {
 * }
 */
public void testMethodMods2() 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 static void method() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    void method() {\n" +
            "    }\n" +
            "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();

            // finally, find the correct body and rewrite it.
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ModifiersTree mods = method.getModifiers();
            workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>emptySet()));
        }

    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:ModifiersTest.java   
/**
 * Original:
 * 
 * Test() {
 * }
 * 
 * Result:
 * 
 * public Test() {
 * }
 */
public void testMethodMods3() 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" +
            "    Test() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    public Test() {\n" +
            "    }\n" +
            "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();

            // finally, find the correct body and rewrite it.
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(0);
            ModifiersTree mods = method.getModifiers();
            workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)));
        }

    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:RemoveOverride.java   
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    ModifiersTree mt = (ModifiersTree) ctx.getPath().getLeaf();

    for (AnnotationTree at : mt.getAnnotations()) {
        Element el = ctx.getWorkingCopy().getTrees().getElement(new TreePath(ctx.getPath(), at));

        if (el != null && el.getKind().isInterface() && ((TypeElement ) el).getQualifiedName().contentEquals("java.lang.Override")) {
            ctx.getWorkingCopy().rewrite(mt, ctx.getWorkingCopy().getTreeMaker().removeModifiersAnnotation(mt, at));
            return ;
        }
    }
}
项目:incubator-netbeans    文件:ModifiersTest.java   
/**
 * Original:
 * 
 * public static void method() {
 * }
 * 
 * Result:
 * 
 * static void method() {
 * }
 */
public void testMethodMods5() 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 static void method() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    static void method() {\n" +
            "    }\n" +
            "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();

            // finally, find the correct body and rewrite it.
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ModifiersTree mods = method.getModifiers();
            workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.STATIC)));
        }

    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:ModifiersTest.java   
/**
 * Original:
 * 
 * public Test() {
 * }
 * 
 * Result:
 * 
 * protected Test() {
 * }
 */
public void testMethodMods6() 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 Test() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    protected Test() {\n" +
            "    }\n" +
            "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();

            // finally, find the correct body and rewrite it.
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(0);
            ModifiersTree mods = method.getModifiers();
            workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.PROTECTED)));
        }

    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:ModifiersTest.java   
public void testChangeInterfaceModifier() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
            "package flaska;\n" +
            "\n" +
            "public interface Test {\n" +
            "}\n"
            );
    String golden =
            "package flaska;\n" +
            "\n" +
            "interface Test {\n" +
            "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            ModifiersTree mods = clazz.getModifiers();
            Set<Modifier> flags = new HashSet<Modifier>(mods.getFlags());
            flags.remove(Modifier.PUBLIC);
            ModifiersTree modified = make.Modifiers(flags);

            ClassTree copy = make.Interface(
                    modified,
                    clazz.getSimpleName(),
                    Collections.<TypeParameterTree>emptyList(),
                    Collections.<Tree>emptyList(),
                    clazz.getMembers()
            );
            workingCopy.rewrite(clazz, copy);
        }
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:ModifiersTest.java   
public void test124701() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
            "package flaska;\n" +
            "\n" +
            "public class Test {\n" +
            "    @SuppressWarnings(\"x\")\n" +
            "    private void alois() {\n" +
            "    }\n" +
            "    \n" +
            "}\n"
            );
    String golden =
            "package flaska;\n" +
            "\n" +
            "public class Test {\n" +
            "    @SuppressWarnings(\"x\")\n" +
            "    public void alois() {\n" +
            "    }\n" +
            "    \n" +
            "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ModifiersTree mods = method.getModifiers();
            ModifiersTree copy = make.Modifiers(EnumSet.of(Modifier.PUBLIC), mods.getAnnotations());
            workingCopy.rewrite(mods, copy);
        }
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:CreateDefaultConstructor.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);
                TreeMaker make = workingCopy.getTreeMaker();

                ModifiersTree modifiers = make.Modifiers(Collections.singleton(Modifier.PUBLIC));

                MethodTree constr = make.Constructor(
                        modifiers, 
                        Collections.<TypeParameterTree>emptyList(),
                        Collections.<VariableTree>emptyList(),
                        Collections.<ExpressionTree>emptyList(),
                        "{}"); //NOI18N

                ClassTree newClass = make.insertClassMember(clazzTree,
                        getPositionToInsert(clazzTree),
                        constr);

                workingCopy.rewrite(clazzTree, newClass);
            }
        }
    };

    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    文件:FmtCodeGeneration.java   
protected void doModification(ResultIterator resultIterator) throws Exception {
    WorkingCopy copy = WorkingCopy.get(resultIterator.getParserResult());
    copy.toPhase(Phase.RESOLVED);
    TreeMaker tm = copy.getTreeMaker();
    GeneratorUtilities gu = GeneratorUtilities.get(copy);
    CompilationUnitTree cut = copy.getCompilationUnit();
    ClassTree ct = (ClassTree) cut.getTypeDecls().get(0);
    VariableTree field = (VariableTree)ct.getMembers().get(1);
    List<Tree> members = new ArrayList<Tree>();
    AssignmentTree stat = tm.Assignment(tm.Identifier("name"), tm.Literal("Name")); //NOI18N
    BlockTree init = tm.Block(Collections.singletonList(tm.ExpressionStatement(stat)), false);
    members.add(init);
    members.add(gu.createConstructor(ct, Collections.<VariableTree>emptyList()));
    members.add(gu.createGetter(field));
    ModifiersTree mods = tm.Modifiers(EnumSet.of(Modifier.PRIVATE));
    ClassTree inner = tm.Class(mods, "Inner", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList()); //NOI18N
    members.add(inner);
    mods = tm.Modifiers(EnumSet.of(Modifier.PRIVATE, Modifier.STATIC));
    ClassTree nested = tm.Class(mods, "Nested", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList()); //NOI18N
    members.add(nested);
    IdentifierTree nestedId = tm.Identifier("Nested"); //NOI18N
    VariableTree staticField = tm.Variable(mods, "instance", nestedId, null); //NOI18N
    members.add(staticField);
    NewClassTree nct = tm.NewClass(null, Collections.<ExpressionTree>emptyList(), nestedId, Collections.<ExpressionTree>emptyList(), null);
    stat = tm.Assignment(tm.Identifier("instance"), nct); //NOI18N
    BlockTree staticInit = tm.Block(Collections.singletonList(tm.ExpressionStatement(stat)), true);
    members.add(staticInit);
    members.add(gu.createGetter(staticField));
    ClassTree newCT = gu.insertClassMembers(ct, members);
    copy.rewrite(ct, newCT);
}
项目:incubator-netbeans    文件:MultipleRewritesTest.java   
public void testRewriteRewrittenTree() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    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" +
            "    @Deprecated\n" +
            "    public void taragui() {\n" +
            "    }\n" +
            "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();

            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            ModifiersTree mods = make.Modifiers(EnumSet.of(Modifier.PUBLIC));
            MethodTree method = make.Method(mods, "taragui", make.Type(workingCopy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}", null);

            workingCopy.rewrite(clazz, make.addClassMember(clazz, method));

            ModifiersTree nueMods = make.Modifiers(EnumSet.of(Modifier.PUBLIC), Collections.singletonList(make.Annotation(make.QualIdent(workingCopy.getElements().getTypeElement("java.lang.Deprecated")), Collections.<ExpressionTree>emptyList())));

            workingCopy.rewrite(mods, nueMods);
        }

    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:Field6Test.java   
public void testAddFieldToIndex0() 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() {\n" +
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "import java.io.*;\n\n" +
        "public class Test {\n" +
        "\n" +
        "    int field1;\n" +
        "    public void taragui() {\n" +
        "    }\n" +
        "}\n";

    process(
        new Transformer<Void, Object>() {

            public Void visitClass(ClassTree node, Object p) {
                super.visitClass(node, p);
                ModifiersTree mods = make.Modifiers(Collections.<Modifier>emptySet());
                PrimitiveTypeTree type = make.PrimitiveType(TypeKind.INT);
                VariableTree var = make.Variable(mods, "field1", type, null);
                ClassTree copy = make.insertClassMember(node, 0, var);
                this.copy.rewrite(node, copy);
                return null;
            }
        }
    );
    String res = TestUtilities.copyFileToString(testFile);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:JUnit4TestGenerator.java   
/**
 * Generates a set-up or a tear-down method.
 * The generated method will have no arguments, void return type
 * and a declaration that it may throw {@code java.lang.Exception}.
 * The method will have a declared protected member access.
 * The method contains call of the corresponding super method, i.e.
 * {@code super.setUp()} or {@code super.tearDown()}.
 *
 * @param  methodName  name of the method to be created
 * @return  created method
 * @see  http://junit.sourceforge.net/javadoc/junit/framework/TestCase.html
 *       methods {@code setUp()} and {@code tearDown()}
 */
private MethodTree generateInitMethod(String methodName,
                                      String annotationClassName,
                                      boolean isStatic,
                                      WorkingCopy workingCopy) {
    Set<Modifier> methodModifiers
            = isStatic ? createModifierSet(PUBLIC, STATIC)
                       : Collections.<Modifier>singleton(PUBLIC);
    ModifiersTree modifiers = createModifiersTree(annotationClassName,
                                                  methodModifiers,
                                                  workingCopy);
    TreeMaker maker = workingCopy.getTreeMaker();
    BlockTree methodBody = maker.Block(
            Collections.<StatementTree>emptyList(),
            false);
    MethodTree method = maker.Method(
            modifiers,              // modifiers
            methodName,             // name
            maker.PrimitiveType(TypeKind.VOID),         // return type
            Collections.<TypeParameterTree>emptyList(), // type params
            Collections.<VariableTree>emptyList(),      // parameters
            Collections.<ExpressionTree>singletonList(
                    maker.Identifier("Exception")),     // throws...//NOI18N
            methodBody,
            null);                                      // default value
    return method;
}
项目: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);
}
项目:incubator-netbeans    文件:JUnit3TestGenerator.java   
/**
 * Generates a set-up or a tear-down method.
 * The generated method will have no arguments, void return type
 * and a declaration that it may throw {@code java.lang.Exception}.
 * The method will have a declared protected member access.
 * The method contains call of the corresponding super method, i.e.
 * {@code super.setUp()} or {@code super.tearDown()}.
 *
 * @param  methodName  name of the method to be created
 * @return  created method
 * @see  http://junit.sourceforge.net/javadoc/junit/framework/TestCase.html
 *       methods {@code setUp()} and {@code tearDown()}
 */
protected MethodTree generateInitMethod(String methodName,
                                        TreeMaker maker,
                                        WorkingCopy workingCopy) {
    Set<Modifier> modifiers = Collections.<Modifier>singleton(PROTECTED);
    ModifiersTree modifiersTree
            = useAnnotations
              ? createModifiersTree(OVERRIDE, modifiers, workingCopy)
              : maker.Modifiers(modifiers);
    ExpressionTree superMethodCall = maker.MethodInvocation(
            Collections.<ExpressionTree>emptyList(),    // type params.
            maker.MemberSelect(
                    maker.Identifier("super"), methodName),         //NOI18N
            Collections.<ExpressionTree>emptyList());
    BlockTree methodBody = maker.Block(
            Collections.<StatementTree>singletonList(
                    maker.ExpressionStatement(superMethodCall)),
            false);
    MethodTree method = maker.Method(
            modifiersTree,          // modifiers
            methodName,             // name
            maker.PrimitiveType(TypeKind.VOID),         // return type
            Collections.<TypeParameterTree>emptyList(), // type params
            Collections.<VariableTree>emptyList(),      // parameters
            Collections.<ExpressionTree>singletonList(
                    maker.Identifier("Exception")),     // throws...//NOI18N
            methodBody,
            null);                                      // default value
    return method;
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
/**
 */
protected ModifiersTree createModifiersTree(String annotationClassName,
                                            Set<Modifier> modifiers,
                                            WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    AnnotationTree annotation = maker.Annotation(
            getClassIdentifierTree(annotationClassName, workingCopy),
            Collections.<ExpressionTree>emptyList());
    return maker.Modifiers(modifiers,
                           Collections.<AnnotationTree>singletonList(
                                                               annotation));
}
项目:javaide    文件:JavaInputAstVisitor.java   
/**
 * Output combined modifiers and annotations and returns the trailing break.
 */
private List<Op> visitModifiers(
        ModifiersTree modifiersTree,
        Direction annotationsDirection,
        Optional<BreakTag> declarationAnnotationBreak) {
    return visitModifiers(
            modifiersTree.getAnnotations(),
            annotationsDirection,
            declarationAnnotationBreak);
}
项目:incubator-netbeans    文件:ControllerGenerator.java   
private AnnotationTree findFxmlAnnotation(ModifiersTree modTree) {
    for (AnnotationTree annTree : modTree.getAnnotations()) {
        TreePath tp = new TreePath(new TreePath(wcopy.getCompilationUnit()), annTree.getAnnotationType());
        Element  e  = wcopy.getTrees().getElement(tp);
        if (fxmlAnnotationType.equals(e)) {
            return annTree;
        }
    }
    return null;
}
项目:incubator-netbeans    文件:AddJavaFXPropertyMaker.java   
private MethodTree createProperty(ModifiersTree mods, DeclaredType selectedType, ExecutableElement wrapperMethod) {
    String getterName = config.getName() + "Property";
    ExpressionTree expression;
    if (wrapperMethod == null) {
        expression = make.Identifier(config.getName());
    } else {
        expression = make.MethodInvocation(Collections.EMPTY_LIST, make.MemberSelect(make.Identifier(config.getName()), wrapperMethod.getSimpleName()), Collections.EMPTY_LIST);
    }
    ReturnTree returnTree = make.Return(expression);
    BlockTree getterBody = make.Block(Collections.singletonList(returnTree), false);
    MethodTree getter = make.Method(mods, getterName, selectedType == null ? make.Identifier(config.getPropertyType()) : make.QualIdent(selectedType.asElement()), Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST, getterBody, null);
    return getter;
}