com.sun.source.tree.VariableTree Java Examples

The following examples show how to use com.sun.source.tree.VariableTree. 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: PrivateStaticFinalLoggers.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchVariable(final VariableTree tree, final VisitorState state) {
  final Symbol.VarSymbol sym = ASTHelpers.getSymbol(tree);
  if (sym == null || sym.getKind() != ElementKind.FIELD) {
    return NO_MATCH;
  }
  if (sym.getModifiers()
      .containsAll(List.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))) {
    return NO_MATCH;
  }
  if (!isSubtype(
      getType(tree), state.getTypeFromString("org.apache.logging.log4j.Logger"), state)) {
    return NO_MATCH;
  }
  return buildDescription(tree)
      .addFix(addModifiers(tree, state, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))
      .build();
}
 
Example #2
Source File: Tiny.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_CanBeFinal", description = "#DESC_CanBeFinal", category="thread", suppressWarnings="FieldMayBeFinal")
@TriggerTreeKind(Kind.VARIABLE)
public static ErrorDescription canBeFinal(HintContext ctx) {
    Element ve = ctx.getInfo().getTrees().getElement(ctx.getPath());
    
    if (ve == null || ve.getKind() != ElementKind.FIELD || ve.getModifiers().contains(Modifier.FINAL) || /*TODO: the point of volatile?*/ve.getModifiers().contains(Modifier.VOLATILE)) return null;
    
    //we can't say much currently about non-private fields:
    if (!ve.getModifiers().contains(Modifier.PRIVATE)) return null;
    
    FlowResult flow = Flow.assignmentsForUse(ctx);
    
    if (flow == null || ctx.isCanceled()) return null;
    
    if (flow.getFinalCandidates().contains(ve)) {
        VariableTree vt = (VariableTree) ctx.getPath().getLeaf();
        Fix fix = null;
        if (flow.getFieldInitConstructors(ve).size() <= 1) {
            fix = FixFactory.addModifiersFix(ctx.getInfo(), new TreePath(ctx.getPath(), vt.getModifiers()), EnumSet.of(Modifier.FINAL), Bundle.FIX_CanBeFinal(ve.getSimpleName().toString()));
        }
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_CanBeFinal(ve.getSimpleName().toString()), fix);
    }
    
    return null;
}
 
Example #3
Source File: TreeConverter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private TreeNode convertMethodDeclaration(MethodTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  ExecutableElement element = (ExecutableElement) getElement(path);
  MethodDeclaration newNode = new MethodDeclaration();

  // JCMethodDecl's preferred diagnostic position is the beginning of the method name.
  int methodStartPosition = ((JCMethodDecl) node).pos().getPreferredPosition();

  int length =
      ElementUtil.isConstructor(element)
          ? element.toString().indexOf('(')
          : node.getName().length();

  Name name = Name.newName(null /* qualifier */, element);
  name.setPosition(new SourcePosition(methodStartPosition, length));

  convertBodyDeclaration(node, parent, node.getModifiers(), newNode);
  for (VariableTree param : node.getParameters()) {
    newNode.addParameter((SingleVariableDeclaration) convert(param, path));
  }
  return newNode
      .setIsConstructor(ElementUtil.isConstructor(element))
      .setExecutableElement(element)
      .setBody((Block) convert(node.getBody(), path))
      .setName(name);
}
 
Example #4
Source File: EntityMethodGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public MethodTree createHashCodeMethod(List<VariableTree> fields) {
    StringBuilder body = new StringBuilder(20 + fields.size() * 30);
    body.append("{"); // NOI18N
    body.append("int hash = 0;"); // NOI18N
    for (VariableTree field : fields) {
        body.append(createHashCodeLineForField(field));
    }
    body.append("return hash;"); // NOI18N
    body.append("}"); // NOI18N
    TreeMaker make = copy.getTreeMaker();
    // XXX Javadoc
    return make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC),
            Collections.singletonList(genUtils.createAnnotation("java.lang.Override"))), "hashCode",
            make.PrimitiveType(TypeKind.INT), Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body.toString(), null);
}
 
Example #5
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a public static {@code main(String[])} method
 * with the body taken from settings.
 *
 * @param  maker  {@code TreeMaker} to use for creating the method
 * @return  created {@code main(...)} method,
 *          or {@code null} if the method body would be empty
 */
