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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: ModifiersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test124701() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
            "package flaska;\n" +
            "\n" +
            "public class Test {\n" +
            "    @SuppressWarnings(\"x\")\n" +
            "    private void alois() {\n" +
            "    }\n" +
            "    \n" +
            "}\n"
            );
    String golden =
            "package flaska;\n" +
            "\n" +
            "public class Test {\n" +
            "    @SuppressWarnings(\"x\")\n" +
            "    public void alois() {\n" +
            "    }\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();
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ModifiersTree mods = method.getModifiers();
            ModifiersTree copy = make.Modifiers(EnumSet.of(Modifier.PUBLIC), mods.getAnnotations());
            workingCopy.rewrite(mods, copy);
        }
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #10
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 #11
Source File: Util.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void addXmlRootAnnotation(WorkingCopy working, TreeMaker make){
    if ( working.getElements().getTypeElement(
            XMLROOT_ANNOTATION) == null)
    {
        return;
    }
    
    TypeElement entityElement = 
        working.getTopLevelElements().get(0);
    List<? extends AnnotationMirror> annotationMirrors = 
        working.getElements().getAllAnnotationMirrors(
                entityElement);
    boolean hasXmlRootAnnotation = false;
    for (AnnotationMirror annotationMirror : annotationMirrors)
    {
        DeclaredType type = annotationMirror.getAnnotationType();
        Element annotationElement = type.asElement();
        if ( annotationElement instanceof TypeElement ){
            Name annotationName = ((TypeElement)annotationElement).
                getQualifiedName();
            if ( annotationName.contentEquals(XMLROOT_ANNOTATION))
            {
                hasXmlRootAnnotation = true;
            }
        }
    }
    if ( !hasXmlRootAnnotation ){
        ClassTree classTree = working.getTrees().getTree(
                entityElement);
        GenerationUtils genUtils = GenerationUtils.
            newInstance(working);
        ModifiersTree modifiersTree = make.addModifiersAnnotation(
                classTree.getModifiers(),
                genUtils.createAnnotation(XMLROOT_ANNOTATION));

        working.rewrite( classTree.getModifiers(), 
                modifiersTree);
    }
}
 
Example #12
Source File: JUnit4TestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 */
@Override
protected ClassTree finishSuiteClass(ClassTree tstClass,
                                     TreePath tstClassTreePath,
                                     List<Tree> tstMembers,
                                     List<String> suiteMembers,
                                     boolean membersChanged,
                                     ClassMap classMap,
                                     WorkingCopy workingCopy) {

    ModifiersTree currModifiers = tstClass.getModifiers();
    ModifiersTree modifiers = fixSuiteClassModifiers(tstClass,
                                                     tstClassTreePath,
                                                     currModifiers,
                                                     suiteMembers,
                                                     workingCopy);
    if (!membersChanged) {
        if (modifiers != currModifiers) {
            workingCopy.rewrite(currModifiers, modifiers);
        }
        return tstClass;
    }

    return workingCopy.getTreeMaker().Class(
            modifiers,
            tstClass.getSimpleName(),
            tstClass.getTypeParameters(),
            tstClass.getExtendsClause(),
            (List<? extends ExpressionTree>) tstClass.getImplementsClause(),
            tstMembers);
}
 
Example #13
Source File: SendJMSGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an injected JMSConnectionFactory field for the given <code>target</code>. The name
 * of the field will be derivated from the given <code>destinationName</code>.
 * @param target the target class
 * @param mappedName the value for resource's mappedName attribute
 * @param fieldType the class of the field.
 * @return name of the created field.
 */
