com.sun.source.tree.MethodTree#getReturnType ( )源码实例Demo

下面列出了com.sun.source.tree.MethodTree#getReturnType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Refaster   文件: UClassDecl.java
@Override
@Nullable
public Unifier visitClass(ClassTree node, @Nullable Unifier unifier) {
  // We want to skip e.g. autogenerated init members, so we do this by hand...
  Iterator<UMethodDecl> membersItr = getMembers().iterator();
  for (Tree targetMember : node.getMembers()) {
    if (targetMember instanceof MethodTree) {
      MethodTree targetMethodDecl = (MethodTree) targetMember;
      if (targetMethodDecl.getReturnType() != null) {
        unifier = membersItr.hasNext()
            ? membersItr.next().unify(targetMethodDecl, unifier)
            : null;
      }
    }
  }
  return membersItr.hasNext() ? null : unifier;
}
 
源代码2 项目: netbeans   文件: AsyncConverter.java
private ClassTree moveRestMethod( TreeMaker maker, String movedName,
        MethodTree method, WorkingCopy copy, ClassTree classTree)
{
    List<? extends VariableTree> parameters = method.getParameters();
    Tree returnType = method.getReturnType();
    BlockTree body = method.getBody();  
    
    ModifiersTree modifiers = maker.Modifiers(EnumSet.of(Modifier.PRIVATE));
    MethodTree newMethod = maker.Method(modifiers, movedName, 
            returnType,
            Collections.<TypeParameterTree> emptyList(),
            parameters,
            Collections.<ExpressionTree> emptyList(),body,null);
    
    ClassTree newClass = maker.addClassMember(classTree, newMethod);
    newClass = maker.removeClassMember(newClass, method);
    return newClass;
}
 
源代码3 项目: besu   文件: DoNotReturnNullOptionals.java
@SuppressWarnings("TreeToString")
@Override
public Description matchMethod(final MethodTree tree, final VisitorState state) {
  if ((tree.getReturnType() == null)
      || !tree.getReturnType().toString().startsWith("Optional<")
      || (tree.getBody() == null)
      || (!CONTAINS_RETURN_NULL.matches(tree.getBody(), state))) {
    return Description.NO_MATCH;
  }
  return describeMatch(tree);
}
 
源代码4 项目: deptective   文件: DeptectiveTreeVisitor.java
@Override
public Void visitMethod(MethodTree node, Void p) {
    Tree returnType = node.getReturnType();
    if (returnType != null) {
        checkPackageAccess(returnType, getQualifiedPackageName(returnType));
    }
    return super.visitMethod(node, p);
}
 
源代码5 项目: teku   文件: DoNotReturnNullOptionals.java
@Override
public Description matchMethod(final MethodTree tree, final VisitorState state) {
  if ((tree.getReturnType() == null)
      || !RETURN_OPTIONAL_MATCHER.matches(tree, state)
      || (tree.getBody() == null)
      || !CONTAINS_RETURN_NULL.matches(tree.getBody(), state)) {
    return Description.NO_MATCH;
  }
  return describeMatch(tree);
}
 
源代码6 项目: deptective   文件: DeptectiveTreeVisitor.java
@Override
public Void visitMethod(MethodTree node, Void p) {
    Tree returnType = node.getReturnType();
    if (returnType != null) {
        checkPackageAccess(returnType, getQualifiedPackageName(returnType));
    }
    return super.visitMethod(node, p);
}
 
源代码7 项目: netbeans   文件: Hacks.java
@Override
public Scope visitMethod(MethodTree node, CompilationInfo p) {
    if (node.getReturnType() == null) {
        return null;
    }
    return super.visitMethod(node, p);
}
 
源代码8 项目: Refaster   文件: UTemplater.java
@Override
public UClassDecl visitClass(ClassTree tree, Void v) {
  ImmutableList.Builder<UMethodDecl> decls = ImmutableList.builder();
  for (MethodTree decl : Iterables.filter(tree.getMembers(), MethodTree.class)) {
    if (decl.getReturnType() != null) {
      decls.add(visitMethod(decl, null));
    }
  }
  return UClassDecl.create(decls.build());
}
 
