com.sun.source.tree.MethodTree Java Examples

The following examples show how to use com.sun.source.tree.MethodTree. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavacParserTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPreferredPositionForBinaryOp() throws IOException {

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

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

    JCTree condJC = (JCTree) cond;
    int condStartPos = code.indexOf("&&");
    assertEquals("testPreferredPositionForBinaryOp",
            condStartPos, condJC.pos);
}
 
Example #2
Source File: WrappingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testVariableInitWrapped() throws Exception {
    String code = "package hierbas.del.litoral;\n\n" +
        "import java.util.concurrent.atomic.AtomicBoolean;\n\n" +
        "public class Test {\n" +
        "    public void t() {\n" +
        "        new AtomicBoolean();\n" + 
        "    }\n" +
        "}\n";
    runWrappingTest(code, new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ExpressionStatementTree init = (ExpressionStatementTree) method.getBody().getStatements().get(0);
            VariableTree nue = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "ab", make.Type("java.util.concurrent.atomic.AtomicBoolean"), init.getExpression());
            workingCopy.rewrite(init, nue);
        }
    }, FmtOptions.wrapAssignOps, WrapStyle.WRAP_IF_LONG.name());
}
 
Example #3
Source File: AbstractMethodGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Adds method to class.
 * <p>
 * <b>Should be called outside EDT.</b>
 */
protected static void addMethod(final MethodModel methodModel, FileObject fileObject, final String className) throws IOException {
    if (fileObject != null && methodModel != null){
        JavaSource javaSource = JavaSource.forFileObject(fileObject);
        javaSource.runModificationTask(new Task<WorkingCopy>() {
            public void run(WorkingCopy workingCopy) throws IOException {
                workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                TypeElement typeElement = workingCopy.getElements().getTypeElement(className);
                boolean generateDefaultBody = (typeElement.getKind() != ElementKind.INTERFACE) && !methodModel.getModifiers().contains(Modifier.ABSTRACT);
                MethodTree methodTree = MethodModelSupport.createMethodTree(workingCopy, methodModel, generateDefaultBody);
                ClassTree classTree = workingCopy.getTrees().getTree(typeElement);
                ClassTree newClassTree = workingCopy.getTreeMaker().addClassMember(classTree, methodTree);
                workingCopy.rewrite(classTree, newClassTree);
            }
        }).commit();
    }
}
 
Example #4
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #5
Source File: JavacParserTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPreferredPositionForBinaryOp() throws IOException {

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

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

    JCTree condJC = (JCTree) cond;
    int condStartPos = code.indexOf("&&");
    assertEquals("testPreferredPositionForBinaryOp",
            condStartPos, condJC.pos);
}
 
Example #6
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String createMethodSignature(MethodTree m, boolean skipName) {
    String sign = "";
    if (!skipName) {
        sign += m.getName();
    }
    sign += "(";
    if (m.getParameters() != null) {
        for (VariableTree p : m.getParameters()) {
            sign += getShortTypeName(p.getType()) + ",";
        }
        if (m.getParameters().size() > 0) {
            sign = sign.substring(0, sign.length() - 1);
        }
    }
    sign += ")";
    return sign;
}
 
Example #7
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a setter method for a field.
 *
 * @param clazz the class to create the setter within
 * @param field field to create setter for
 * @return the setter method
 * @since 0.20
 */
public MethodTree createSetter(ClassTree clazz, VariableTree field) {
    assert clazz != null && field != null;
    TreeMaker make = copy.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    boolean isStatic = field.getModifiers().getFlags().contains(Modifier.STATIC);
    if (isStatic)
        mods.add(Modifier.STATIC);
    CharSequence name = field.getName();
    assert name.length() > 0;
    CodeStyle cs = DiffContext.getCodeStyle(copy);
    String propName = removeFieldPrefixSuffix(field, cs);
    String setterName = CodeStyleUtils.computeSetterName(field.getName(), isStatic, cs);
    String paramName = addParamPrefixSuffix(propName, cs);
    List<VariableTree> params = Collections.singletonList(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), paramName, field.getType(), null));
    BlockTree body = make.Block(Collections.singletonList(make.ExpressionStatement(make.Assignment(make.MemberSelect(isStatic? make.Identifier(clazz.getSimpleName()) : make.Identifier("this"), name), make.Identifier(paramName)))), false); //NOI18N
    return make.Method(make.Modifiers(mods), setterName, make.Type(copy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), params, Collections.<ExpressionTree>emptyList(), body, null);
}
 