private MethodTree createMainMethod(TreeMaker maker) {
    String initialMainMethodBody = getInitialMainMethodBody();
    if (initialMainMethodBody.length() == 0) {
        return null;
    }

    ModifiersTree modifiers = maker.Modifiers(
            createModifierSet(Modifier.PUBLIC, Modifier.STATIC));
    VariableTree param = maker.Variable(
                    maker.Modifiers(Collections.<Modifier>emptySet()),
                    "argList",                                      //NOI18N
                    maker.Identifier("String[]"),                   //NOI18N
                    null);            //initializer - not used in params
    MethodTree mainMethod = maker.Method(
          modifiers,                            //public static
          "main",                               //method name "main"//NOI18N
          maker.PrimitiveType(TypeKind.VOID),   //return type "void"
          Collections.<TypeParameterTree>emptyList(),     //type params
          Collections.<VariableTree>singletonList(param), //method param
          Collections.<ExpressionTree>emptyList(),        //throws-list
          '{' + initialMainMethodBody + '}',    //body text
          null);                                //only for annotations

    return mainMethod;
}
 
Example #6
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVarPos() throws IOException {

    final String code = "package t; class Test { " +
            "{ java.io.InputStream in = null; } }";

    CompilationUnitTree cut = getCompilationUnitTree(code);

    new TreeScanner<Void, Void>() {

        @Override
        public Void visitVariable(VariableTree node, Void p) {
            if ("in".contentEquals(node.getName())) {
                JCTree.JCVariableDecl var = (JCTree.JCVariableDecl) node;
                assertEquals("testVarPos","in = null; } }",
                        code.substring(var.pos));
            }
            return super.visitVariable(node, p);
        }
    }.scan(cut, null);
}
 
Example #7
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a setter method for a field.
 *
 * @param clazz the class to create the setter within
 * @param field field to create setter for
 * @return the setter method
 * @since 0.20
 */
public MethodTree createSetter(ClassTree clazz, VariableTree field) {
    assert clazz != null && field != null;
    TreeMaker make = copy.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    boolean isStatic = field.getModifiers().getFlags().contains(Modifier.STATIC);
    if (isStatic)
        mods.add(Modifier.STATIC);
    CharSequence name = field.getName();
    assert name.length() > 0;
    CodeStyle cs = DiffContext.getCodeStyle(copy);
    String propName = removeFieldPrefixSuffix(field, cs);
    String setterName = CodeStyleUtils.computeSetterName(field.getName(), isStatic, cs);
    String paramName = addParamPrefixSuffix(propName, cs);
    List<VariableTree> params = Collections.singletonList(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), paramName, field.getType(), null));
    BlockTree body = make.Block(Collections.singletonList(make.ExpressionStatement(make.Assignment(make.MemberSelect(isStatic? make.Identifier(clazz.getSimpleName()) : make.Identifier("this"), name), make.Identifier(paramName)))), false); //NOI18N
    return make.Method(make.Modifiers(mods), setterName, make.Type(copy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), params, Collections.<ExpressionTree>emptyList(), body, null);
}
 
Example #8
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static ClassTree addConstructor(WorkingCopy copy, ClassTree tree, Modifier[] modifiers, String[] parameters, Object[] paramTypes, String bodyText, String comment) {
    TreeMaker maker = copy.getTreeMaker();
    ModifiersTree modifiersTree = createModifiersTree(copy, modifiers, null, null);
    ModifiersTree paramModTree = maker.Modifiers(Collections.<Modifier>emptySet());
    List<VariableTree> paramTrees = new ArrayList<VariableTree>();

    if (parameters != null) {
        for (int i = 0; i < parameters.length; i++) {
            paramTrees.add(maker.Variable(paramModTree, parameters[i], createTypeTree(copy, paramTypes[i]), null));
        }
    }

    MethodTree methodTree = maker.Constructor(modifiersTree, Collections.<TypeParameterTree>emptyList(), paramTrees, Collections.<ExpressionTree>emptyList(), bodyText);

    if (comment != null) {
        maker.addComment(methodTree, createJavaDocComment(comment), true);
    }

    return maker.addClassMember(tree, methodTree);
}
 
Example #9
Source File: FieldTest1.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * copy the initialization 'new String("NetBeers")' to 'new String()'.
 * It tests only change in expression, no expression swap.
 */