private String createInjectedFactory(FileObject fileObject, String className, String destinationName, String fieldType) throws IOException {
    String fieldName = "context"; //NOI18N
    final ElementHandle<VariableElement> field = _RetoucheUtil.generateAnnotatedField(
            fileObject,
            className,
            "javax.jms.JMSConnectionFactory", //NOI18N
            fieldName,
            fieldType,
            Collections.singletonMap("", destinationName),  //NOI18N
            InjectionTargetQuery.isStaticReferenceRequired(fileObject, className)
            );
    JavaSource javaSource = JavaSource.forFileObject(fileObject);
    javaSource.runModificationTask(new Task<WorkingCopy>() {
        @Override
        public void run(WorkingCopy parameter) throws Exception {
            parameter.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            GenerationUtils genUtils = GenerationUtils.newInstance(parameter);
            TreePath fieldTree = parameter.getTrees().getPath(field.resolve(parameter));
            VariableTree originalTree = (VariableTree) fieldTree.getLeaf();
            ModifiersTree modifiers = originalTree.getModifiers();
            List<AnnotationTree> annotations = new ArrayList<AnnotationTree>(modifiers.getAnnotations());
            annotations.add(0, genUtils.createAnnotation("javax.inject.Inject")); //NOI18N
            ModifiersTree nueMods = parameter.getTreeMaker().Modifiers(modifiers, annotations);
            parameter.rewrite(modifiers, nueMods);
        }
    }).commit();
    return fieldName;
}
 
Example #14
Source File: JaxWsServiceCreator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private VariableTree generateEjbInjection(WorkingCopy workingCopy, 
        TreeMaker make) 
{

    TypeElement ejbAnElement = workingCopy.getElements().getTypeElement(
            "javax.ejb.EJB"); //NOI18N
    if ( ejbAnElement == null ){
        isIncomplete = true;
        return null ;
    }
    TypeElement interfaceElement = workingCopy.getElements().
        getTypeElement(interfaceClass); //NOI18N
    if ( interfaceElement == null ){
        isIncomplete = true;
        return null ;
    }

    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 = interfaceElement != null;

    return make.Variable(
            methodModifiers,
            "ejbRef", //NOI18N
            onClassPath ? make.Type(interfaceElement.asType()) : 
                make.Identifier(interfaceClass),
            null);
}
 
Example #15
Source File: JerseyGenerationStrategy.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
MethodTree generateOptionalFormMethod(TreeMaker maker , WorkingCopy copy ){
    String mvMapClass = "javax.ws.rs.core.MultivaluedMap"; //NOI18N
    TypeElement mvMapEl = copy.getElements().getTypeElement(mvMapClass);
    String mvType = mvMapEl == null ? mvMapClass : "MultivaluedMap"; //NOI18N

    String body =
    "{"+ //NOI18N
        mvType+"<String,String> qParams = new com.sun.jersey.api.representation.Form();"+ //NOI18N
       "for (String qParam : optionalParams) {" + //NOI18N
        "    String[] qPar = qParam.split(\"=\");"+ //NOI18N
        "    if (qPar.length > 1) qParams.add(qPar[0], qPar[1])"+ //NOI18N
        "}"+ //NOI18N
        "return qParams;"+ //NOI18N
    "}"; //NOI18N
    ModifiersTree methodModifier = maker.Modifiers(Collections.<Modifier>singleton(Modifier.PRIVATE));
    ExpressionTree returnTree =
            mvMapEl == null ?
                copy.getTreeMaker().Identifier(mvMapClass) :
                copy.getTreeMaker().QualIdent(mvMapEl);
    ModifiersTree paramModifier = maker.Modifiers(Collections.<Modifier>emptySet());
    VariableTree param = maker.Variable(paramModifier, "optionalParams", maker.Identifier("String..."), null); //NOI18N
    return maker.Method (
            methodModifier,
            "getQParams", //NOI18N
            returnTree,
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>singletonList(param),
            Collections.<ExpressionTree>emptyList(),
            body,
            null); //NOI18N
}
 