Example #8
Source File: Tiny.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean isSynced(HintContext ctx, TreePath inspect) {
    while (inspect != null && !TreeUtilities.CLASS_TREE_KINDS.contains(inspect.getLeaf().getKind())) {
        if (inspect.getLeaf().getKind() == Kind.SYNCHRONIZED) {
            return true;
        }

        if (inspect.getLeaf().getKind() == Kind.METHOD) {
            if (((MethodTree) inspect.getLeaf()).getModifiers().getFlags().contains(Modifier.SYNCHRONIZED)) {
                return true;
            }

            break;
        }

        inspect = inspect.getParentPath();
    }

    return false;
}
 
Example #9
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static MethodTree getMethodByName(CompilationController controller, String methodName) {
    TypeElement classElement = getTopLevelClassElement(controller);
    List<ExecutableElement> methods = ElementFilter.methodsIn(classElement.getEnclosedElements());
    List<MethodTree> found = new ArrayList<MethodTree>();
    for (ExecutableElement method : methods) {
        if (method.getSimpleName().toString().equals(methodName)) {
            found.add(controller.getTrees().getTree(method));
        }
    }
    if (found.size() > 1) {
        throw new IllegalArgumentException("Unexpected overloading methods of '" + methodName + "' found.");
    } else if (found.size() == 1) {
        return found.get(0);
    }
    return null;
}
 
Example #10
Source File: CompilationInfo.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns tree which was reparsed by an incremental reparse.
 * When the source file wasn't parsed yet or the parse was a full parse
 * this method returns null.
 * <p class="nonnormative">
 * Currently the leaf tree is a MethodTree but this may change in the future.
 * Client of this method is responsible to check the corresponding TreeKind
 * to find out if it may perform on the changed subtree or it needs to
 * reprocess the whole tree.
 * </p>
 * @return {@link TreePath} or null
 * @since 0.31
 */
public @CheckForNull @CheckReturnValue TreePath getChangedTree () {
    checkConfinement();
    if (JavaSource.Phase.PARSED.compareTo (impl.getPhase())>0) {
        return null;
    }
    final Pair<DocPositionRegion,MethodTree> changedTree = impl.getChangedTree();
    if (changedTree == null) {
        return null;
    }
    final CompilationUnitTree cu = impl.getCompilationUnit();
    if (cu == null) {
        return null;
    }
    return TreePath.getPath(cu, changedTree.second());
}
 
Example #11
Source File: MethodTest4.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAddThirdThrows() throws IOException {
    System.err.println("testAddThirdThrows");
    process(
        new Transformer<Void, Object>() {
            public Void visitMethod(MethodTree node, Object p) {
                super.visitMethod(node, p);
                if ("fooMethod".contentEquals(node.getName())) {
                    MethodTree copy = make.insertMethodThrows(node, 0, make.Identifier("java.io.WriteAbortedException"));
                    this.copy.rewrite(node, copy);
                }
                return null;
            }
        }
    );
    assertFiles("testAddThirdThrows.pass");
}
 
Example #12
Source File: JavacParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testStartPositionForMethodWithoutModifiers() throws IOException {

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

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

    assertEquals("testStartPositionForMethodWithoutModifiers",
            "<T> void t() {}", code.substring(start, end));
}
 
Example #13
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPreferredPositionForBinaryOp() throws IOException {

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

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

    JCTree condJC = (JCTree) cond;
    int condStartPos = code.indexOf("&&");
    assertEquals("testPreferredPositionForBinaryOp",
            condStartPos, condJC.pos);
}
 
Example #14
Source File: JUnit3TestGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 */
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
}
 
Example #15
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static MethodTree getDefaultConstructor(CompilationController controller) {
    TypeElement classElement = getTopLevelClassElement(controller);
    List<ExecutableElement> constructors = ElementFilter.constructorsIn(classElement.getEnclosedElements());

    for (ExecutableElement constructor : constructors) {
        if (constructor.getParameters().size() == 0) {
            return controller.getTrees().getTree(constructor);
        }
    }

    return null;
}
 
