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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: ComputeImports.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitMethod(MethodTree node, Map<String, Object> p) {
    scan(node.getModifiers(), p);
    scan(node.getTypeParameters(), p, true);
    scan(node.getReturnType(), p, true);
    scan(node.getReceiverParameter(), p);
    scan(node.getParameters(), p);
    scan(node.getThrows(), p, true);
    scan(node.getDefaultValue(), p);
    scan(node.getBody(), p);
    return null;
}
 
Example #16
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isSetter(Tree member) {
    return member.getKind() == Tree.Kind.METHOD
            && name(member).startsWith("set") //NOI18N
            && ((MethodTree)member).getParameters().size() == 1
            && ((MethodTree)member).getReturnType().getKind() == Tree.Kind.PRIMITIVE_TYPE
            && ((PrimitiveTypeTree)((MethodTree)member).getReturnType()).getPrimitiveTypeKind() == TypeKind.VOID;
}
 
Example #17
Source File: JavacParserTest.java    From openjdk-jdk8u 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 #18
Source File: RestUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static MethodTree findGetAsXmlMethod(JavaSource rSrc) {
    MethodTree method = null;
    List<MethodTree> rTrees = JavaSourceHelper.getAllMethods(rSrc);
    for (MethodTree tree : rTrees) {
        boolean isHttpGetMethod = false;
        boolean isXmlMime = false;
        List<? extends AnnotationTree> mAnons = tree.getModifiers().getAnnotations();
        if (mAnons != null && mAnons.size() > 0) {
            for (AnnotationTree mAnon : mAnons) {
                String mAnonType = mAnon.getAnnotationType().toString();
                if (RestConstants.GET_ANNOTATION.equals(mAnonType) || RestConstants.GET.equals(mAnonType)) {
                    isHttpGetMethod = true;
                } else if (RestConstants.PRODUCE_MIME_ANNOTATION.equals(mAnonType) || 
                        RestConstants.PRODUCE_MIME.equals(mAnonType)) {
                    List<String> mimes = getMimeAnnotationValue(mAnon);
                     if (mimes.contains(Constants.MimeType.JSON.value()) ||
                        mimes.contains(Constants.MimeType.XML.value())) {
                        isXmlMime = true;
                    }
                }
            }
            if (isHttpGetMethod && isXmlMime) {
                method = tree;
                break;
            }
        }
    }
    return method;
}
 
Example #19
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 #20
Source File: StreamNullabilityPropagator.java    From NullAway with MIT License 5 votes vote down vote up
private void handleMapAnonClass(
    MaplikeMethodRecord methodRecord,
    MethodInvocationTree observableDotMap,
    ClassTree annonClassBody) {
  for (Tree t : annonClassBody.getMembers()) {
    if (t instanceof MethodTree
        && ((MethodTree) t).getName().toString().equals(methodRecord.getInnerMethodName())) {
      observableCallToInnerMethodOrLambda.put(observableDotMap, t);
    }
  }
}
 
Example #21
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;
}
 
Example #22
Source File: ModifiersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Original:
 * 
 * public static void method() {
 * }
 * 
 * Result:
 * 
 * static void method() {
 * }
 */
public void testMethodMods5() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    public static void method() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    static void method() {\n" +
            "    }\n" +
            "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        
        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            
            // finally, find the correct body and rewrite it.
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ModifiersTree mods = method.getModifiers();
            workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.STATIC)));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #23
Source File: ListenerGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ClassTree generateInterfaces(WorkingCopy wc, TypeElement te, ClassTree ct, GenerationUtils gu) {
    ClassTree newClassTree = ct;

    List<String> ifList = new ArrayList<String>();
    List<ExecutableElement> methods = new ArrayList<ExecutableElement>();
    
    if (isContext) {
        ifList.add("javax.servlet.ServletContextListener");
    }
    if (isContextAttr) {
        ifList.add("javax.servlet.ServletContextAttributeListener");
    }
    if (isSession) {
        ifList.add("javax.servlet.http.HttpSessionListener");
    }
    if (isSessionAttr) {
        ifList.add("javax.servlet.http.HttpSessionAttributeListener");
    }
    if (isRequest) {
        ifList.add("javax.servlet.ServletRequestListener");
    }
    if (isRequestAttr) {
        ifList.add("javax.servlet.ServletRequestAttributeListener");
    }
    for (String ifName : ifList) {
        newClassTree = gu.addImplementsClause(newClassTree, ifName);
        TypeElement typeElement = wc.getElements().getTypeElement(ifName);
        methods.addAll(ElementFilter.methodsIn(typeElement.getEnclosedElements()));
    }

    for (MethodTree t : GeneratorUtilities.get(wc).createAbstractMethodImplementations(te, methods)) {
        newClassTree = GeneratorUtilities.get(wc).insertClassMember(newClassTree, t);
    }

    return newClassTree;
}
 