源代码9 项目: netbeans   文件: ChangeMethodReturnType.java
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    TreePath parentPath = treePath.getParentPath();
    if (parentPath == null || parentPath.getLeaf().getKind() != Kind.RETURN) return null;
    
    TreePath method = null;
    TreePath tp = treePath;

    while (tp != null && !TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
        if (tp.getLeaf().getKind() == Kind.METHOD) {
            method = tp;
            break;
        }

        tp = tp.getParentPath();
    }

    if (method == null) return null;

    MethodTree mt = (MethodTree) tp.getLeaf();

    if (mt.getReturnType() == null) return null;

    TypeMirror targetType = purify(info, info.getTrees().getTypeMirror(treePath));

    if (targetType == null) return null;

    if (targetType.getKind() == TypeKind.EXECUTABLE) {
        String expression = info.getText().substring((int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), treePath.getLeaf()), (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), treePath.getLeaf()));
        Scope s = info.getTrees().getScope(treePath);
        ExpressionTree expr = info.getTreeUtilities().parseExpression(expression, new SourcePositions[1]);

        targetType = purify(info, info.getTreeUtilities().attributeTree(expr, s));
    }

    if (targetType == null || targetType.getKind() == TypeKind.EXECUTABLE) return null;

    return Collections.singletonList(new FixImpl(info, method, TypeMirrorHandle.create(targetType), info.getTypeUtilities().getTypeName(targetType).toString()).toEditorFix());
}
 
源代码10 项目: netbeans   文件: MagicSurroundWithTryCatchFix.java
public @Override Void visitBlock(BlockTree bt, Void p) {
    List<CatchTree> catches = createCatches(info, make, thandles, statement);
    
    //#89379: if inside a constructor, do not wrap the "super"/"this" call:
    //please note that the "super" or "this" call is supposed to be always
    //in the constructor body
    BlockTree toUse = bt;
    StatementTree toKeep = null;
    Tree parent = getCurrentPath().getParentPath().getLeaf();
    
    if (parent.getKind() == Kind.METHOD && bt.getStatements().size() > 0) {
        MethodTree mt = (MethodTree) parent;
        
        if (mt.getReturnType() == null) {
            toKeep = bt.getStatements().get(0);
            toUse = make.Block(bt.getStatements().subList(1, bt.getStatements().size()), false);
        }
    }
    
    if (!streamAlike) {
        info.rewrite(bt, createBlock(bt.isStatic(), toKeep, make.Try(toUse, catches, null)));
    } else {
        VariableTree originalDeclaration = (VariableTree) statement.getLeaf();
        VariableTree declaration = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), originalDeclaration.getName(), originalDeclaration.getType(), make.Identifier("null"));
        StatementTree assignment = make.ExpressionStatement(make.Assignment(make.Identifier(originalDeclaration.getName()), originalDeclaration.getInitializer()));
        BlockTree finallyTree = make.Block(Collections.singletonList(createFinallyCloseBlockStatement(originalDeclaration)), false);
        
        info.rewrite(originalDeclaration, assignment);
        info.rewrite(bt, createBlock(bt.isStatic(), toKeep, declaration, make.Try(toUse, catches, finallyTree)));
    }
    
    return null;
}
 
源代码11 项目: netbeans   文件: ClassStructure.java
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.publicConstructorInNonPublicClass", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.publicConstructorInNonPublicClass", category = "class_structure", enabled = false, suppressWarnings = {"PublicConstructorInNonPublicClass"}) //NOI18N
@TriggerTreeKind(Kind.METHOD)
public static ErrorDescription publicConstructorInNonPublicClass(HintContext context) {
    final MethodTree mth = (MethodTree) context.getPath().getLeaf();
    final Tree parent = context.getPath().getParentPath().getLeaf();
    if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getKind()) && mth.getReturnType() == null && "<init>".contentEquals(mth.getName()) && //NOI18N
            mth.getModifiers().getFlags().contains(Modifier.PUBLIC) && !((ClassTree) parent).getModifiers().getFlags().contains(Modifier.PUBLIC)) {
        return ErrorDescriptionFactory.forName(context, mth, NbBundle.getMessage(ClassStructure.class, "MSG_PublicConstructorInNonPublicClass", mth.getName()), //NOI18N
                FixFactory.removeModifiersFix(context.getInfo(), TreePath.getPath(context.getPath(), mth.getModifiers()), EnumSet.of(Modifier.PUBLIC), NbBundle.getMessage(ClassStructure.class, "FIX_RemovePublicFromConstructor"))); //NOI18N
    }
    return null;
}
 
