com.sun.source.tree.ModifiersTree Java Examples

The following examples show how to use com.sun.source.tree.ModifiersTree. 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 TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPositionForEnumModifiers() throws IOException {
    final String theString = "public";
    String code = "package test; " + theString + " enum Test {A;}";

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

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ModifiersTree mt = clazz.getModifiers();
    int spos = code.indexOf(theString);
    int epos = spos + theString.length();
    assertEquals("testPositionForEnumModifiers",
            spos, pos.getStartPosition(cut, mt));
    assertEquals("testPositionForEnumModifiers",
            epos, pos.getEndPosition(cut, mt));
}
 
Example #2
Source File: AsyncConverter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ClassTree moveRestMethod( TreeMaker maker, String movedName,
        MethodTree method, WorkingCopy copy, ClassTree classTree)
{
    List<? extends VariableTree> parameters = method.getParameters();
    Tree returnType = method.getReturnType();
    BlockTree body = method.getBody();  
    
    ModifiersTree modifiers = maker.Modifiers(EnumSet.of(Modifier.PRIVATE));
    MethodTree newMethod = maker.Method(modifiers, movedName, 
            returnType,
            Collections.<TypeParameterTree> emptyList(),
            parameters,
            Collections.<ExpressionTree> emptyList(),body,null);
    
    ClassTree newClass = maker.addClassMember(classTree, newMethod);
    newClass = maker.removeClassMember(newClass, method);
    return newClass;
}
 
Example #3
Source File: TestGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 */
@Override
protected ClassTree composeNewTestClass(WorkingCopy workingCopy,
                                        String name,
                                        List<? extends Tree> members) {
    final TreeMaker maker = workingCopy.getTreeMaker();
    ModifiersTree modifiers = maker.Modifiers(
                                  Collections.<Modifier>singleton(PUBLIC));
    return maker.Class(
                modifiers,                                 //modifiers
                name,                                      //name
                Collections.<TypeParameterTree>emptyList(),//type params
                null,                                      //extends
                Collections.<ExpressionTree>emptyList(),   //implements
                members);                                  //members
}
 
Example #4
Source File: ClassStructure.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    GeneratorUtilities gu = GeneratorUtilities.get(wc);
    TreePath path = ctx.getPath();
    final ClassTree cls = (ClassTree) path.getLeaf();
    gu.importComments(cls, wc.getCompilationUnit());
    final TreeMaker treeMaker = wc.getTreeMaker();
    ModifiersTree mods = cls.getModifiers();
    if (mods.getFlags().contains(Modifier.ABSTRACT)) {
        Set<Modifier> modifiers = EnumSet.copyOf(mods.getFlags());
        modifiers.remove(Modifier.ABSTRACT);
        ModifiersTree nmods = treeMaker.Modifiers(modifiers, mods.getAnnotations());
        gu.copyComments(mods, nmods, true);
        gu.copyComments(mods, nmods, false);
        mods = nmods;
    }
    Tree nue = treeMaker.Interface(mods, cls.getSimpleName(), cls.getTypeParameters(), cls.getImplementsClause(), cls.getMembers());
    gu.copyComments(cls, nue, true);
    gu.copyComments(cls, nue, false);
    wc.rewrite(path.getLeaf(), nue);
}
 
Example #5
Source File: JaxWsServiceCreator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private VariableTree generateEjbInjection(WorkingCopy workingCopy, TreeMaker make, String beanInterface, boolean[] onClassPath) {

        TypeElement ejbAnElement = workingCopy.getElements().getTypeElement("javax.ejb.EJB"); //NOI18N
        TypeElement interfaceElement = workingCopy.getElements().getTypeElement(beanInterface); //NOI18N

        AnnotationTree ejbAnnotation = make.Annotation(
                make.QualIdent(ejbAnElement),
                Collections.<ExpressionTree>emptyList());
        // create method modifier: public and no annotation
        ModifiersTree methodModifiers = make.Modifiers(
                Collections.<Modifier>singleton(Modifier.PRIVATE),
                Collections.<AnnotationTree>singletonList(ejbAnnotation));

        onClassPath[0] = interfaceElement != null;

        return make.Variable(
                methodModifiers,
                "ejbRef", //NOI18N
                onClassPath[0] ? make.Type(interfaceElement.asType()) : make.Identifier(beanInterface),
                null);
    }
 