Example #24
Source File: FinalizeDoesNotCallSuper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    final TreeMaker tm = wc.getTreeMaker();
    TreePath tp = ctx.getPath();
    final BlockTree oldBody = ((MethodTree)tp.getLeaf()).getBody();
    if (oldBody == null) {
        return;
    }
    final List<StatementTree> newStatements = new ArrayList<StatementTree>(2);
    BlockTree superFinalize = tm.Block(
                                Collections.singletonList(
                                    tm.ExpressionStatement(
                                        tm.MethodInvocation(Collections.<ExpressionTree>emptyList(),
                                            tm.MemberSelect(
                                                tm.Identifier(SUPER),
                                                FINALIZE), Collections.<ExpressionTree>emptyList()))),
                                false);
    if (oldBody.getStatements().isEmpty()) {
        wc.rewrite(oldBody, superFinalize);
    } else {
        TryTree soleTry = soleTryWithoutFinally(oldBody);
        
        if (soleTry != null) {
            wc.rewrite(soleTry, tm.Try(soleTry.getBlock(), soleTry.getCatches(), superFinalize));
        } else {
            wc.rewrite(oldBody, tm.Block(Collections.singletonList(tm.Try(oldBody, Collections.<CatchTree>emptyList(), superFinalize)), false));
        }
    }
}
 
Example #25
Source File: CmFieldGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static MethodTree createSetter(WorkingCopy workingCopy, MethodModel.Variable field, Set<Modifier> modifiers) {
    MethodModel methodModel = MethodModel.create(
            "set" + Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1),
            "void",
            null,
            Collections.singletonList(MethodModel.Variable.create(field.getType(), field.getName())),
            Collections.<String>emptyList(),
            modifiers
            );
    return MethodModelSupport.createMethodTree(workingCopy, methodModel);
}
 
Example #26
Source File: AccessError.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    ModifiersTree mods;
    Tree el = ctx.getPath().getLeaf();
    
    switch (el.getKind()) {
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            mods = ((ClassTree) el).getModifiers();
            break;
        case METHOD:
            mods = ((MethodTree) el).getModifiers();
            break;
        case VARIABLE:
            mods = ((VariableTree) el).getModifiers();
            break;
        default:
            throw new IllegalStateException(el.getKind().name());
    }
    
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    
    ModifiersTree result = mods;
    
    result = make.removeModifiersModifier(result, Modifier.PUBLIC);    //should not be there, presumably...
    result = make.removeModifiersModifier(result, Modifier.PROTECTED);
    result = make.removeModifiersModifier(result, Modifier.PRIVATE);
    
    for (Modifier m : newVisibility.getRequiredModifiers()) {
        result = make.addModifiersModifier(result, m);
    }
    
    ctx.getWorkingCopy().rewrite(mods, result);
}
 
Example #27
Source File: JavacParserTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void testPositionBrokenSource126732a() throws IOException {
    String[] commands = new String[]{
        "return Runnable()",
        "do { } while (true)",
        "throw UnsupportedOperationException()",
        "assert true",
        "1 + 1",};

    for (String command : commands) {

        String code = "package test;\n"
                + "public class Test {\n"
                + "    public static void test() {\n"
                + "        " + command + " {\n"
                + "                new Runnable() {\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 =
                method.getBody().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 #28
Source File: TestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source File: ClientGenerationStrategy.java    From netbeans with Apache License 2.0 5 votes vote down vote up
MethodTree generateConstructorAuthBasic(TreeMaker maker) {
    
    ModifiersTree methodModifier = maker.Modifiers(
            Collections.<Modifier>singleton(Modifier.PUBLIC));

    List<VariableTree> paramList = new ArrayList<VariableTree>();
    
    Tree argTypeTree = maker.Identifier("String"); //NOI18N
    ModifiersTree fieldModifier = maker.Modifiers(
            Collections.<Modifier>emptySet());
    VariableTree argFieldTree = maker.Variable(fieldModifier, 
            "username", argTypeTree, null); //NOI18N
    paramList.add(argFieldTree);
    argFieldTree = maker.Variable(fieldModifier, 
            "password", argTypeTree, null); //NOI18N
    paramList.add(argFieldTree);
    
    
    String body =
            "{"+
                 "this();" +
                 "setUsernamePassword(username, password);" +
            "}"; //NOI18N
    return maker.Constructor (
            methodModifier,
            Collections.<TypeParameterTree>emptyList(),
            paramList,
            Collections.<ExpressionTree>emptyList(),
            body);
    
}
 
Example #30
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}