源代码12 项目: openjdk-jdk9   文件: Eval.java
private List<Snippet> processMethod(String userSource, Tree unitTree, String compileSource, ParseTask pt) {
    TreeDependencyScanner tds = new TreeDependencyScanner();
    tds.scan(unitTree);
    TreeDissector dis = TreeDissector.createByFirstClass(pt);

    MethodTree mt = (MethodTree) unitTree;
    String name = mt.getName().toString();
    String parameterTypes
            = mt.getParameters()
            .stream()
            .map(param -> dis.treeToRange(param.getType()).part(compileSource))
            .collect(Collectors.joining(","));
    Tree returnType = mt.getReturnType();
    DiagList modDiag = modifierDiagnostics(mt.getModifiers(), dis, true);
    MethodKey key = state.keyMap.keyForMethod(name, parameterTypes);
    // Corralling mutates.  Must be last use of pt, unitTree, mt
    Wrap corralled = new Corraller(key.index(), pt.getContext()).corralMethod(mt);

    if (modDiag.hasErrors()) {
        return compileFailResult(modDiag, userSource, Kind.METHOD);
    }
    Wrap guts = Wrap.classMemberWrap(compileSource);
    Range typeRange = dis.treeToRange(returnType);
    String signature = "(" + parameterTypes + ")" + typeRange.part(compileSource);

    Snippet snip = new MethodSnippet(key, userSource, guts,
            name, signature,
            corralled, tds.declareReferences(), tds.bodyReferences(), modDiag);
    return singletonList(snip);
}
 
源代码13 项目: netbeans   文件: SemanticHighlighterBase.java
@Override
public Void visitMethod(MethodTree tree, Void p) {
    if (info.getTreeUtilities().isSynthetic(getCurrentPath())) {
        return super.visitMethod(tree, p);
    }

    //#170338: constructor without modifiers:
    tl.moveToOffset(sourcePositions.getStartPosition(info.getCompilationUnit(), tree));

    handlePossibleIdentifier(getCurrentPath(), true);
    
    Element el = info.getTrees().getElement(getCurrentPath());
    
    scan(tree.getModifiers(), null);
    tl.moveToEnd(tree.getModifiers());
    scan(tree.getTypeParameters(), null);
    tl.moveToEnd(tree.getTypeParameters());
    scan(tree.getReturnType(), p);
    tl.moveToEnd(tree.getReturnType());
    
    String name;
    
    if (tree.getReturnType() != null) {
        //method:
        name = tree.getName().toString();
    } else {
        //constructor:
        TreePath tp = getCurrentPath();
        
        while (tp != null && !TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
            tp = tp.getParentPath();
        }
        
        if (tp != null && TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
            name = ((ClassTree) tp.getLeaf()).getSimpleName().toString();
        } else {
            name = null;
        }
    }
    
    if (name != null) {
        firstIdentifier(name);
    }
    
    scan(tree.getParameters(), null);
    scan(tree.getThrows(), null);
    scan(tree.getDefaultValue(), null);

    recursionDetector = (el != null && el.getKind() == ElementKind.METHOD) ? (ExecutableElement) el : null;
    
    scan(tree.getBody(), null);

    recursionDetector = null;

    return null;
}
 
