com.sun.source.tree.ClassTree Java Examples

The following examples show how to use com.sun.source.tree.ClassTree. 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 Project: netbeans   Author: apache   File: MemberAdditionTest.java    License: Apache License 2.0 6 votes vote down vote up
public Void visitClass(ClassTree node, Boolean p) {
    TypeElement te = (TypeElement)model.getElement(node);
    if (te != null) {
        List<Tree> members = new ArrayList<Tree>();
        for(Tree m : node.getMembers())
            members.add(m);
        members.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test", make.PrimitiveType(TypeKind.INT), null));
        ClassTree decl = make.Class(node.getModifiers(), node.getSimpleName(), node.getTypeParameters(), node.getExtendsClause(), (List<ExpressionTree>)node.getImplementsClause(), members);
        model.setElement(decl, te);
        model.setType(decl, model.getType(node));
        model.setPos(decl, model.getPos(node));
        copy.rewrite(node, decl);
    }
    
    return null;
}
 
Example #2
Source Project: netbeans   Author: apache   File: WrappingTest.java    License: 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 Project: netbeans   Author: apache   File: GeneratorUtilitiesTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testGetterNamingConvention0() throws Exception {//#165241
    performTest("package test;\npublic class Test {\nprivate int eMai;\npublic Test(){\n}\n }\n", new GetterSetterTask(34, false), new Validator() {

        public void validate(CompilationInfo info) {
            ClassTree ct = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);

            for (Tree member : ct.getMembers()) {
                if (member.getKind() == Kind.METHOD) {
                    String name = ((MethodTree) member).getName().toString();
                    if (!name.equals("<init>")) {
                        assertEquals(name, "seteMai");
                    }
                }
            }
        }
    });
}
 
Example #4
Source Project: TencentKona-8   Author: Tencent   File: NewArrayPretty.java    License: GNU General Public License v2.0 6 votes vote down vote up
void run(String code) throws IOException {
    String src = "public class Test {" + code + ";}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));

    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCVariableDecl var =
                (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);

        if (!code.equals(var.toString())) {
            System.err.println("Expected: " + code);
            System.err.println("Obtained: " + var.toString());
            throw new RuntimeException("strings do not match!");
        }
    }
}
 
Example #5
Source Project: netbeans   Author: apache   File: JavaFixUtilitiesTest.java    License: Apache License 2.0 6 votes vote down vote up
private void performArithmeticTest(String orig, String nue) throws Exception {
    String code = replace("0");

    prepareTest("Test.java", code);
    ClassTree clazz = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);
    VariableTree variable = (VariableTree) clazz.getMembers().get(1);
    ExpressionTree init = variable.getInitializer();
    TreePath tp = new TreePath(new TreePath(new TreePath(new TreePath(info.getCompilationUnit()), clazz), variable), init);
    Fix fix = JavaFixUtilities.rewriteFix(info, "A", tp, orig, Collections.<String, TreePath>emptyMap(), Collections.<String, Collection<? extends TreePath>>emptyMap(), Collections.<String, String>emptyMap(), Collections.<String, TypeMirror>emptyMap(), Collections.<String, String>emptyMap());
    fix.implement();

    String golden = replace(nue);
    String out = doc.getText(0, doc.getLength());

    assertEquals(golden, out);

    LifecycleManager.getDefault().saveAll();
}
 
Example #6
Source Project: annotation-tools   Author: typetools   File: LocalClassScanner.java    License: MIT License 6 votes vote down vote up
@Override
public Void visitBlock(BlockTree node, Integer level) {
  if (level < 1) {
    // Visit blocks since a local class can only be in a block. Then visit each
    // statement of the block to see if any are the correct local class.
    for (StatementTree statement : node.getStatements()) {
      if (!found && statement.getKind() == Tree.Kind.CLASS) {
        ClassTree c = (ClassTree) statement;
        if (localClass == statement) {
          found = true;
        } else if (c.getSimpleName().equals(localClass.getSimpleName())) {
          index++;
        }
      }
    }
    super.visitBlock(node, level + 1);
  }
  return null;
}
 