Example #6
Source File: ApplicationSubclassGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ClassTree createMethodsOlderVersion(Collection<String> classNames,
        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));
    //StringBuilder builder = new StringBuilder();
    String methodBody = MiscPrivateUtilities.collectRestResources(classNames, restSupport, true);
    ModifiersTree modifiersTree = maker.Modifiers(EnumSet
            .of(Modifier.PRIVATE));
    MethodTree methodTree = maker.Method(modifiersTree,
            GET_REST_RESOURCE_CLASSES, wildSet,
            Collections.<TypeParameterTree> emptyList(),
            Collections.<VariableTree> emptyList(),
            Collections.<ExpressionTree> emptyList(), methodBody,
            null);
    modified = maker.addClassMember(modified, methodTree);
    return modified;
}
 
Example #7
Source File: JUnit5TestGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 */
@Override
protected ClassTree composeNewTestClass(WorkingCopy workingCopy,
                                        String name,
                                        List<? extends Tree> members) {
    final TreeMaker maker = workingCopy.getTreeMaker();
    ModifiersTree modifiers = maker.Modifiers(
                                  Collections.<Modifier>singleton(PUBLIC));
    return maker.Class(
                modifiers,                                 //modifiers
                name,                                      //name
                Collections.<TypeParameterTree>emptyList(),//type params
                null,                                      //extends
                Collections.<ExpressionTree>emptyList(),   //implements
                members);                                  //members
}
 
Example #8
Source File: CodeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ModifiersTree computeMods(Element e) {
    Set<Modifier> implicitModifiers = IMPLICIT_MODIFIERS.get(Arrays.asList(e.getKind()));

    if (implicitModifiers == null) {
        implicitModifiers = IMPLICIT_MODIFIERS.get(Arrays.asList(e.getKind(), e.getEnclosingElement().getKind()));
    }

    Set<Modifier> modifiers = EnumSet.noneOf(Modifier.class);

    modifiers.addAll(e.getModifiers());

    if (implicitModifiers != null) {
        modifiers.removeAll(implicitModifiers);
    }

    List<AnnotationTree> annotations = new LinkedList<AnnotationTree>();

    for (AnnotationMirror m : e.getAnnotationMirrors()) {
        annotations.add(computeAnnotationTree(m));
    }

    return make.Modifiers(modifiers, annotations);
}
 
Example #9
Source File: MakeClassPublic.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ChangeInfo implement(){
    CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>(){
        public void cancel() {}
        
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TypeElement clazz = classHandle.resolve(workingCopy);
            
            if (clazz != null){    
                ClassTree clazzTree = workingCopy.getTrees().getTree(clazz);
                TreeMaker make = workingCopy.getTreeMaker();
                
                Set<Modifier> flags = new HashSet<Modifier>(clazzTree.getModifiers().getFlags());
                flags.add(Modifier.PUBLIC);
                ModifiersTree newModifiers = make.Modifiers(flags, clazzTree.getModifiers().getAnnotations());
                workingCopy.rewrite(clazzTree.getModifiers(), newModifiers);
            }
        }
    };
    
    JavaSource javaSource = JavaSource.forFileObject(fileObject);
    
    try{
        javaSource.runModificationTask(task).commit();
    } catch (IOException e){
        JPAProblemFinder.LOG.log(Level.SEVERE, e.getMessage(), e);
    }
    return null;
}
 
Example #10
Source File: GenerationUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new field.
 *
 * @param  scope the scope in which to create the field (will be e.g. used
 *         to parse <code>fieldType</code>).
 * @param  modifiersTree the field modifiers; cannot be null.
 * @param  fieldType the fully-qualified name of the field type; cannot be null.
 * @param  fieldName the field name; cannot be null.
 * @param  expressionTree expression to initialize the field; can be null.
 * @return the new field; never null.
 */
public VariableTree createField(TypeElement scope, ModifiersTree modifiersTree, String fieldName, String fieldType, ExpressionTree expressionTree) {
    Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
    Parameters.javaIdentifier("fieldName", fieldName); // NOI18N
    Parameters.notNull("fieldType", fieldType); // NOI18N

    return getTreeMaker().Variable(
            modifiersTree,
            fieldName,
            createType(fieldType, scope),
            expressionTree);
}
 
Example #11
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitModifiers(ModifiersTree expected, Tree actual) {
  Optional<ModifiersTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  checkForDiff(expected.getFlags().equals(other.get().getFlags()),
      "Expected modifier set to be <%s> but was <%s>.",
      expected.getFlags(), other.get().getFlags());

  parallelScan(expected.getAnnotations(), other.get().getAnnotations());
  return null;
}
 