源代码14 项目: openjdk-jdk9   文件: CompletenessStressTest.java
@Test(dataProvider = "crawler")
public void testFile(String fileName) throws IOException {
    File file = getSourceFile(fileName);
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    boolean success = true;
    StringWriter writer = new StringWriter();
    writer.write("Testing : " + file.toString() + "\n");
    String text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file);
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Trees trees = Trees.instance(task);
    SourcePositions sp = trees.getSourcePositions();

    for (CompilationUnitTree cut : asts) {
        for (ImportTree imp : cut.getImports()) {
            success &= testStatement(writer, sp, text, cut, imp);
        }
        for (Tree decl : cut.getTypeDecls()) {
            success &= testStatement(writer, sp, text, cut, decl);
            if (decl instanceof ClassTree) {
                ClassTree ct = (ClassTree) decl;
                for (Tree mem : ct.getMembers()) {
                    if (mem instanceof MethodTree) {
                        MethodTree mt = (MethodTree) mem;
                        BlockTree bt = mt.getBody();
                        // No abstract methods or constructors
                        if (bt != null && mt.getReturnType() != null) {
                            // The modifiers synchronized, abstract, and default are not allowed on
                            // top-level declarations and are errors.
                            Set<Modifier> modifier = mt.getModifiers().getFlags();
                            if (!modifier.contains(Modifier.ABSTRACT)
                                    && !modifier.contains(Modifier.SYNCHRONIZED)
                                    && !modifier.contains(Modifier.DEFAULT)) {
                                success &= testStatement(writer, sp, text, cut, mt);
                            }
                            testBlock(writer, sp, text, cut, bt);
                        }
                    }
                }
            }
        }
    }
    fileManager.close();
    if (!success) {
        throw new AssertionError(writer.toString());
    }
}
 
源代码15 项目: netbeans   文件: CreateElementUtilities.java
private static List<? extends TypeMirror> computeMethod(Set<ElementKind> types, CompilationInfo info, TreePath parent, TypeMirror[] typeParameterBound, Tree error, int offset) {
       //class or field:
       //check the error is in the body:
       //#92419: check for abstract method/method without body:
       MethodTree mt = (MethodTree) parent.getLeaf();
       
       if (mt.getReturnType() == error) {
           types.add(ElementKind.CLASS);
           types.add(ElementKind.INTERFACE);
           types.add(ElementKind.ENUM);
       }

       List<? extends ExpressionTree> throwList = mt.getThrows();
if (throwList != null && !throwList.isEmpty()) {
           for (ExpressionTree t : throwList) {
               if (t == error) {
                   types.add(ElementKind.CLASS);
                   typeParameterBound[0] = info.getElements().getTypeElement("java.lang.Exception").asType();
                   break;
               }
           }
}
       
       if (mt.getBody() == null) {
           return null;
       }
       
       try {
           Document doc = info.getDocument();
           
           if (doc != null) {//XXX
               int bodyStart = findBodyStart(parent.getLeaf(), info.getCompilationUnit(), info.getTrees().getSourcePositions(), doc);
               int bodyEnd   = (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), parent.getLeaf());

               types.add(ElementKind.PARAMETER);
               types.add(ElementKind.LOCAL_VARIABLE);
               types.add(ElementKind.FIELD);

               if (bodyStart <= offset && offset <= bodyEnd)
                   return Collections.singletonList(info.getElements().getTypeElement("java.lang.Object").asType());
           }
       } catch (IOException ex) {
           Logger.getLogger("global").log(Level.INFO, ex.getMessage(), ex);
       }
       
       return null;
   }
 