Example #7
Source Project: netbeans   Author: apache   File: ClassEncapsulation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChangeInfo implement() throws Exception {
    final FileObject file = handle.getFileObject();
    final JTextComponent component = EditorRegistry.lastFocusedComponent();
    if (file != null && file == getFileObject(component)) {
        final int[] position = new int[] {-1};
        JavaSource.forFileObject(file).runUserActionTask(new Task<CompilationController>() {
            @Override
            public void run(CompilationController controller) throws Exception {
                controller.toPhase(JavaSource.Phase.PARSED);
                final TreePath tp = handle.resolve(controller);
                if (tp != null && TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
                    position[0] = (int) controller.getTrees().getSourcePositions().getStartPosition(
                            tp.getCompilationUnit(),
                            (ClassTree)tp.getLeaf())+1;
                }
            }
        }, true);
        invokeRefactoring(component, position[0]);
    }
    return null;
}
 
Example #8
Source Project: netbeans   Author: apache   File: GeneratorUtilities.java    License: 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 #9
Source Project: netbeans   Author: apache   File: InsertTask.java    License: Apache License 2.0 6 votes vote down vote up
private ClassTree modifyJavaClass( WorkingCopy workingCopy,
        TreeMaker make, ClassTree javaClass, TypeElement classElement )
{
    Collection<String> existingImports = getImports(workingCopy);
    CompilationUnitTree original = workingCopy.getCompilationUnit();
    CompilationUnitTree modified = original;
    for (String imp : manager.getImports()) {
        if (!existingImports.contains(imp)) {
            modified = make.addCompUnitImport(
                    modified, make.Import(make.Identifier(imp), false));
        }
    }
    workingCopy.rewrite(original, modified);
    return insertSecurityFetaureField(workingCopy, make, javaClass, 
            classElement);
}
 
Example #10
Source Project: openjdk-8-source   Author: keerath   File: JavacParserTest.java    License: 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 Project: java-n-IDE-for-Android   Author: shenghuntianlang   File: Trees.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the enclosing type declaration (class, enum, interface, or annotation) for the given
 * path.
 */
static ClassTree getEnclosingTypeDeclaration(TreePath path) {
    for (; path != null; path = path.getParentPath()) {
        switch (path.getLeaf().getKind()) {
            case CLASS:
            case ENUM:
            case INTERFACE:
                // TODO: 22-Jul-17 wrong??
            case ANNOTATION_TYPE:
                return (ClassTree) path.getLeaf();
            default:
                break;
        }
    }
    throw new AssertionError();
}
 
Example #12
Source Project: netbeans   Author: apache   File: AnnotationAsSuperInterface.java    License: Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static Iterable<ErrorDescription> run(HintContext ctx) {
    Element e = ctx.getInfo().getTrees().getElement(ctx.getPath());

    if ( e == null || !(e instanceof TypeElement) ) {
        return null;
    }
    
    List<ErrorDescription> eds = new ArrayList<ErrorDescription>();
    
    for (Tree i : ((ClassTree) ctx.getPath().getLeaf()).getImplementsClause()) {
        Element ie = ctx.getInfo().getTrees().getElement(new TreePath(ctx.getPath(), i));

        if (ie != null && ie.getKind() == ElementKind.ANNOTATION_TYPE) {
            eds.add(ErrorDescriptionFactory.forTree(ctx, i, NbBundle.getMessage(AnnotationAsSuperInterface.class,
                                "HNT_AnnotationAsSuperInterface",  // NOI18N
                                ie.getSimpleName().toString())));
        }
    }

    return eds;
}
 
Example #13
Source Project: netbeans   Author: apache   File: CreateElementUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeClass(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ClassTree ct = (ClassTree) parent.getLeaf();
    
    if (ct.getExtendsClause() == error) {
        types.add(ElementKind.CLASS);
        return null;
    }
    
    for (Tree t : ct.getImplementsClause()) {
        if (t == error) {
            types.add(ElementKind.INTERFACE);
            return null;
        }
    }
    
    //XXX: annotation types...
    
    return null;
}
 