Example #16
Source File: Common.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static MethodTree createMethod(TreeMaker make,String name, Map<String,String> params) {
    ModifiersTree methodModifiers = make.Modifiers(
            Collections.<Modifier>singleton(Modifier.PUBLIC),
            Collections.<AnnotationTree>emptyList()
            );
    List<VariableTree> paramList = new LinkedList<VariableTree>();
    for(String paramName: params.keySet()) {
        Tree paramType = getTreeForType(params.get(paramName), make);
        VariableTree parameter = make.Variable(
                make.Modifiers(
                Collections.<Modifier>emptySet(),
                Collections.<AnnotationTree>emptyList()
                ),
                paramName, // name
                paramType, // parameter type
                null // initializer - does not make sense in parameters.
                );
        paramList.add(parameter);
    }
    MethodTree newMethod = make.Method(
            methodModifiers, // public
            name, // name
            make.PrimitiveType(TypeKind.VOID), // return type "void"
            Collections.<TypeParameterTree>emptyList(), // type parameters - none
            paramList, // final ObjectOutput arg0
            Collections.<ExpressionTree>emptyList(), // throws
            "{ throw new UnsupportedOperationException(\"Not supported yet.\") }", // body text
            null // default value - not applicable here, used by annotations
            );
    return newMethod;
}
 
Example #17
Source File: MiscUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** creates addResourceClasses method
 * 
 * @param maker tree maker
 * @param classTree class tree
 * @param controller compilation controller
 * @param methodBody method body
 * @param addComment add comment or not
 * @return modified class tree
 * @throws IOException 
 */
public static ClassTree createAddResourceClasses(TreeMaker maker,
        ClassTree classTree, CompilationController controller,
        String methodBody, boolean addComment) 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));
    ModifiersTree modifiersTree = maker.Modifiers(EnumSet
            .of(Modifier.PRIVATE));
    VariableTree newParam = maker.Variable(
            maker.Modifiers(Collections.<Modifier>emptySet()),
            "resources", wildSet, null);
    MethodTree methodTree = maker.Method(modifiersTree,
            RestConstants.GET_REST_RESOURCE_CLASSES2, maker.Type("void"),
            Collections.<TypeParameterTree> emptyList(),
            Arrays.asList(newParam),
            Collections.<ExpressionTree> emptyList(), methodBody,
            null);
    if (addComment) {
        Comment comment = Comment.create(Comment.Style.JAVADOC,// -2, -2, -2,
                "Do not modify "+RestConstants.GET_REST_RESOURCE_CLASSES2+"() method.\n"
                + "It is automatically populated with\n"
                + "all resources defined in the project.\n"
                + "If required, comment out calling this method in getClasses()."); // NOI18N
        maker.addComment(methodTree, comment, true);
    }
    return maker.addClassMember(classTree, methodTree);
}
 
Example #18
Source File: ClientJavaSourceHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static ClassTree addJerseyClientClass (
        WorkingCopy copy,
        ClassTree classTree,
        String className,
        String resourceURI,
        RestServiceDescription restServiceDesc,
        WadlSaasResource saasResource,
        PathFormat pf,
        Security security, ClientGenerationStrategy strategy ) {

    TreeMaker maker = copy.getTreeMaker();
    ModifiersTree modifs = maker.Modifiers(Collections.<Modifier>singleton(Modifier.STATIC));
    ClassTree innerClass = maker.Class(
            modifs,
            className,
            Collections.<TypeParameterTree>emptyList(),
            null,
            Collections.<Tree>emptyList(),
            Collections.<Tree>emptyList());

    ClassTree modifiedInnerClass =
            generateClassArtifacts(copy, innerClass, resourceURI, 
                    restServiceDesc, saasResource, pf, security, 
                    classTree.getSimpleName().toString(), strategy );

    return maker.addClassMember(classTree, modifiedInnerClass);
}
 
Example #19
Source File: FixFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath path = ctx.getPath();
    TreeMaker make = wc.getTreeMaker();
    ModifiersTree newMods = (ModifiersTree) path.getLeaf();
    for (Modifier a : toAdd) {
        newMods = make.addModifiersModifier(newMods, a);
    }
    for (Modifier r : toRemove) {
        newMods = make.removeModifiersModifier(newMods, r);
    }
    wc.rewrite(path.getLeaf(), newMods);
}
 