源代码16 项目: netbeans   文件: ClassMetrics.java
private static ErrorDescription checkTooManyMethods(HintContext ctx, TreePath path, int limit, boolean anon) {
    ClassTree clazz = (ClassTree)path.getLeaf();
    boolean ignoreAccessors = ctx.getPreferences().getBoolean(OPTION_CLASS_METHODS_IGNORE_ACCESSORS, DEFAULT_CLASS_METHODS_IGNORE_ACCESSORS);
    boolean ignoreAbstract = ctx.getPreferences().getBoolean(OPTION_CLASS_METHODS_IGNORE_ABSTRACT, DEFAULT_CLASS_METHODS_IGNORE_ABSTRACT);
    int methodCount = 0;
    for (Tree member : clazz.getMembers()) {
        if (member.getKind() != Tree.Kind.METHOD) {
            continue;
        }
        MethodTree method = (MethodTree)member;
        if (method.getReturnType() == null) {
            // a constructor ?
            continue;
        }
        TreePath methodPath = new TreePath(path, method);
        if (ignoreAccessors && (isSimpleGetter(ctx.getInfo(), methodPath) ||
                isSimpleSetter(ctx.getInfo(), methodPath))) {
            continue;
        }
        if (ignoreAbstract) {
            ExecutableElement mel = (ExecutableElement)ctx.getInfo().getTrees().getElement(methodPath);
            ExecutableElement overriden = ctx.getInfo().getElementUtilities().getOverriddenMethod(mel);
            if (overriden != null && overriden.getModifiers().contains(Modifier.ABSTRACT)) {
                continue;
            }
        }
        methodCount++;
    }
    
    if (methodCount <= limit) {
        return null;
    }
    if (anon) {
        CompilationInfo info = ctx.getInfo();
        SourcePositions pos = info.getTrees().getSourcePositions();
        long start = pos.getStartPosition(info.getCompilationUnit(), path.getParentPath().getLeaf());
        long mstart = pos.getStartPosition(info.getCompilationUnit(), path.getLeaf());
        return ErrorDescriptionFactory.forSpan(ctx, (int)start, (int)mstart,
                TEXT_AnonClassManyMethods(methodCount));
    } else {
        return ErrorDescriptionFactory.forName(ctx, 
                path, 
                TEXT_ClassManyMethods(clazz.getSimpleName().toString(), methodCount));
    }
}
 
源代码17 项目: netbeans   文件: MissingReturnStatement.java
@Override
public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    TreePath method = null;
    if (diagnosticKey != null && diagnosticKey.contains("/compiler.misc.incompatible.ret.type.in.lambda/")) { // NOI18N
        // PENDING: when issue #258201 is implemented, use the new method instead of this HACK
        offset++;
    }
    TreePath tp = compilationInfo.getTreeUtilities().pathFor(offset);

    while (tp != null && !TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
        Kind kind = tp.getLeaf().getKind();
        if (kind == Kind.METHOD || kind == Kind.LAMBDA_EXPRESSION) {
            method = tp;
            break;
        }

        tp = tp.getParentPath();
    }

    if (method == null) {
        return null;
    }
    
    if (method.getLeaf().getKind() == Kind.METHOD) {
        MethodTree mt = (MethodTree) tp.getLeaf();
        if (mt.getReturnType() == null) {
            return null;
        }
    } else if (method.getLeaf().getKind() == Kind.LAMBDA_EXPRESSION) {
        LambdaExpressionTree let = (LambdaExpressionTree)method.getLeaf();
        TreePath bodyPath = new TreePath(method, let.getBody());
        if (let.getBodyKind() == LambdaExpressionTree.BodyKind.EXPRESSION) {
            TypeMirror m = compilationInfo.getTrees().getTypeMirror(
                bodyPath);
            if (m == null) {
                return null;
            }
            if (m.getKind() == TypeKind.ERROR) {
                m = compilationInfo.getTrees().getOriginalType((ErrorType)m);
            }
            if (m.getKind() != TypeKind.VOID) {
                // do not offer to add return for something, which already has
                // some type
                return null;
            }
        } else if (Utilities.exitsFromAllBranchers(compilationInfo, bodyPath)) {
            // do not add return, returns are already there.
            return null;
        }
    }

    List<Fix> result = new ArrayList<Fix>(2);

    result.add(new FixImpl(compilationInfo.getSnapshot().getSource(), TreePathHandle.create(tp, compilationInfo)));
    if (method.getLeaf().getKind() == Kind.METHOD) {
        result.add(new ChangeMethodReturnType.FixImpl(compilationInfo, tp, TypeMirrorHandle.create(compilationInfo.getTypes().getNoType(TypeKind.VOID)), "void").toEditorFix());
    }

    return result;
}
 