Example #14
Source Project: netbeans   Author: apache   File: BreadCrumbsNodeImpl.java    License: Apache License 2.0 6 votes vote down vote up
private static String className(TreePath path) {
    ClassTree ct = (ClassTree) path.getLeaf();
    
    if (path.getParentPath().getLeaf().getKind() == Kind.NEW_CLASS) {
        NewClassTree nct = (NewClassTree) path.getParentPath().getLeaf();
        
        if (nct.getClassBody() == ct) {
            return simpleName(nct.getIdentifier());
        }
    } else if (path.getParentPath().getLeaf() == path.getCompilationUnit()) {
        ExpressionTree pkg = path.getCompilationUnit().getPackageName();
        String pkgName = pkg != null ? pkg.toString() : null;
        if (pkgName != null && !pkgName.contentEquals(ERR_NAME)) {
            return pkgName + '.' + ct.getSimpleName().toString();
        }
    }
    
    return ct.getSimpleName().toString();
}
 
Example #15
Source Project: netbeans   Author: apache   File: AbstractMethodGenerator.java    License: 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 #16
Source Project: netbeans   Author: apache   File: ApplicationSubclassGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private ClassTree createMethods(Collection<String> classNames, MethodTree getClasses,
        TreeMaker maker, ClassTree modified,
        CompilationController controller) throws IOException
{
    WildcardTree wildCard = maker.Wildcard(Tree.Kind.UNBOUNDED_WILDCARD,
            null);
    ParameterizedTypeTree wildClass = maker.ParameterizedType(
            maker.QualIdent(Class.class.getCanonicalName()),
            Collections.singletonList(wildCard));
    ParameterizedTypeTree wildSet = maker.ParameterizedType(
            maker.QualIdent(Set.class.getCanonicalName()),
            Collections.singletonList(wildClass));

    String methodBody = MiscPrivateUtilities.collectRestResources(classNames, restSupport, false);
    
    return MiscUtilities.createAddResourceClasses(maker, modified, controller, methodBody, false);
}
 
Example #17
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: JavacParserTest.java    License: 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 #18
Source Project: hottub   Author: dsrg-uoft   File: NewArrayPretty.java    License: GNU General Public License v2.0 6 votes vote down vote up
void run(String code) throws IOException {
    String src = "public class Test {" + code + ";}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));

    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCVariableDecl var =
                (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);

        if (!code.equals(var.toString())) {
            System.err.println("Expected: " + code);
            System.err.println("Obtained: " + var.toString());
            throw new RuntimeException("strings do not match!");
        }
    }
}
 
Example #19
Source Project: netbeans   Author: apache   File: ComputeImports.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Void visitClass(ClassTree node, Map<String, Object> p) {
    if (getCurrentPath().getParentPath().getLeaf().getKind() != Kind.NEW_CLASS) {
        filterByAcceptedKind(node.getExtendsClause(), ElementKind.CLASS);
        for (Tree intf : node.getImplementsClause()) {
            filterByAcceptedKind(intf, ElementKind.INTERFACE, ElementKind.ANNOTATION_TYPE);
        }
    }

    scan(node.getModifiers(), p);
    scan(node.getTypeParameters(), p, true);
    scan(node.getExtendsClause(), p, true);
    scan(node.getImplementsClause(), p, true);
    scan(node.getMembers(), p);

    return null;
}
 
Example #20
Source Project: besu   Author: hyperledger   File: MethodInputParametersMustBeFinal.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Description matchClass(final ClassTree tree, final VisitorState state) {
  isAbstraction =
      isInterface(tree.getModifiers())
          || isAnonymousClassInAbstraction(tree)
          || isEnumInAbstraction(tree);
  return Description.NO_MATCH;
}
 
