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

项目:incubator-netbeans    文件:MethodMetrics.java   
@Hint(
     category = "metrics",
     displayName = "#DN_MethodTooDeepNesting",
     description = "#DESC_MethodTooDeepNesting",
     options = { Hint.Options.QUERY, Hint.Options.HEAVY },
     enabled = false
)
@TriggerTreeKind(Tree.Kind.METHOD)
@UseOptions(value = { OPTION_NESTING_LIMIT })
public static ErrorDescription tooDeepNesting(HintContext ctx) {
    Tree t = ctx.getPath().getLeaf();
    MethodTree method = (MethodTree)t;
    DepthVisitor v = new DepthVisitor();
    v.scan(ctx.getPath(), null);

    int depth = v.getDepth();
    int treshold = ctx.getPreferences().getInt(OPTION_NESTING_LIMIT, DEFAULT_NESTING_LIMIT);
    if (depth <= treshold) {
        return null;
    }
    return ErrorDescriptionFactory.forName(ctx, t, 
            methodOrConstructor(ctx) ?
            TEXT_ConstructorTooDeepNesting(depth) :
            TEXT_MethodTooDeepNesting(method.getName().toString(), depth)
    );
}
项目:incubator-netbeans    文件:EntityManagerGenerationStrategySupport.java   
private String makeUnique(String methodName){
    List <? extends Tree> members=getClassTree().getMembers();
    String name=methodName;
    int add=1;
    boolean found=false;
    do
    {
        found=false;
        for(Tree membr:members) {
            if(Tree.Kind.METHOD.equals(membr.getKind())){
                MethodTree mt = membr instanceof MethodTree ? (MethodTree) membr : null;
                if(mt!=null && name.equals(mt.getName().toString())) {
                    found = true;
                    name = methodName + add++;
                }
            }
        }
    }while(found);
    return name;
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testStartPositionForMethodWithoutModifiers() throws IOException {

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

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, 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));
}
项目:incubator-netbeans    文件:MethodMetrics.java   
@Hint(
    category = "metrics",
    displayName = "#DN_MethodMultipleLoops",
    description = "#DESC_MethodMultipleLoops",
    options = { Hint.Options.QUERY, Hint.Options.HEAVY },
    enabled = false
)
@TriggerTreeKind(Tree.Kind.METHOD)
@UseOptions({ OPTION_LOOPS_LIMIT })
public static ErrorDescription multipleLoops(HintContext ctx) {
    Tree t = ctx.getPath().getLeaf();
    MethodTree method = (MethodTree)t;

    LoopFinder v = new LoopFinder();
    v.scan(ctx.getPath(), null);
    int count = v.getLoopCount();
    int limit = ctx.getPreferences().getInt(OPTION_LOOPS_LIMIT, DEFAULT_LOOPS_LIMIT);
    if (count > limit) {
        return ErrorDescriptionFactory.forName(ctx, t, 
                TEXT_MethodMultipleLoops(method.getName().toString(), count)
        );
    } else {
        return null;
    }
}
项目:incubator-netbeans    文件:JpaControllerUtil.java   
private static MethodTree createMethod(WorkingCopy wc, MethodInfo mInfo) {
    TreeMaker make = wc.getTreeMaker();
    TypeInfo[] pTypes = mInfo.getParameterTypes();
    String[] pNames = mInfo.getParameterNames();
    List<VariableTree> params = new ArrayList<VariableTree>();
    for (int i = 0 ; pTypes != null && i < pTypes.length; i++) {
        VariableTree vtree = createVariable(wc, pNames[i], pTypes[i]);
        params.add(vtree);
    }

    TypeInfo[] excepTypes = mInfo.getExceptionTypes();
    List<ExpressionTree> throwsList = new ArrayList<ExpressionTree>();
    for (int i = 0 ; excepTypes != null && i < excepTypes.length; i++) {
        throwsList.add((ExpressionTree)createType(wc, excepTypes[i]));
    }

    String body = mInfo.getMethodBodyText();
    if(body == null) {
        body = "";
    }

    MethodTree mtree = make.Method(createModifiers(wc, mInfo.getModifiers(), mInfo.getAnnotations()),
            mInfo.getName(),
            createType(wc, mInfo.getReturnType()),
            Collections.<TypeParameterTree>emptyList(),
            params,
            throwsList,
            "{" + body + "}",
            null
            );

    //         if(mInfo.getCommentText() != null) {
    //             Comment comment = Comment.create(Comment.Style.JAVADOC, -2,
    //                     -2, -2, mInfo.getCommentText());
    //             make.addComment(mtree, comment, true);
    //         }

    return mtree;
}
项目:incubator-netbeans    文件:EntityMethodGenerator.java   
public  MethodTree createEqualsMethod(String simpleClassName, List<VariableTree> fields) {
    StringBuilder body = new StringBuilder(50 + fields.size() * 30);
    body.append("{"); // NOI18N
    body.append("// TODO: Warning - this method won't work in the case the id fields are not set\n"); // NOI18N
    body.append("if (!(object instanceof "); // NOI18N
    body.append(simpleClassName + ")) {return false;}"); // NOI18N
    body.append(simpleClassName + " other = (" + simpleClassName + ")object;"); // NOI18N
    for (VariableTree field : fields) {
        body.append(createEqualsLineForField(field));
    }
    body.append("return true;"); // NOI18N
    body.append("}"); // NOI18N
    TreeMaker make = copy.getTreeMaker();
    // XXX Javadoc
    return make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC),
            Collections.singletonList(genUtils.createAnnotation("java.lang.Override"))), "equals",
            make.PrimitiveType(TypeKind.BOOLEAN), Collections.<TypeParameterTree>emptyList(),
            Collections.singletonList(genUtils.createVariable(scope, "object", "java.lang.Object")),
            Collections.<ExpressionTree>emptyList(), body.toString(), null);
}
项目:incubator-netbeans    文件:EntityMethodGenerator.java   
public MethodTree createToStringMethod(String fqn, List<VariableTree> fields) {
    StringBuilder body = new StringBuilder(30 + fields.size() * 30);
    body.append("{"); // NOI18N
    body.append("return \"" + fqn + "[ "); // NOI18N
    for (Iterator<VariableTree> i = fields.iterator(); i.hasNext();) {
        String fieldName = i.next().getName().toString();
        body.append(fieldName + "=\" + " + fieldName + " + \""); //NOI18N
        body.append(i.hasNext() ? ", " : " ]\";"); //NOI18N
    }
    body.append("}"); // NOI18N
    TreeMaker make = copy.getTreeMaker();
    // XXX Javadoc
    return make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC),
            Collections.singletonList(genUtils.createAnnotation("java.lang.Override"))), "toString",
            genUtils.createType("java.lang.String", scope), Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body.toString(), null);
}
项目:NullAway    文件:RxNullabilityPropagator.java   
@Override
public void onMatchReturn(NullAway analysis, ReturnTree tree, VisitorState state) {
  // Figure out the enclosing method node
  TreePath enclosingMethodOrLambda =
      NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(state.getPath());
  if (enclosingMethodOrLambda == null) {
    throw new RuntimeException("no enclosing method, lambda or initializer!");
  }
  if (!(enclosingMethodOrLambda.getLeaf() instanceof MethodTree
      || enclosingMethodOrLambda.getLeaf() instanceof LambdaExpressionTree)) {
    throw new RuntimeException(
        "return statement outside of a method or lambda! (e.g. in an initializer block)");
  }
  Tree leaf = enclosingMethodOrLambda.getLeaf();
  if (filterMethodOrLambdaSet.contains(leaf)) {
    returnToEnclosingMethodOrLambda.put(tree, leaf);
    // We need to manually trigger the dataflow analysis to run on the filter method,
    // this ensures onDataflowVisitReturn(...) gets called for all return statements in this
    // method before
    // onDataflowInitialStore(...) is called for all successor methods in the observable chain.
    // Caching should prevent us from re-analyzing any given method.
    AccessPathNullnessAnalysis nullnessAnalysis = analysis.getNullnessAnalysis(state);
    nullnessAnalysis.forceRunOnMethod(new TreePath(state.getPath(), leaf), state.context);
  }
}
项目:incubator-netbeans    文件:ControllerGenerator.java   
private void indexController() {
    for (Tree member : controllerClass.getMembers()) {
        switch (member.getKind()) {
            case VARIABLE: {
                VariableTree vt = (VariableTree)member;
                fields.put(vt.getName().toString(), vt);
                break;
            }
            case METHOD: {
                MethodTree mt = (MethodTree)member;
                addMethod(mt);
                break;
            }
        }
    }
}
项目:incubator-netbeans    文件:JUnit3TestGenerator.java   
/**
 */