Example #20
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private List<Annotation> convertAnnotations(ModifiersTree modifiers, TreePath parent) {
  List<Annotation> annotations = new ArrayList<>();
  TreePath path = getTreePath(parent, modifiers);
  for (AnnotationTree annotation : modifiers.getAnnotations()) {
    annotations.add((Annotation) convert(annotation, path));
  }
  return annotations;
}
 
Example #21
Source File: InsertTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ClassTree generateWsServiceRef(WorkingCopy workingCopy,
        TreeMaker make, ClassTree javaClass)
{
    if ( containsWsRefInjection ) {
        return javaClass;
    }
    //TypeElement wsRefElement = workingCopy.getElements().getTypeElement("javax.xml.ws.WebServiceRef"); //NOI18N
    AnnotationTree wsRefAnnotation = make.Annotation(
            make.QualIdent("javax.xml.ws.WebServiceRef"),
            Collections.<ExpressionTree>singletonList(make.Assignment(make.
                    Identifier("wsdlLocation"), make.Literal(wsdlUrl)))); //NOI18N
    // create field modifier: private(static) with @WebServiceRef annotation
    FileObject targetFo = workingCopy.getFileObject();
    Set<Modifier> modifiers = new HashSet<Modifier>();
    if (Car.getCar(targetFo) != null) {
        modifiers.add(Modifier.STATIC);
    }
    modifiers.add(Modifier.PRIVATE);
    ModifiersTree methodModifiers = make.Modifiers(
            modifiers,
            Collections.<AnnotationTree>singletonList(wsRefAnnotation));
    TypeElement typeElement = workingCopy.getElements().getTypeElement(serviceJavaName);
    VariableTree serviceRefInjection = make.Variable(
        methodModifiers,
        serviceFName,
        (typeElement != null ? make.Type(typeElement.asType()) : 
            make.Identifier(serviceJavaName)),
        null);
    
    ClassTree modifiedClass = make.insertClassMember(javaClass, 0, 
            serviceRefInjection);
    return modifiedClass;
}
 
Example #22
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void removeAnnotation(WorkingCopy workingCopy, 
        Element element, String fqn) 
        throws IOException 
{
    ModifiersTree oldTree = null;
    if (element instanceof TypeElement) {
        oldTree = workingCopy.getTrees().getTree((TypeElement) element).
            getModifiers();
    } else if (element instanceof ExecutableElement) {
        oldTree = workingCopy.getTrees().getTree((ExecutableElement) element).
            getModifiers();
    } else if (element instanceof VariableElement) {
        oldTree = ((VariableTree) workingCopy.getTrees().getTree(element)).
            getModifiers();
    }
    if (oldTree == null) {
        return;
    }
    AnnotationMirror annMirror = null;
    for( AnnotationMirror annotationMirror : element.getAnnotationMirrors() ){
        Element annElement = annotationMirror.getAnnotationType().asElement();
        if ( annElement instanceof TypeElement ){
            if ( fqn.contentEquals(((TypeElement)annElement).getQualifiedName())){
                annMirror = annotationMirror;
            }
        }
    }
    if ( annMirror == null ){
        return;
    }
    AnnotationTree annotation = (AnnotationTree) workingCopy.getTrees().
        getTree(element, annMirror);
    TreeMaker make = workingCopy.getTreeMaker();
    ModifiersTree newTree = make.removeModifiersAnnotation(oldTree, annotation);
    workingCopy.rewrite(oldTree, newTree);
}
 
Example #23
Source File: ConvertToARM.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static VariableTree removeFinal(
        final WorkingCopy wc,
        final VariableTree varTree) {
    final ModifiersTree oldMods = varTree.getModifiers();
    if (oldMods != null && oldMods.getFlags().contains(Modifier.FINAL)) {
        final ModifiersTree newMods = wc.getTreeMaker().removeModifiersModifier(oldMods, Modifier.FINAL);
        rewriteCopyComments(wc, oldMods, newMods);
    }
    return varTree;
}
 
Example #24
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;
}
 
Example #25
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 #26
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 #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 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 #29
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 #30
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);
        }
    }

}