Example #12
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
/** Output combined modifiers and annotations and the trailing break. */
void visitAndBreakModifiers(
    ModifiersTree modifiers,
    Direction annotationDirection,
    Optional<BreakTag> declarationAnnotationBreak) {
  builder.addAll(visitModifiers(modifiers, annotationDirection, declarationAnnotationBreak));
}
 
Example #13
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Output combined modifiers and annotations and returns the trailing break.
 */
private List<Op> visitModifiers(
        ModifiersTree modifiersTree,
        Direction annotationsDirection,
        Optional<BreakTag> declarationAnnotationBreak) {
    return visitModifiers(
            modifiersTree.getAnnotations(),
            annotationsDirection,
            declarationAnnotationBreak);
}
 
Example #14
Source File: MakeClassPublic.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public ChangeInfo implement() {
    CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>() {
        @Override
        public void cancel() {
        }

        @Override
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TypeElement clazz = classHandle.resolve(workingCopy);

            if (clazz != null) {
                ClassTree clazzTree = workingCopy.getTrees().getTree(clazz);
                TreeMaker make = workingCopy.getTreeMaker();

                Set<Modifier> flags = new HashSet<>(clazzTree.getModifiers().getFlags());
                flags.add(Modifier.PUBLIC);
                ModifiersTree newModifiers = make.Modifiers(flags, clazzTree.getModifiers().getAnnotations());
                workingCopy.rewrite(clazzTree.getModifiers(), newModifiers);
            }
        }
    };

    JavaSource javaSource = JavaSource.forFileObject(fileObject);

    try {
        javaSource.runModificationTask(task).commit();
    } catch (IOException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
    }
    return null;
}
 
Example #15
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Output combined modifiers and annotations and the trailing break.
 */
void visitAndBreakModifiers(
        ModifiersTree modifiers,
        Direction annotationDirection,
        Optional<BreakTag> declarationAnnotationBreak) {
    builder.addAll(visitModifiers(modifiers, annotationDirection, declarationAnnotationBreak));
}
 
Example #16
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Should a field with a set of modifiers be declared with horizontal annotations? This is
 * currently true if all annotations are marker annotations.
 */
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
    for (AnnotationTree annotation : modifiers.getAnnotations()) {
        if (!annotation.getArguments().isEmpty()) {
            return Direction.VERTICAL;
        }
    }
    return Direction.HORIZONTAL;
}
 
Example #17
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertAnnotationTypeDeclaration(ClassTree node, TreePath parent) {
  AnnotationTypeDeclaration newNode = new AnnotationTypeDeclaration();
  TreePath path = getTreePath(parent, node);
  Element element = getElement(path);
  convertBodyDeclaration(node, path, node.getModifiers(), newNode);
  for (Tree bodyDecl : node.getMembers()) {
    if (bodyDecl.getKind() == Kind.METHOD) {
      MethodTree methodTree = (MethodTree) bodyDecl;
      TreePath methodPath = getTreePath(path, methodTree);
      ExecutableElement methodElement = (ExecutableElement) getElement(methodPath);
      Tree defaultValue = methodTree.getDefaultValue();
      ModifiersTree modifiers = methodTree.getModifiers();
      AnnotationTypeMemberDeclaration newMember =
          new AnnotationTypeMemberDeclaration()
              .setDefault((Expression) convert(defaultValue, methodPath))
              .setExecutableElement(methodElement);
      newMember
          .setModifiers((int) ((JCModifiers) modifiers).flags)
          .setAnnotations(convertAnnotations(modifiers, getTreePath(methodPath, modifiers)))
          .setJavadoc((Javadoc) getAssociatedJavaDoc(methodTree, methodPath));
      newNode.addBodyDeclaration(newMember);
    } else {
      newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl, path));
    }
  }
  return newNode
      .setName(convertSimpleName(element, getTypeMirror(path), getNamePosition(node)))
      .setTypeElement((TypeElement) element);
}
 