Example #16
Source File: MethodInputParametersMustBeFinal.java    From besu with Apache License 2.0 5 votes vote down vote up
private Description matchParameters(final MethodTree tree) {
  for (final VariableTree inputParameter : tree.getParameters()) {
    if (isMissingFinalModifier(inputParameter)) {
      return describeMatch(tree);
    }
  }

  return Description.NO_MATCH;
}
 
Example #17
Source File: FinalizeNotProtected.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    final Tree tree = tp.getLeaf();
    if (tree.getKind() != Tree.Kind.METHOD) {
        return;
    }
    final TreeMaker tm = wc.getTreeMaker();
    wc.rewrite(((MethodTree)tree).getModifiers(), tm.addModifiersModifier(
            tm.removeModifiersModifier(((MethodTree)tree).getModifiers(), Modifier.PUBLIC),
            Modifier.PROTECTED));
}
 
Example #18
Source File: TestInvokeDynamic.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitMethod(MethodTree node, Void p) {
    super.visitMethod(node, p);
    if (node.getName().toString().equals("bsm")) {
        bsm = ((JCMethodDecl)node).sym;
    }
    return null;
}
 
Example #19
Source File: JavacParserTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
void testPositionBrokenSource126732b() throws IOException {
    String[] commands = new String[]{
        "break",
        "break A",
        "continue ",
        "continue A",};

    for (String command : commands) {

        String code = "package test;\n"
                + "public class Test {\n"
                + "    public static void test() {\n"
                + "        while (true) {\n"
                + "            " + command + " {\n"
                + "                new Runnable() {\n"
                + "        };\n"
                + "        }\n"
                + "    }\n"
                + "}";

        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null,
                null, null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();

        ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
        MethodTree method = (MethodTree) clazz.getMembers().get(0);
        List<? extends StatementTree> statements =
                ((BlockTree) ((WhileLoopTree) method.getBody().getStatements().get(0)).getStatement()).getStatements();

        StatementTree ret = statements.get(0);
        StatementTree block = statements.get(1);

        Trees t = Trees.instance(ct);
        int len = code.indexOf(command + " {") + (command + " ").length();
        assertEquals(command, len,
                t.getSourcePositions().getEndPosition(cut, ret));
        assertEquals(command, len,
                t.getSourcePositions().getStartPosition(cut, block));
    }
}
 
Example #20
Source File: JavacParserTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
void testErrorRecoveryForEnhancedForLoop142381() throws IOException {

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

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

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

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

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

    assertEquals("testErrorRecoveryForEnhancedForLoop142381",
            Kind.ENHANCED_FOR_LOOP, forStatement.getKind());
    assertFalse("testErrorRecoveryForEnhancedForLoop142381", errors.isEmpty());
}
 
Example #21
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isBooleanGetter(Tree member) {
    return member.getKind() == Tree.Kind.METHOD
            && name(member).startsWith("is") //NOI18N
            && ((MethodTree)member).getParameters().isEmpty()
            && ((MethodTree)member).getReturnType().getKind() == Tree.Kind.PRIMITIVE_TYPE
            && ((PrimitiveTypeTree)((MethodTree)member).getReturnType()).getPrimitiveTypeKind() == TypeKind.BOOLEAN;
}
 
Example #22
Source File: ElementHeaderFormater.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static String getMethodHeader(MethodTree tree, ClassTree enclosingClass, CompilationInfo info, String s) {
    VeryPretty veryPretty = new VeryPretty(new DiffContext(info));
    if (enclosingClass != null) {
        veryPretty.enclClass = (com.sun.tools.javac.tree.JCTree.JCClassDecl) enclosingClass;
    }
    return veryPretty.getMethodHeader(tree, s);
}
 