public void testFieldChangeInInitValue() throws IOException {
    System.err.println("testFieldChangeInInitValue");
    process(
        new Transformer<Void, Object>() {
            public Void visitVariable(VariableTree node, Object p) {
                super.visitVariable(node, p);
                if ("initialValueReplacer".contentEquals(node.getName())) {
                    if (Tree.Kind.NEW_CLASS.equals(node.getInitializer().getKind())) {
                        NewClassTree nct = (NewClassTree) node.getInitializer();
                        NewClassTree njuNct = make.NewClass(
                                nct.getEnclosingExpression(), 
                                (List<ExpressionTree>) nct.getTypeArguments(),
                                nct.getIdentifier(),
                                Collections.singletonList(make.Literal("NetBeans")),
                                nct.getClassBody()
                        );
                        copy.rewrite(nct, njuNct);
                    }
                }
                return null;
            }
        }
    );
    assertFiles("testFieldChangeInInitValue.pass");
}
 
Example #10
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 */
private List<VariableTree> generateParamVariables(
                                        WorkingCopy workingCopy,
                                        ExecutableType srcMethod,
                                        String[] varNames) {
    TreeMaker maker = workingCopy.getTreeMaker();
    List<? extends TypeMirror> params = srcMethod.getParameterTypes();
    if ((params == null) || params.isEmpty()) {
        return Collections.<VariableTree>emptyList();
    }

    Set<Modifier> noModifiers = Collections.<Modifier>emptySet();
    List<VariableTree> paramVariables = new ArrayList<VariableTree>(params.size());
    int index = 0;
    for (TypeMirror param : params) {
        if (param.getKind() == TypeKind.TYPEVAR){
            param = getSuperType(workingCopy, param);
        }
        paramVariables.add(
                maker.Variable(maker.Modifiers(noModifiers),
                               varNames[index++],
                               maker.Type(param),
                               getDefaultValue(maker, param)));
    }
    return paramVariables;
}
 
Example #11
Source File: GenerationUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts the given fields in the given class after any fields already existing
 * in the class (if any, otherwise the fields are inserted at the beginning
 * of the class).
 *
 * @param  classTree the class to add fields to; cannot be null.
 * @param  fieldTrees the fields to be added; cannot be null.
 * @return the class containing the new fields; never null.
 */
public ClassTree addClassFields(ClassTree classTree, List<? extends VariableTree> fieldTrees) {
    Parameters.notNull("classTree", classTree); // NOI18N
    Parameters.notNull("fieldTrees", fieldTrees); // NOI18N

    int firstNonFieldIndex = 0;
    Iterator<? extends Tree> memberTrees = classTree.getMembers().iterator();
    while (memberTrees.hasNext() && memberTrees.next().getKind() == Tree.Kind.VARIABLE) {
        firstNonFieldIndex++;
    }
    TreeMaker make = getTreeMaker();
    ClassTree newClassTree = classTree;
    for (VariableTree fieldTree : fieldTrees) {
        newClassTree = make.insertClassMember(newClassTree, firstNonFieldIndex, fieldTree);
        firstNonFieldIndex++;
    }
    return newClassTree;
}
 
Example #12
Source File: ConvertToLambdaConverter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Tree visitVariable(VariableTree variableDeclTree, Trees trees) {
    //check for shadowed variable
    if (isNameAlreadyUsed(variableDeclTree.getName())) {
        TreePath path = getCurrentPath();

        CharSequence newName = getUniqueName(variableDeclTree.getName());

        Element el = trees.getElement(path);
        if (el != null) {
            originalToNewName.put(el, newName);
        }

        VariableTree newTree = copy.getTreeMaker()
                .Variable(variableDeclTree.getModifiers(), newName, variableDeclTree.getType(), variableDeclTree.getInitializer());
        copy.rewrite(variableDeclTree, newTree);
    }

    return super.visitVariable(variableDeclTree, trees);
}
 
Example #13
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testNewClassWithEnclosing() throws IOException {

    final String theString = "Test.this.new d()";
    String code = "package test; class Test { " +
            "class d {} private void method() { " +
            "Object o = " + theString + "; } }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, 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);
    ExpressionTree est =
            ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();

    final int spos = code.indexOf(theString);
    final int epos = spos + theString.length();
    assertEquals("testNewClassWithEnclosing",
            spos, pos.getStartPosition(cut, est));
    assertEquals("testNewClassWithEnclosing",
            epos, pos.getEndPosition(cut, est));
}
 