Example #18
Source File: ApplicationManagedResourceTransactionInjectableInWeb.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ClassTree generate() {
    
    ClassTree modifiedClazz = getClassTree();
    String body = "";
    
    FieldInfo em = getEntityManagerFieldInfo();
    if (!em.isExisting()){
        FieldInfo emf = getEntityManagerFactoryFieldInfo();
        if (!emf.isExisting()){
            modifiedClazz = getTreeMaker().insertClassMember(getClassTree(), getIndexForField(getClassTree()), createEntityManagerFactory(emf.getName()));
        }
        body += getEmInitCode(em, emf);
    }
    
    body += getMethodBody(em);
    
    ModifiersTree methodModifiers = getTreeMaker().Modifiers(
            getGenerationOptions().getModifiers(),
            Collections.<AnnotationTree>emptyList()
            );
    
    MethodTree newMethod = getTreeMaker().Method(
            methodModifiers,
            computeMethodName(),
            getTreeMaker().PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            getParameterList(),
            Collections.<ExpressionTree>emptyList(),
            "{ " + body + "}",
            null
            );
    
    return getTreeMaker().addClassMember(modifiedClazz, importFQNs(newMethod));
}
 
Example #19
Source File: JpaControllerUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static ClassTree addVariable(ClassTree classTree, WorkingCopy wc, String name, TypeInfo type, int modifiers, Object initializer, AnnotationInfo[] annotations) {
    Tree typeTree = createType(wc, type);
    ModifiersTree modTree = createModifiers(wc, modifiers, annotations);
    TreeMaker make = wc.getTreeMaker();
    VariableTree tree = make.Variable(modTree, name, typeTree, make.Literal(initializer));
    return make.addClassMember(classTree, tree);
}
 
Example #20
Source File: InsertTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ClassTree insertSecurityFetaureField(WorkingCopy workingCopy,
        TreeMaker make, ClassTree javaClass, TypeElement classElement )
{
    for (VariableElement var : 
        ElementFilter.fieldsIn( classElement.getEnclosedElements())) 
    {
        TypeMirror varType = var.asType();
        if (!varType.getKind().equals(TypeKind.ARRAY)) {
            continue;
        }
        if ( var.getSimpleName().contentEquals(PolicyManager.SECURITY_FEATURE)) {
            /*
             * there is no way to find existing comments. So if field is
             * already in the class. Just return
             */
            return javaClass;
        }
    }
    Set<Modifier> modifiers = new HashSet<Modifier>();
    modifiers.add( Modifier.PRIVATE);
    modifiers.add( Modifier.STATIC);
    modifiers.add( Modifier.FINAL);
    
    ModifiersTree modifiersTree = make.Modifiers(
            modifiers);
    
    Tree typeTree = manager.createSecurityFeatureType( workingCopy , make );
    ExpressionTree initializer = manager.createSecurityFeatureInitializer( 
            workingCopy, make );
    VariableTree securityFeature = make.Variable(
            modifiersTree, PolicyManager.SECURITY_FEATURE,      
            typeTree,
            initializer);
    if ( manager.isSupported() ){
        manager.modifySecurityFeatureAttribute( securityFeature , workingCopy , 
            make );
    }
    return make.insertClassMember(javaClass, 0, securityFeature);
}
 
Example #21
Source File: IntroduceMethodFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private MethodTree createMethodDefinition(boolean mustStatic) {
    // if all the statements are contained within a Block, get just the block, it will be processed recursively
    List<VariableTree> formalArguments = IntroduceHint.createVariables(copy, parameters, pathToClass, 
            statementPaths.subList(from, to + 1));
    if (formalArguments == null) {
        return null; //XXX
    }
    List<ExpressionTree> thrown = IntroduceHint.typeHandleToTree(copy, thrownTypes);
    if (thrown == null) {
        return null; //XXX
    }
    List<TypeParameterTree> typeVars = new LinkedList<TypeParameterTree>();
    for (TreePathHandle tph : IntroduceMethodFix.this.typeVars) {
        typeVars.add((TypeParameterTree) tph.resolve(copy).getLeaf());
    }
    List<StatementTree> methodStatements = new ArrayList<StatementTree>();
    generateMethodContents(methodStatements);
    makeReturnsFromExtractedMethod(methodStatements);
    
    Set<Modifier> modifiers = EnumSet.noneOf(Modifier.class);
    modifiers.addAll(access);
    
    if (target.iface) {
        modifiers.add(Modifier.DEFAULT);
    } else if (mustStatic) {
        modifiers.add(Modifier.STATIC);
    }
    ModifiersTree mods = make.Modifiers(modifiers);
    MethodTree method = make.Method(mods, name, returnTypeTree, typeVars, formalArguments, thrown, make.Block(methodStatements, false), null);
    
    return method;
}
 