protected MethodTree composeNewTestMethod(String testMethodName,
                                          BlockTree testMethodBody,
                                          List<ExpressionTree> throwsList,
                                          WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    return maker.Method(
            maker.Modifiers(createModifierSet(PUBLIC)),
            testMethodName,
            maker.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(),
            throwsList,
            testMethodBody,
            null);          //default value - used by annotations
}
项目: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;
}
项目:incubator-netbeans    文件:TestGenerator.java   
/**
 */
private void addInitMethod(String methodName,
                           String annotationClassName,
                           boolean isStatic,
                           int targetIndex,
                           List<Tree> clsMembers,
                           ClassMap clsMap,
                           WorkingCopy workingCopy) {
    MethodTree initMethod = generateInitMethod(methodName,
                                               annotationClassName,
                                               isStatic,
                                               workingCopy);

    if (targetIndex == -1) {
        targetIndex = getPlaceForFirstInitMethod(clsMap);
    }

    if (targetIndex != -1) {
        clsMembers.add(targetIndex, initMethod);
    } else {
        clsMembers.add(initMethod);
    }
    clsMap.addNoArgMethod(methodName, annotationClassName, targetIndex);
}
项目:incubator-netbeans    文件:ChangeMethodReturnType.java   
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    TypeMirror targetType = targetTypeHandle.resolve(wc);

    if (targetType == null) {
        //XXX: log
        return ;
    }

    MethodTree mt = (MethodTree) tp.getLeaf();
    TreeMaker make = wc.getTreeMaker();

    wc.rewrite(mt.getReturnType(), make.Type(targetType));
}
项目: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(TypeElement clazz, VariableElement field) {
    assert clazz != null && field != null;
    TreeMaker make = copy.getTreeMaker();
    CodeStyle cs = DiffContext.getCodeStyle(copy);
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    boolean isStatic = field.getModifiers().contains(Modifier.STATIC);
    if (isStatic) {
        mods.add(Modifier.STATIC);
    }
    CharSequence name = field.getSimpleName();
    assert name.length() > 0;
    TypeMirror type = copy.getTypes().asMemberOf((DeclaredType)clazz.asType(), field);
    String setterName = CodeStyleUtils.computeSetterName(field.getSimpleName(), isStatic, cs);
    String paramName = addParamPrefixSuffix(removeFieldPrefixSuffix(field, cs), cs);
    List<VariableTree> params = Collections.singletonList(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), paramName, make.Type(type), null));
    BlockTree body = make.Block(Collections.singletonList(make.ExpressionStatement(make.Assignment(make.MemberSelect(isStatic? make.Identifier(field.getEnclosingElement().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 testCreateProperty() throws Exception {
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "   private Object x;" +
            "   public 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);
            TypeElement scope = SourceUtils.classTree2TypeElement(copy, classTree);
            VariableTree field = genUtils.createField(scope, genUtils.createModifiers(Modifier.PRIVATE), "someProp", "java.lang.String", null);
            MethodTree getter = genUtils.createPropertyGetterMethod(scope, genUtils.createModifiers(Modifier.PUBLIC), "someProp", "java.lang.String");
            MethodTree setter = genUtils.createPropertySetterMethod(scope, genUtils.createModifiers(Modifier.PUBLIC), "someProp", "java.lang.String");
            TreeMaker make = copy.getTreeMaker();
            ClassTree newClassTree = classTree;
            newClassTree = make.insertClassMember(newClassTree, 0, field);
            newClassTree = make.addClassMember(newClassTree, getter);
            newClassTree = make.addClassMember(newClassTree, setter);
            copy.rewrite(classTree, newClassTree);
        }
    }).commit();
    // TODO check the field and methods
}
项目:incubator-netbeans    文件:FindUsagesTest.java   
public void test202412() throws IOException, InterruptedException, ExecutionException { // #202412 NullPointerException at org.netbeans.modules.refactoring.java.RefactoringUtils.getFileObject
    FileObject testFile = projectDir.getFileObject("/src/simplej2seapp/I.java");
    JavaSource src = JavaSource.forFileObject(testFile);
    final WhereUsedQuery[] wuq = new WhereUsedQuery[1];
    src.runWhenScanFinished(new Task<CompilationController>() {

        @Override
        public void run(CompilationController controller) throws Exception {
            controller.toPhase(JavaSource.Phase.RESOLVED);
            ClassTree klass = (ClassTree) controller.getCompilationUnit().getTypeDecls().get(0);
            MethodTree runTree = (MethodTree) klass.getMembers().get(0);
            TreePath path = controller.getTrees().getPath(controller.getCompilationUnit(), runTree);
            TreePathHandle element = TreePathHandle.create(path, controller);
            wuq[0] = new WhereUsedQuery(Lookups.singleton(element));
        }
    }, false).get();
    setParameters(wuq, true, false, false, false, false, false);

    doRefactoring("test202412", wuq, 1);
}
项目:incubator-netbeans    文件:JavaSourceHelper.java   
public static ClassTree addConstructor(WorkingCopy copy, ClassTree tree, Modifier[] modifiers, String[] parameters, Object[] paramTypes, String bodyText, String comment) {
    TreeMaker maker = copy.getTreeMaker();
    ModifiersTree modifiersTree = createModifiersTree(copy, modifiers, null, null);
    ModifiersTree paramModTree = maker.Modifiers(Collections.<Modifier>emptySet());
    List<VariableTree> paramTrees = new ArrayList<VariableTree>();

    if (parameters != null) {
        for (int i = 0; i < parameters.length; i++) {
            paramTrees.add(maker.Variable(paramModTree, parameters[i], createTypeTree(copy, paramTypes[i]), null));
        }
    }

    MethodTree methodTree = maker.Constructor(modifiersTree, Collections.<TypeParameterTree>emptyList(), paramTrees, Collections.<ExpressionTree>emptyList(), bodyText);

    if (comment != null) {
        maker.addComment(methodTree, createJavaDocComment(comment), true);
    }

    return maker.addClassMember(tree, methodTree);
}
项目: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    文件:RenameConstructor.java   
@Override
public ChangeInfo implement() throws Exception {
    try {
        ModificationResult.runModificationTask(Collections.singleton(source), new UserTask() {
            @Override
            public void run(ResultIterator resultIterator) throws Exception {
                WorkingCopy wc = WorkingCopy.get(resultIterator.getParserResult(offset));
                wc.toPhase(Phase.PARSED);
                TreePath path = pathHandle.resolve(wc);
                if (path != null && path.getLeaf().getKind() == Kind.METHOD) {
                    MethodTree mt = (MethodTree) path.getLeaf();
                    wc.rewrite(mt, wc.getTreeMaker().setLabel(mt, newConstructorName));
                }
            }
        }).commit();
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
    return null;
}
项目:affinechecker    文件:AffinePointerTransfer.java   
private Element elementOf(Node n) {
    Tree t = n.getTree();
    if (t instanceof ExpressionTree) {
        return TreeUtils.elementFromUse((ExpressionTree)t);
    } else if (t instanceof MethodInvocationTree) {
        return TreeUtils.elementFromUse((MethodInvocationTree)t);
    } else if (t instanceof NewClassTree) {
        return TreeUtils.elementFromUse((NewClassTree)t);
    } else if (t instanceof VariableTree) {
        return TreeUtils.elementFromDeclaration((VariableTree)t);
    } else if (t instanceof MethodTree) {
        return TreeUtils.elementFromDeclaration((MethodTree)t);
    } else if (t instanceof ClassTree) {
        return TreeUtils.elementFromDeclaration((ClassTree)t);
    } else {
        throw new RuntimeException("Unsupported tree type " + t.getClass());
    }
}
项目:incubator-netbeans    文件:MethodTest2.java   
public Void visitMethod(MethodTree node, Object p) {
    super.visitMethod(node, p);
    if (method.equals(node)) {
        MethodTree njuMethod = make.Method(
                node.getModifiers(),
                node.getName().toString(),
                (ExpressionTree) node.getReturnType(),
                node.getTypeParameters(),
                node.getParameters(),
                node.getThrows(),
                newType,
                (ExpressionTree) node.getDefaultValue()
                );
        method = njuMethod;
        copy.rewrite(node, njuMethod);
    }
    return null;
}
项目:incubator-netbeans    文件:MethodTest2.java   
public Void visitMethod(MethodTree node, Object p) {
    super.visitMethod(node, p);
    if (method.equals(node)) {
        MethodTree njuMethod = make.Method(
                node.getModifiers(),
                newName,
                (ExpressionTree) node.getReturnType(),
                node.getTypeParameters(),
                node.getParameters(),
                node.getThrows(),
                node.getBody(),
                (ExpressionTree) node.getDefaultValue()
                );
        copy.rewrite(node, njuMethod);
        method = njuMethod;
    }
    return null;
}
项目:incubator-netbeans    文件:GenerationUtils.java   
/**
 * Creates a new public property getter 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 createPropertyGetterMethod(ModifiersTree modifiersTree, String propertyName, Tree propertyType) {
    Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
    Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
    Parameters.notNull("propertyType", propertyType); // NOI18N

    return getTreeMaker().Method(
            modifiersTree,
            createPropertyAccessorName(propertyName, true),
            propertyType,
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(),
            Collections.<ExpressionTree>emptyList(),
            "{ return " + propertyName + "; }", // NOI18N
            null);
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@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);
}
项目:incubator-netbeans    文件:WrappingTest.java   
public void testWrapAssignment() 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(AtomicBoolean ab) {\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);
            AssignmentTree bt = make.Assignment(make.Identifier("ab"), init.getExpression());
            workingCopy.rewrite(init, make.ExpressionStatement(bt));
        }
    }, FmtOptions.wrapAssignOps, WrapStyle.WRAP_IF_LONG.name());
}
项目: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    文件:CommanAndWhitespaceTest.java   
public void testNewClassToFactory() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui() {\n" +
        "        tests(Integer.MAX_VALUE, new Integer(1));\n" +
        "    }" +
        "    private void test(Integer i1, Integer i2) {}\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui() {\n" +
        "        tests(Integer.MAX_VALUE, Integer.valueOf(1));\n" +
        "    }" +
        "    private void test(Integer i1, Integer i2) {}\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);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            MethodInvocationTree mit = (MethodInvocationTree) ((ExpressionStatementTree) method.getBody().getStatements().get(0)).getExpression();
            MethodInvocationTree valueOf = make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.MemberSelect(make.Identifier("Integer"), "valueOf"), Collections.singletonList(make.Literal(1)));
            workingCopy.rewrite(mit.getArguments().get(1), valueOf);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目: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    文件:AbstractTestGenerator.java   
/**
 * Generates test methods for the given source methods.
 * The created test methods will be put to a newly created test class.
 * The test class does not exist at the moment this method is called.
 * 
 * @param  srcClass  source class containing the source methods
 * @param  instanceClsName  name of a class whose instance should be created
 *                          if appropriate
 * @param  srcMethods  source methods the test methods should be created for
 */
private List<MethodTree> generateTestMethods(
                                   TypeElement srcClass,
                                   CharSequence instanceClsName,
                                   List<ExecutableElement> srcMethods,
                                   WorkingCopy workingCopy) {
    if (srcMethods.isEmpty()) {
        return Collections.<MethodTree>emptyList();
    }

    List<String> testMethodNames
            = TestMethodNameGenerator.getTestMethodNames(srcMethods,
                                                         null,
                                                         null,   //reserved
                                                         workingCopy);

    Iterator<ExecutableElement> srcMethodsIt = srcMethods.iterator();
    Iterator<String> tstMethodNamesIt = testMethodNames.iterator();

    List<MethodTree> testMethods = new ArrayList<MethodTree>(srcMethods.size());
    while (srcMethodsIt.hasNext()) {
        assert tstMethodNamesIt.hasNext();

        ExecutableElement srcMethod = srcMethodsIt.next();
        String testMethodName = tstMethodNamesIt.next();

        testMethods.add(
                generateTestMethod(srcClass,
                                   srcMethod,
                                   testMethodName,
                                   instanceClsName,
                                   workingCopy));
    }
    assert !tstMethodNamesIt.hasNext();
    return testMethods;
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
/**
     * Generates a test methods for the given source method.
     * 
     * @param  srcClass  source class - parent of the source method
     * @param  srcMethod  source method for which the test method should be
     *                    created
     * @param  useNoArgConstrutor  whether a no-argument constructor should be
     *                             used in the default test method body;
     *                             it should not be {@code true} unless
     *                             the source class contains an accessible
     *                             no-argument constructor
     * @param  instanceClsName  name of a class of which a constructor should be
     *                          createc if {@code useNoArgConstrutor} is
     *                          {@code true}
     * @return  the generated test method
     */
    @NbBundle.Messages({"# {0} - method",
        "# {1} - class",
        "TestCreator.variantMethods.JavaDoc.comment=Test of {0} method, of class {1}."})
    protected MethodTree generateTestMethod(TypeElement srcClass,
                                          ExecutableElement srcMethod,
                                          String testMethodName,
                                          CharSequence instanceClsName,
                                          WorkingCopy workingCopy) {
        final TreeMaker maker = workingCopy.getTreeMaker();

        MethodTree method = composeNewTestMethod(
                testMethodName,
                generateTestMethodBody(srcClass,
                                       srcMethod,
                                       instanceClsName,
                                       workingCopy),
                generateThrowsList(srcMethod, workingCopy, maker, isClassEjb31Bean(workingCopy, srcClass)),
                workingCopy);

        if (setup.isGenerateMethodJavadoc()) {
//            String commentText = NbBundle.getMessage(
//                    TestCreator.class,
//                    "TestCreator.variantMethods.JavaDoc.comment",       //NOI18N
//                    srcMethod.getSimpleName().toString(),
//                    srcClass.getSimpleName().toString());
            String commentText = Bundle.TestCreator_variantMethods_JavaDoc_comment(
                    srcMethod.getSimpleName().toString(),
                    srcClass.getSimpleName().toString());
            Comment javadoc = Comment.create(Comment.Style.JAVADOC,
                                             -2, -2, -2,
                                             commentText);
            maker.addComment(method, javadoc, true);
        }

        return method;
    }
项目:incubator-netbeans    文件:FindOverridingVisitor.java   
@Override
public Tree visitMethod(MethodTree node, Element elementToFind) {
    if (!workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) {
        ExecutableElement el = (ExecutableElement) workingCopy.getTrees().getElement(getCurrentPath());

        if (el != null && workingCopy.getElements().overrides(el, (ExecutableElement) elementToFind, (TypeElement) el.getEnclosingElement())) {
            addUsage(getCurrentPath());
        }
    }
    return super.visitMethod(node, elementToFind);
}
项目:incubator-netbeans    文件:TestGenerator.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
 */
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    文件:Hacks.java   
@Override
public Scope visitMethod(MethodTree node, CompilationInfo p) {
    if (node.getReturnType() == null) {
        return null;
    }
    return super.visitMethod(node, p);
}
项目: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    文件:ConvertToLambdaPreconditionChecker.java   
@Override
public Tree visitMethod(MethodTree methodTree, Trees trees) {

    //don't visit synthetic methods
    TreePath path = getCurrentPath();
    if (info.getTreeUtilities().isSynthetic(path)) {
        return methodTree;
    }
    return super.visitMethod(methodTree, trees);
}
项目:incubator-netbeans    文件:JavaSourceHelper.java   
public static void getAvailableConstructorSignature(JavaSource source,
        Map<String, String> map) {
    List<MethodTree> constructors = getAllConstuctors(source);
    for (MethodTree c : constructors) {
        map.put(createMethodSignature(c, true), c.getName().toString());
    }
}
项目:incubator-netbeans    文件:ClassStructure.java   
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.finalMethod", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.finalMethod", category = "class_structure", enabled = false, suppressWarnings = {"FinalMethod"}) //NOI18N
@TriggerTreeKind(Kind.METHOD)
public static ErrorDescription finalMethod(HintContext context) {
    final MethodTree mth = (MethodTree) context.getPath().getLeaf();
    if (mth.getModifiers().getFlags().contains(Modifier.FINAL)) {
        return ErrorDescriptionFactory.forName(context, mth, NbBundle.getMessage(ClassStructure.class, "MSG_FinalMethod", mth.getName()), //NOI18N
                FixFactory.removeModifiersFix(context.getInfo(), TreePath.getPath(context.getPath(), mth.getModifiers()), EnumSet.of(Modifier.FINAL), NbBundle.getMessage(ClassStructure.class, "FIX_RemoveFinalFromMethod", mth.getName()))); //NOI18N
    }
    return null;
}
项目:incubator-netbeans    文件:JUnit4TestGenerator.java   
/**
 */
@Override
protected List<? extends Tree> generateInitMembers(WorkingCopy workingCopy) {
    if (!setup.isGenerateBefore() && !setup.isGenerateAfter()
            && !setup.isGenerateBeforeClass() && !setup.isGenerateAfterClass()) {
        return Collections.<Tree>emptyList();
    }

    List<MethodTree> result = new ArrayList<MethodTree>(4);
    if (setup.isGenerateBeforeClass()) {
        result.add(
                generateInitMethod(BEFORE_CLASS_METHOD_NAME, ANN_BEFORE_CLASS, true, workingCopy));
    }
    if (setup.isGenerateAfterClass()) {
        result.add(
                generateInitMethod(AFTER_CLASS_METHOD_NAME, ANN_AFTER_CLASS, true, workingCopy));
    }
    if (setup.isGenerateBefore()) {
        result.add(
                generateInitMethod(BEFORE_METHOD_NAME, ANN_BEFORE, false, workingCopy));
    }
    if (setup.isGenerateAfter()) {
        result.add(
                generateInitMethod(AFTER_METHOD_NAME, ANN_AFTER, false, workingCopy));
    }
    return result;
}
项目:incubator-netbeans    文件:ElementScanningTask.java   
@Override
public Context visitMethod(MethodTree 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 null;
}
项目:openjdk-jdk10    文件:LocalInAnonymous.java   
@Override
public Void visitMethod(MethodTree node, Void p) {
    Element prevOwner = currentOwner;
    try {
        Element currentElement = trees.getElement(getCurrentPath());
        if (currentElement.getEnclosingElement() != currentOwner) {
            throw new AssertionError("Unexpected owner!");
        }
        currentOwner = currentElement;
        return super.visitMethod(node, p);
    } finally {
        currentOwner = prevOwner;
    }
}