Example #14
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
private void visitEnumConstantDeclaration(VariableTree enumConstant) {
    for (AnnotationTree annotation : enumConstant.getModifiers().getAnnotations()) {
        scan(annotation, null);
        builder.forcedBreak();
    }
    visit(enumConstant.getName());
    NewClassTree init = ((NewClassTree) enumConstant.getInitializer());
    if (init.getArguments().isEmpty()) {
        builder.guessToken("(");
        builder.guessToken(")");
    } else {
        addArguments(init.getArguments(), plusFour);
    }
    if (init.getClassBody() != null) {
        addBodyDeclarations(
                init.getClassBody().getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
    }
}
 
Example #15
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
void visitVariables(
        List<VariableTree> fragments,
        DeclarationKind declarationKind,
        Direction annotationDirection) {
    if (fragments.size() == 1) {
        VariableTree fragment = fragments.get(0);
        declareOne(
                declarationKind,
                annotationDirection,
                Optional.of(fragment.getModifiers()),
                fragment.getType(),
                VarArgsOrNot.fromVariable(fragment),
                ImmutableList.<AnnotationTree>of(),
                fragment.getName(),
                "",
                "=",
                Optional.fromNullable(fragment.getInitializer()),
                Optional.of(";"),
                Optional.<ExpressionTree>absent(),
                Optional.fromNullable(variableFragmentDims(true, 0, fragment.getType())));

    } else {
        declareMany(fragments, annotationDirection);
    }
}
 
Example #16
Source File: ConstantNameHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean checkZeroSizeArray(CompilationInfo info, TreePath val) {
    if (val.getLeaf().getKind() != Tree.Kind.VARIABLE) {
        return false;
    }
    VariableTree vt = (VariableTree)val.getLeaf();
    ExpressionTree xpr = vt.getInitializer();
    if (xpr == null) {
        return false;
    }
    if (xpr.getKind() == Tree.Kind.NEW_ARRAY) {
        NewArrayTree nat = (NewArrayTree)xpr;
        List<? extends ExpressionTree> dims = nat.getDimensions();
        if (dims != null && !dims.isEmpty()) {
            Object size = ArithmeticUtilities.compute(info, 
                    new TreePath(
                        new TreePath(val, xpr),
                        dims.get(dims.size() -1)), 
                    true);
            return ArithmeticUtilities.isRealValue(size) && Integer.valueOf(0).equals(size);
        } else {
            return nat.getInitializers() != null && nat.getInitializers().isEmpty();
        }
    }
    return false;
}
 
Example #17
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static ClassTree addConstructor(WorkingCopy copy, ClassTree tree, Modifier[] modifiers, String[] parameters, Object[] paramTypes, String bodyText, String comment) {
    TreeMaker maker = copy.getTreeMaker();
    ModifiersTree modifiersTree = createModifiersTree(copy, modifiers, null, null);
    ModifiersTree paramModTree = maker.Modifiers(Collections.<Modifier>emptySet());
    List<VariableTree> paramTrees = new ArrayList<VariableTree>();

    if (parameters != null) {
        for (int i = 0; i < parameters.length; i++) {
            paramTrees.add(maker.Variable(paramModTree, parameters[i], createTypeTree(copy, paramTypes[i]), null));
        }
    }

    MethodTree methodTree = maker.Constructor(modifiersTree, Collections.<TypeParameterTree>emptyList(), paramTrees, Collections.<ExpressionTree>emptyList(), bodyText);

    if (comment != null) {
        maker.addComment(methodTree, createJavaDocComment(comment), true);
    }

    return maker.addClassMember(tree, methodTree);
}
 
Example #18
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
protected void visitStatements(List<? extends StatementTree> statements) {
  boolean first = true;
  PeekingIterator<StatementTree> it = Iterators.peekingIterator(statements.iterator());
  dropEmptyDeclarations();
  while (it.hasNext()) {
    StatementTree tree = it.next();
    builder.forcedBreak();
    if (!first) {
      builder.blankLineWanted(BlankLineWanted.PRESERVE);
    }
    markForPartialFormat();
    first = false;
    List<VariableTree> fragments = variableFragments(it, tree);
    if (!fragments.isEmpty()) {
      visitVariables(
          fragments,
          DeclarationKind.NONE,
          canLocalHaveHorizontalAnnotations(fragments.get(0).getModifiers()));
    } else {
      scan(tree, null);
    }
  }
}
 
Example #19
Source File: TreeMirrorMaker.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public JCTree visitVariable(VariableTree node, Void p) {
	JCVariableDecl original = node instanceof JCVariableDecl ? (JCVariableDecl) node : null;
	JCVariableDecl copy = (JCVariableDecl) super.visitVariable(node, p);
	if (original == null) return copy;
	
	copy.sym = original.sym;
	if (copy.sym != null) copy.type = original.type;
	if (copy.type != null) {
		boolean wipeSymAndType = copy.type.isErroneous();
		if (!wipeSymAndType) {
			TypeTag typeTag = TypeTag.typeTag(copy.type);
			wipeSymAndType = (CTC_NONE.equals(typeTag) || CTC_ERROR.equals(typeTag) || CTC_UNKNOWN.equals(typeTag) || CTC_UNDETVAR.equals(typeTag));
		}
		
		if (wipeSymAndType) {
			copy.sym = null;
			copy.type = null;
		}
	}
	
	return copy;
}
 
Example #20
Source File: FieldTest1.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Change whole initial value expression to literal 78.
 */
public void testFieldInitialValue() throws IOException {
    System.err.println("testFieldInitialValue");
    process(
        new Transformer<Void, Object>() {
            public Void visitVariable(VariableTree node, Object p) {
                super.visitVariable(node, p);
                if ("initialValueChanger".contentEquals(node.getName())) {
                    copy.rewrite(node.getInitializer(), make.Literal(Long.valueOf(78)));
                }
                return null;
            }
        }
    );
    assertFiles("testFieldInitialValue.pass");
}
 
Example #21
Source File: EntityManagerGenerationStrategySupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the variable tree representing the first field of the given type in
 * our class.
 *
 * @param fieldTypeFqn the fully qualified name of the field's type.
 * @return the variable tree or null if no matching field was found.
 */
protected VariableTree getField(final String fieldTypeFqn){
    
    Parameters.notEmpty("fieldTypeFqn", fieldTypeFqn); //NOI18N
    
    for (Tree member : getClassTree().getMembers()){
        if (Tree.Kind.VARIABLE == member.getKind()){
            VariableTree variable = (VariableTree) member;
            TreePath path = getWorkingCopy().getTrees().getPath(getWorkingCopy().getCompilationUnit(), variable);
            TypeMirror variableType = getWorkingCopy().getTrees().getTypeMirror(path);
            if (fieldTypeFqn.equals(variableType.toString())){
                return variable;
            }
            
        }
    }
    return null;
}
 
Example #22
Source File: GenerationUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts the given fields in the given class after any fields already existing
 * in the class (if any, otherwise the fields are inserted at the beginning
 * of the class).
 *
 * @param  classTree the class to add fields to; cannot be null.
 * @param  fieldTrees the fields to be added; cannot be null.
 * @return the class containing the new fields; never null.
 */
public ClassTree addClassFields(ClassTree classTree, List fieldTrees) {
    Parameters.notNull("classTree", classTree); // NOI18N
    Parameters.notNull("fieldTrees", fieldTrees); // NOI18N

    int firstNonFieldIndex = 0;
    Iterator<? extends Tree> memberTrees = classTree.getMembers().iterator();
    while (memberTrees.hasNext() && memberTrees.next().getKind() == Tree.Kind.VARIABLE) {
        firstNonFieldIndex++;
    }
    TreeMaker make = getTreeMaker();
    ClassTree newClassTree = classTree;
    for (int i=0; i < fieldTrees.size(); i++ ) {
        VariableTree fieldTree =  (VariableTree)fieldTrees.get(i);        
        newClassTree = make.insertClassMember(newClassTree, firstNonFieldIndex, fieldTree);
        firstNonFieldIndex++;
    }
    return newClassTree;
}
 
Example #23
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void addAnnotation(WorkingCopy workingCopy, 
        Element element, String annotationName) 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;
    }
    TreeMaker make = workingCopy.getTreeMaker();
    AnnotationTree annotationTree = make.Annotation(make.QualIdent(annotationName), 
            Collections.<ExpressionTree>emptyList());
    ModifiersTree newTree = make.addModifiersAnnotation(oldTree, annotationTree);
    workingCopy.rewrite(oldTree, newTree);
}
 