Example #22
Source File: ToStringGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static MethodTree createToStringMethod(WorkingCopy wc, Iterable<? extends VariableElement> fields, String typeName, boolean useStringBuilder) {
    TreeMaker make = wc.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    List<AnnotationTree> annotations = new LinkedList<>();
    if (GeneratorUtils.supportsOverride(wc)) {
        TypeElement override = wc.getElements().getTypeElement("java.lang.Override"); //NOI18N
        if (override != null) {
            annotations.add(wc.getTreeMaker().Annotation(wc.getTreeMaker().QualIdent(override), Collections.<ExpressionTree>emptyList()));
        }
    }
    ModifiersTree modifiers = make.Modifiers(mods, annotations);
    BlockTree body = createToStringMethodBody(make, typeName, fields, useStringBuilder);
    return make.Method(modifiers, "toString", make.Identifier("String"), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N
}
 
Example #23
Source File: WorkingCopy.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves all fields that belong to the same field group. 
 */
private static @NonNull List<? extends Tree> collectFieldGroup(@NonNull CompilationInfo info, 
        @NonNull TreePath parentPath, Tree leaf) {
    Iterable<? extends Tree> children;

    switch (parentPath.getLeaf().getKind()) {
        case BLOCK: children = ((BlockTree) parentPath.getLeaf()).getStatements(); break;
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            children = ((ClassTree) parentPath.getLeaf()).getMembers(); break;
        case CASE:  children = ((CaseTree) parentPath.getLeaf()).getStatements(); break;
        default:    children = Collections.singleton(leaf); break;
    }

    List<Tree> result = new LinkedList<>();
    ModifiersTree currentModifiers = ((VariableTree) leaf).getModifiers();

    for (Tree c : children) {
        if (c.getKind() != Kind.VARIABLE) continue;

        if (((VariableTree) c).getModifiers() == currentModifiers) {
            result.add(c);
        }
    }
    
    return result;
}
 
Example #24
Source File: JavaxFacesBeanIsGonnaBeDeprecated.java    From netbeans with 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 #25
Source File: GenerationUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public MethodTree createConstructor(ModifiersTree modifiersTree, String constructorName, List parameters, String body) {
    Parameters.notNull("modifiersTree", modifiersTree);
    Parameters.javaIdentifier("constructorName", constructorName); // NOI18N
    Parameters.notNull("parameters", parameters); // NOI18N

    TreeMaker make = getTreeMaker();
    return make.Constructor(
            modifiersTree,
            Collections.<TypeParameterTree>emptyList(),
            parameters,
            Collections.<ExpressionTree>emptyList(),
            body);
}
 
Example #26
Source File: ModifiersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Original:
 * 
 * public static void method() {
 * }
 * 
 * Result:
 * 
 * void method() {
 * }
 */
public void testMethodMods2() 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" +
            "    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>emptySet()));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #27
Source File: ModifiersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Original:
 * 
 * public Test() {
 * }
 * 
 * Result:
 * 
 * Test() {
 * }
 */
public void testMethodMods4() 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 Test() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    Test() {\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(0);
            ModifiersTree mods = method.getModifiers();
            workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>emptySet()));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #28
Source File: ModifiersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Original:
 * 
 * public Test() {
 * }
 * 
 * Result:
 * 
 * protected Test() {
 * }
 */
public void testMethodMods6() 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 Test() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    protected Test() {\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(0);
            ModifiersTree mods = method.getModifiers();
            workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.PROTECTED)));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #29
Source File: SpringEntityResourcesGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected ModifiersTree addResourceAnnotation( String entityFQN,
        ClassTree classTree, GenerationUtils genUtils, TreeMaker maker )
{
    ModifiersTree tree = super.addResourceAnnotation(entityFQN, classTree, 
            genUtils, maker);
    
    tree = maker.addModifiersAnnotation( tree, genUtils.createAnnotation(
            RestConstants.SINGLETON));
    tree = maker.addModifiersAnnotation( tree, genUtils.createAnnotation(
            SpringConstants.AUTOWIRE));
    return tree;
}
 
Example #30
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Should a field with a set of modifiers be declared with horizontal annotations? This is
 * currently true if all annotations are marker annotations.
 */
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
    for (AnnotationTree annotation : modifiers.getAnnotations()) {
        if (!annotation.getArguments().isEmpty()) {
            return Direction.VERTICAL;
        }
    }
    return Direction.HORIZONTAL;
}