Example #21
Source Project: netbeans   Author: apache   File: ClassScanner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TypeElement visitClass(ClassTree arg0, Void arg1) {
    TypeElement typeElement = (TypeElement) trees.getElement(getCurrentPath());
    if (typeElement == null) {
        return super.visitClass(arg0, arg1);
    }
    String binaryName = elements.getBinaryName(typeElement).toString();
    if (match(binaryName)) {
        return typeElement;
    } else {
        return super.visitClass(arg0, arg1);
    }
}
 
Example #22
Source Project: netbeans   Author: apache   File: SourceUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A convenience method for converting a <code>ClassTree</code> to the 
 * corresponding <code>TypeElement</code>, if any.
 */
static TypeElement classTree2TypeElement(CompilationController controller, ClassTree classTree) {
    assert controller != null;
    assert classTree != null;

    TreePath classTreePath = controller.getTrees().getPath(controller.getCompilationUnit(), classTree);
    return (TypeElement)controller.getTrees().getElement(classTreePath);
}
 
Example #23
Source Project: NullAway   Author: uber   File: AccessPathNullnessPropagation.java    License: MIT License 5 votes vote down vote up
/**
 * @param classTree a class
 * @return the nullness info of locals in the enclosing environment for the closest enclosing
 *     local or anonymous class. if no such class, returns an empty {@link NullnessStore}
 */
private NullnessStore getEnvNullnessStoreForClass(ClassTree classTree) {
  NullnessStore envStore = NullnessStore.empty();
  ClassTree enclosingLocalOrAnonymous = findEnclosingLocalOrAnonymousClass(classTree);
  if (enclosingLocalOrAnonymous != null) {
    EnclosingEnvironmentNullness environmentNullness =
        EnclosingEnvironmentNullness.instance(context);
    envStore =
        Objects.requireNonNull(
            environmentNullness.getEnvironmentMapping(enclosingLocalOrAnonymous));
  }
  return envStore;
}
 
Example #24
Source Project: netbeans   Author: apache   File: ClassStructure.java    License: Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.classMayBeInterface", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.classMayBeInterface", category = "class_structure", enabled = false, suppressWarnings = {"ClassMayBeInterface"}, options=Options.NO_BATCH) //NOI18N
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static ErrorDescription classMayBeInterface(HintContext context) {
    final ClassTree cls = (ClassTree) context.getPath().getLeaf();
    final TreeUtilities treeUtilities = context.getInfo().getTreeUtilities();
    if (treeUtilities.isClass(cls) && testClassMayBeInterface(context.getInfo().getTrees(), treeUtilities, context.getPath())) {
        return ErrorDescriptionFactory.forName(context, cls, NbBundle.getMessage(ClassStructure.class, "MSG_ClassMayBeInterface", cls.getSimpleName()), //NOI18N
                new ConvertClassToInterfaceFixImpl(TreePathHandle.create(context.getPath(), context.getInfo()), NbBundle.getMessage(ClassStructure.class, "FIX_ConvertClassToInterface", cls.getSimpleName())).toEditorFix()); //NOI18N
    }
    return null;
}
 
Example #25
Source Project: hottub   Author: dsrg-uoft   File: T6404194.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1          2          3
            //      01234567890123456 7890 123456789012345
            return "@SuppressWarning(\"foo\") @Deprecated class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null, compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    ClassTree classTree = (ClassTree)toplevel.getTypeDecls().get(0);
    List<? extends Tree> annotations = classTree.getModifiers().getAnnotations();
    Tree tree1 = annotations.get(0);
    Tree tree2 = annotations.get(1);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree1);
    if (pos != 0)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree1);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree1, pos));
    pos = trees.getSourcePositions().getStartPosition(toplevel, tree2);
    if (pos != 24)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree2, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree2);
    if (pos != 35)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree2, pos));
}
 