Example #24
Source File: TestGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 */
@Override
protected MethodTree composeNewTestMethod(String testMethodName,
                                          BlockTree testMethodBody,
                                          List<ExpressionTree> throwsList,
                                          WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    return maker.Method(
            createModifiersTree(ANN_TEST,
                                createModifierSet(PUBLIC),
                                workingCopy),
            testMethodName,
            maker.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(),
            throwsList,
            testMethodBody,
            null);          //default value - used by annotations
}
 
Example #25
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 */
private List<IdentifierTree> createIdentifiers(
                                        TreeMaker maker,
                                        List<VariableTree> variables) {
    List<IdentifierTree> identifiers;
    if (variables.isEmpty()) {
        identifiers = Collections.<IdentifierTree>emptyList();
    } else {
        identifiers = new ArrayList<IdentifierTree>(variables.size());
        for (VariableTree var : variables) {
            identifiers.add(maker.Identifier(var.getName().toString()));
        }
    }
    return identifiers;
}
 
Example #26
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String name(Tree tree) {
    switch (tree.getKind()) {
        case VARIABLE:
            return ((VariableTree)tree).getName().toString();
        case METHOD:
            return ((MethodTree)tree).getName().toString();
        case CLASS:
            return ((ClassTree)tree).getSimpleName().toString();
        case IDENTIFIER:
            return ((IdentifierTree)tree).getName().toString();
        case MEMBER_SELECT:
            return name(((MemberSelectTree)tree).getExpression()) + '.' + ((MemberSelectTree)tree).getIdentifier();
    }
    return ""; //NOI18N
}
 