Example #23
Source File: JavacParserTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void testPositionBrokenSource126732b() throws IOException {
    String[] commands = new String[]{
        "break",
        "break A",
        "continue ",
        "continue A",};

    for (String command : commands) {

        String code = "package test;\n"
                + "public class Test {\n"
                + "    public static void test() {\n"
                + "        while (true) {\n"
                + "            " + command + " {\n"
                + "                new Runnable() {\n"
                + "        };\n"
                + "        }\n"
                + "    }\n"
                + "}";

        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null,
                null, null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();

        ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
        MethodTree method = (MethodTree) clazz.getMembers().get(0);
        List<? extends StatementTree> statements =
                ((BlockTree) ((WhileLoopTree) method.getBody().getStatements().get(0)).getStatement()).getStatements();

        StatementTree ret = statements.get(0);
        StatementTree block = statements.get(1);

        Trees t = Trees.instance(ct);
        int len = code.indexOf(command + " {") + (command + " ").length();
        assertEquals(command, len,
                t.getSourcePositions().getEndPosition(cut, ret));
        assertEquals(command, len,
                t.getSourcePositions().getStartPosition(cut, block));
    }
}
 
Example #24
Source File: Eval.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #25
Source File: TestInvokeDynamic.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitMethod(MethodTree node, Void p) {
    super.visitMethod(node, p);
    if (node.getName().toString().equals("bsm")) {
        bsm = ((JCMethodDecl)node).sym;
    }
    return null;
}
 
Example #26
Source File: GeneratorUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testOverrideAnnotation2() throws Exception {
    performTest("package test;\npublic class Test extends C implements B { }\ninterface A {public void test1(); public void test4();}\ninterface B {public void test2();}\nabstract class C implements A {public abstract void test3(); public abstract void test4();}\n", "1.6", new AddAllAbstractMethodsTask(30), new Validator() {
        public void validate(CompilationInfo info) {
            ClassTree ct = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);

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

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

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

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

                if ("test4".equals(m.getName().toString())) {
                    assertFalse(m.getModifiers().getAnnotations().isEmpty());
                }
            }
        }
    });
}
 
Example #27
Source File: ModifiersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Original:
 * 
 * void method() {
 * }
 * 
 * Result:
 * 
 * public static void method() {
 * }
 */
public void testMethodMods1() 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" +
            "    void method() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    public 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(EnumSet.of(Modifier.PUBLIC, Modifier.STATIC)));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #28
Source File: OriginResourceIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void generateJaxRs20Filter( JavaSource javaSource ) throws IOException {
    javaSource.runModificationTask( new Task<WorkingCopy>() {
        
        @Override
        public void run( WorkingCopy  copy ) throws Exception {
            copy.toPhase(Phase.ELEMENTS_RESOLVED);
            ClassTree classTree = JavaSourceHelper.getTopLevelClassTree(copy);
            
            ClassTree newTree = classTree;
            TreeMaker treeMaker = copy.getTreeMaker();
            
            GenerationUtils genUtils = GenerationUtils.newInstance(copy);
            
            AnnotationTree provider = genUtils.
                    createAnnotation("javax.ws.rs.ext.Provider");
            newTree = genUtils.addAnnotation(newTree, provider);
            
            LinkedHashMap<String,String> params = new LinkedHashMap<String, String>();
            params.put("requestContext", 
                    "javax.ws.rs.container.ContainerRequestContext");// NOI18N
            params.put("response",
                    "javax.ws.rs.container.ContainerResponseContext");// NOI18N
            newTree = genUtils.addImplementsClause(newTree, 
                    "javax.ws.rs.container.ContainerResponseFilter");// NOI18N
            MethodTree method = AbstractJaxRsFeatureIterator.createMethod(
                    genUtils, treeMaker, "filter",params, 
                    getFilterBody(false));
            newTree = treeMaker.addClassMember( newTree, method);
            
            copy.rewrite( classTree, newTree);
        }
    }).commit();
}
 
Example #29
Source File: FindMethodRegionsVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public List<Pair<DocPositionRegion,MethodTree>> getResult () {
    //todo: threading, user of returned value should do the check
    if (canceled.get()) {
        posRegions.clear();
    }
    return posRegions;
}
 
Example #30
Source File: TranslatePositionsVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public TranslatePositionsVisitor (final MethodTree changedMethod, final EndPosTable endPos, final int delta) {
//        assert changedMethod != null;
        assert endPos != null;
        this.changedMethod = changedMethod;
        this.endPos = endPos;
        this.delta = delta;
        
        active = changedMethod == null;//hack
    }