Example #26
Source Project: netbeans   Author: apache   File: JavaxFacesBeanIsGonnaBeDeprecated.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    WorkingCopy wc = ctx.getWorkingCopy();
    wc.toPhase(JavaSource.Phase.RESOLVED);
    TreeMaker make = wc.getTreeMaker();

    // rewrite annotations in case of ManagedBean
    if (MANAGED_BEAN.equals(annotation.getAnnotationType().toString())) {
        ModifiersTree modifiers = ((ClassTree) wc.getTrees().getTree(element)).getModifiers();
        AnnotationTree annotationTree = (AnnotationTree) wc.getTrees().getTree(element, annotation);
        List<ExpressionTree> arguments = new ArrayList<>();
        for (ExpressionTree expressionTree : annotationTree.getArguments()) {
            if (expressionTree.getKind() == Tree.Kind.ASSIGNMENT) {
                AssignmentTree at = (AssignmentTree) expressionTree;
                String varName = ((IdentifierTree) at.getVariable()).getName().toString();
                if (varName.equals("name")) { //NOI18N
                    ExpressionTree valueTree = make.Identifier(at.getExpression().toString());
                    arguments.add(valueTree);
                }
            }
        }
        ModifiersTree newModifiersTree = make.removeModifiersAnnotation(modifiers, (AnnotationTree) wc.getTrees().getTree(element, annotation));
        AnnotationTree newTree = GenerationUtils.newInstance(wc).createAnnotation(replacingClass, arguments);
        newModifiersTree = make.addModifiersAnnotation(newModifiersTree, newTree);
        wc.rewrite(modifiers, newModifiersTree);
    }

    // rewrite imports
    List<? extends ImportTree> imports = wc.getCompilationUnit().getImports();
    ImportTree newImportTree = make.Import(make.QualIdent(replacingClass), false);
    for (ImportTree importTree : imports) {
        if (deprecatedClass.equals(importTree.getQualifiedIdentifier().toString())) {
            wc.rewrite(importTree, newImportTree);
        }
    }

}
 
Example #27
Source Project: netbeans   Author: apache   File: EntityResourcesGenerator.java    License: Apache License 2.0 5 votes vote down vote up
protected ModifiersTree addResourceAnnotation(
        final String entityFQN, ClassTree classTree,
        GenerationUtils genUtils, TreeMaker maker )
{
    // Add @Path annotation to REST resource class
    ExpressionTree resourcePath = maker.Literal(entityFQN.toLowerCase());
    ModifiersTree modifiersTree = classTree.getModifiers();
    modifiersTree =
            maker.addModifiersAnnotation(modifiersTree, 
                    genUtils.createAnnotation(RestConstants.PATH, 
                            Collections.<ExpressionTree>singletonList(
                                    resourcePath)));
    return modifiersTree;
}
 
Example #28
Source Project: netbeans   Author: apache   File: LabelsTest.java    License: Apache License 2.0 5 votes vote down vote up
public Void visitClass(ClassTree node, Object p) {
    System.err.println("visitClass: " + node.getSimpleName());
    super.visitClass(node, p);
    ClassTree copy = make.setLabel(node, node.getSimpleName() + "0");
    this.copy.rewrite(node, copy);
    return null;
}
 
Example #29
Source Project: TencentKona-8   Author: Tencent   File: TypeAnnotationsPretty.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void runMethod(String code) throws IOException {
    String src = prefix +
            code + "}" +
            postfix;

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));


    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCMethodDecl meth =
                (JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
        checkMatch(code, meth);
    }
}
 
Example #30
Source Project: TencentKona-8   Author: Tencent   File: T6402077.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2
            //      0123456789012345678901234
            return "class Test { Test() { } }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask)javac.getTask(null, null, null, null, null,
                                              compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    Tree tree = ((ClassTree)toplevel.getTypeDecls().get(0)).getMembers().get(0);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree);
    if (pos != 13)
        throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!",
                                               tree, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree);
    if (pos != 23)
        throw new AssertionError(String.format("End pos for %s is incorrect (%s)!",
                                               tree, pos));
}