源代码18 项目: netbeans   文件: CreateElementUtilities.java
private static List<? extends TypeMirror> computeMethod(Set<ElementKind> types, CompilationInfo info, TreePath parent, TypeMirror[] typeParameterBound, Tree error, int offset) {
       //class or field:
       //check the error is in the body:
       //#92419: check for abstract method/method without body:
       MethodTree mt = (MethodTree) parent.getLeaf();
       
       if (mt.getReturnType() == error) {
           types.add(ElementKind.CLASS);
           types.add(ElementKind.INTERFACE);
           types.add(ElementKind.ENUM);
       }

       List<? extends ExpressionTree> throwList = mt.getThrows();
if (throwList != null && !throwList.isEmpty()) {
           for (ExpressionTree t : throwList) {
               if (t == error) {
                   types.add(ElementKind.CLASS);
                   TypeElement tel = info.getElements().getTypeElement("java.lang.Exception");
                   if (tel == null) {
                       return null;
                   }
                   typeParameterBound[0] = tel.asType();
                   break;
               }
           }
}
       
       if (mt.getBody() == null) {
           return null;
       }
       
       try {
           Document doc = info.getDocument();
           
           if (doc != null) {//XXX
               int bodyStart = Utilities.findBodyStart(info, parent.getLeaf(), info.getCompilationUnit(), info.getTrees().getSourcePositions(), doc);
               int bodyEnd   = (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), parent.getLeaf());

               types.add(ElementKind.PARAMETER);
               types.add(ElementKind.LOCAL_VARIABLE);
               types.add(ElementKind.FIELD);

               if (bodyStart <= offset && offset <= bodyEnd) {
                   return typeMirrorCollection(info, "java.lang.Object");
               }
           }
       } catch (IOException ex) {
           Logger.getLogger("global").log(Level.INFO, ex.getMessage(), ex);
       }
       
       return null;
   }
 
源代码19 项目: netbeans   文件: JaxWsClassesCookieImpl.java
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
@Override
public void addOperation(final MethodTree method) {
    JavaSource targetSource = JavaSource.forFileObject(implClassFO);
    CancellableTask<WorkingCopy> modificationTask = 
        new CancellableTask<WorkingCopy>() 
        {
        @Override
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);            
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree javaClass = SourceUtils.
                getPublicTopLevelTree(workingCopy);
            if (javaClass!=null) {
                GenerationUtils genUtils = GenerationUtils.newInstance(
                            workingCopy);
                
                AnnotationTree webMethodAnnotation = make.Annotation(
                    make.QualIdent("javax.jws.WebMethod"),      //NOI18N
                    Collections.<ExpressionTree>emptyList()
                );
                // add @WebMethod annotation
                ModifiersTree modifiersTree = make.addModifiersAnnotation(
                        method.getModifiers(), webMethodAnnotation);
                
                // add @Oneway annotation
                if (Kind.PRIMITIVE_TYPE == method.getReturnType().getKind()) {
                    PrimitiveTypeTree primitiveType = 
                        (PrimitiveTypeTree)method.getReturnType();
                    if (TypeKind.VOID == primitiveType.getPrimitiveTypeKind()) {
                        AnnotationTree oneWayAnnotation = make.Annotation(
                            make.QualIdent("javax.jws.Oneway"),         // NOI18N
                            Collections.<ExpressionTree>emptyList()
                        );
                        modifiersTree = make.addModifiersAnnotation(
                                modifiersTree, oneWayAnnotation);
                    }
                }
                
                // add @WebParam annotations 
                List<? extends VariableTree> parameters = method.getParameters();
                List<VariableTree> newParameters = new ArrayList<VariableTree>();
                for (VariableTree param:parameters) {
                    AnnotationTree paramAnnotation = make.Annotation(
                        make.QualIdent("javax.jws.WebParam"),           //NOI18N
                        Collections.<ExpressionTree>singletonList(
                            make.Assignment(make.Identifier("name"),    //NOI18N
                                    make.Literal(param.getName().toString()))) 
                    );
                    newParameters.add(genUtils.addAnnotation(param, paramAnnotation));
                }
                // create new (annotated) method
                MethodTree  annotatedMethod = make.Method(
                            modifiersTree,
                            method.getName(),
                            method.getReturnType(),
                            method.getTypeParameters(),
                            newParameters,
                            method.getThrows(),
                            method.getBody(),
                            (ExpressionTree)method.getDefaultValue());
                Comment comment = Comment.create(NbBundle.getMessage(
                        JaxWsClassesCookieImpl.class, "TXT_WSOperation"));      //NOI18N                 
                make.addComment(annotatedMethod, comment, true);
                
                ClassTree modifiedClass = make.addClassMember(javaClass,
                        annotatedMethod);
                workingCopy.rewrite(javaClass, modifiedClass);
            }
        }
        @Override
        public void cancel() {
            
        }
    };
    try {
        targetSource.runModificationTask(modificationTask).commit();
    } catch (IOException ex) {
        ErrorManager.getDefault().notify(ex);
    }
}
 