Example #27
Source File: MultipleRewritesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testRewriteRewrittenTree2() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
            "package hierbas.del.litoral;\n\n" +
            "public class Test {\n" +
            "    String a;\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "public class Test {\n" +
            "    Object a;\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);
            VariableTree var = (VariableTree) clazz.getMembers().get(1);
            IdentifierTree i = make.Identifier("Test");

            workingCopy.rewrite(var.getType(), i);
            workingCopy.rewrite(i, make.Identifier("Object"));
        }

    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #28
Source File: ProspectiveOperation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ExpressionTree makeSimpleExplicitReducer(Tree.Kind opKind, VariableTree var, VariableTree var1) {
    Tree lambdaBody;
    ExpressionTree lambda;
    lambdaBody = this.treeMaker.Binary(this.getSuitableOperator(opKind), this.treeMaker.Identifier("accumulator"), this.treeMaker.Identifier(UNKNOWN_NAME));
    lambda = treeMaker.LambdaExpression(Arrays.asList(var, var1), lambdaBody);
    return lambda;
}
 
Example #29
Source File: EntityResourcesGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected List<VariableTree> addRestArguments( TypeElement classElement,
        GenerationUtils genUtils, TreeMaker maker,
        RestGenerationOptions option, ModifiersTree paramModifier )
{
    List<VariableTree> vars = new ArrayList<VariableTree>();
    String[] paramNames = option.getParameterNames();
    int paramLength = paramNames == null ? 0 : option.getParameterNames().length ;

    if (paramLength > 0) {
        String[] paramTypes = option.getParameterTypes();
        String[] pathParams = option.getPathParams();
        
        for (int i = 0; i<paramLength; i++) {
            ModifiersTree pathParamTree = paramModifier;
            if (pathParams != null && pathParams[i] != null) {
                List<ExpressionTree> annArguments = 
                    Collections.<ExpressionTree>singletonList(
                            maker.Literal(pathParams[i]));
                pathParamTree =
                    maker.addModifiersAnnotation(paramModifier, 
                            genUtils.createAnnotation(
                                    RestConstants.PATH_PARAM, 
                                    annArguments));
            }
            Tree paramTree = genUtils.createType(paramTypes[i], 
                    classElement);
            VariableTree var = maker.Variable(pathParamTree, 
                    paramNames[i], paramTree, null); 
            vars.add(var);

        }
    }
    return vars;
}
 
Example #30
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
}