源代码20 项目: netbeans   文件: AsyncConverter.java
private ClassTree createAsyncMethod( TreeMaker maker,
        String asyncName, String service, MethodTree method, String movedName , 
        WorkingCopy copy, ClassTree classTree, boolean isEjb)
{
    ModifiersTree modifiers = method.getModifiers();
    if ( isEjb ){
        AnnotationTree async = maker.Annotation(maker.QualIdent(
                "javax.ejb.Asynchronous"),          // NOI18N 
                Collections.<ExpressionTree>emptyList());
        modifiers  = maker.addModifiersAnnotation(modifiers, async);
    }
    List<? extends VariableTree> parameters = method.getParameters();
    String asyncReponseParam = getAsynParam("asyncResponse",parameters);//NOI18N
    
    ModifiersTree paramModifier = maker.Modifiers(EnumSet.of(Modifier.FINAL));
    AnnotationTree annotation = maker.Annotation(
            maker.QualIdent("javax.ws.rs.container.Suspended"),        // NOI18N
            Collections.<ExpressionTree>emptyList());
    paramModifier = maker.Modifiers(paramModifier, 
            Collections.singletonList(annotation));
    VariableTree asyncParam = maker.Variable(paramModifier, asyncReponseParam, 
            maker.QualIdent("javax.ws.rs.container.AsyncResponse"), null);//NOI18N
    List<VariableTree> params = new ArrayList<VariableTree>(parameters.size()+1);
    params.add(asyncParam);
    
    Tree returnType = method.getReturnType();
    boolean noReturn =returnType.toString().equals("void");     // NOI18N

    StringBuilder body = new StringBuilder("{");                // NOI18N
    if ( !isEjb ){
        body.append(service);
        body.append(".submit(new Runnable() { public void run() {");//NOI18N
    }
    if ( !noReturn ){
        body.append(asyncReponseParam);
        body.append(".resume(");                            // NOI18N
    }
    body.append(movedName);
    body.append('(');
    for (VariableTree param : parameters) {
        ModifiersTree modifier = maker.addModifiersModifier(param.getModifiers(), 
                Modifier.FINAL);
        VariableTree newParam = maker.Variable(modifier, param.getName(), 
                param.getType(), param.getInitializer());
        params.add(newParam);
        TreePath pathParam = copy.getTrees().getPath(
                copy.getCompilationUnit(), param);
        body.append(copy.getTrees().getElement(pathParam).getSimpleName());
        body.append(',');
    }
    if ( !parameters.isEmpty()){
        body.deleteCharAt(body.length()-1);
    }
    if ( noReturn){
        body.append(");");
        body.append(asyncReponseParam);
        body.append(".resume(javax.ws.rs.core.Response.ok().build());");//NOI18N
    }
    else {
        body.append("));");
    }
    if ( !isEjb ){
        body.append("}});");
    }
    body.append('}');
    
    MethodTree newMethod = maker.Method(modifiers, asyncName, 
            maker.Type("void"),             // NOI18N
            Collections.<TypeParameterTree> emptyList(),
            params,
            Collections.<ExpressionTree> emptyList(),
            body.toString(),null);
    return maker.addClassMember(classTree, newMethod);
}