com.sun.source.tree.ExpressionTree Java Examples

The following examples show how to use com.sun.source.tree.ExpressionTree. 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: EjbFacadeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ExpressionTree mimeTypeTree(TreeMaker maker, String mimeType) {
    String mediaTypeMember = null;
    if (mimeType.equals("application/xml")) { // NOI18N
        mediaTypeMember = "APPLICATION_XML"; // NOI18N
    } else if (mimeType.equals("application/json")) { // NOI18N
        mediaTypeMember = "APPLICATION_JSON"; // NOI18N
    } else if (mimeType.equals("text/plain")) { // NOI18N
        mediaTypeMember = "TEXT_PLAIN"; // NOI18N
    }
    ExpressionTree result;
    if (mediaTypeMember == null) {
        result = maker.Literal(mimeType);
    } else {
        // Use a field of MediaType class if possible
        ExpressionTree typeTree = maker.QualIdent("javax.ws.rs.core.MediaType"); // NOI18N
        result = maker.MemberSelect(typeTree, mediaTypeMember);
    }
    return result;
}
 
Example #2
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected ClassTree generateStubTestMethod(ClassTree tstClass,
                                           String testMethodName,
                                           WorkingCopy workingCopy) {
    List<? extends Tree> tstMembersOrig = tstClass.getMembers();
    List<Tree> tstMembers = new ArrayList<Tree>(tstMembersOrig.size() + 4);
    tstMembers.addAll(tstMembersOrig);

    List<ExpressionTree> throwsList = Collections.emptyList();
    MethodTree method = composeNewTestMethod(
            STUB_TEST_NAME,
            generateStubTestMethodBody(workingCopy),
            throwsList,
            workingCopy);

    tstMembers.add(method);

    ClassTree newClass = workingCopy.getTreeMaker().Class(
            tstClass.getModifiers(),
            tstClass.getSimpleName(),
            tstClass.getTypeParameters(),
            tstClass.getExtendsClause(),
            (List<? extends ExpressionTree>) tstClass.getImplementsClause(),
            tstMembers);
    return newClass;
}
 
Example #3
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }

  ExpressionTree switchExpression = tree.getExpression();
  if (switchExpression instanceof ParenthesizedTree) {
    switchExpression = ((ParenthesizedTree) switchExpression).getExpression();
  }

  if (mayBeNullExpr(state, switchExpression)) {
    final String message =
        "switch expression " + state.getSourceForNode(switchExpression) + " is @Nullable";
    ErrorMessage errorMessage =
        new ErrorMessage(MessageTypes.SWITCH_EXPRESSION_NULLABLE, message);

    return errorBuilder.createErrorDescription(
        errorMessage, switchExpression, buildDescription(switchExpression), state);
  }

  return Description.NO_MATCH;
}
 
Example #4
Source File: EntityMethodGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public  MethodTree createEqualsMethod(String simpleClassName, List<VariableTree> fields) {
    StringBuilder body = new StringBuilder(50 + fields.size() * 30);
    body.append("{"); // NOI18N
    body.append("// TODO: Warning - this method won't work in the case the id fields are not set\n"); // NOI18N
    body.append("if (!(object instanceof "); // NOI18N
    body.append(simpleClassName + ")) {return false;}"); // NOI18N
    body.append(simpleClassName + " other = (" + simpleClassName + ")object;"); // NOI18N
    for (VariableTree field : fields) {
        body.append(createEqualsLineForField(field));
    }
    body.append("return true;"); // 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"))), "equals",
            make.PrimitiveType(TypeKind.BOOLEAN), Collections.<TypeParameterTree>emptyList(),
            Collections.singletonList(genUtils.createVariable(scope, "object", "java.lang.Object")),
            Collections.<ExpressionTree>emptyList(), body.toString(), null);
}
 
Example #5
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 #6
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
private void dotExpressionUpToArgs(ExpressionTree expression, Optional<BreakTag> tyargTag) {
    expression = getArrayBase(expression);
    switch (expression.getKind()) {
        case MEMBER_SELECT:
            MemberSelectTree fieldAccess = (MemberSelectTree) expression;
            visit(fieldAccess.getIdentifier());
            break;
        case METHOD_INVOCATION:
            MethodInvocationTree methodInvocation = (MethodInvocationTree) expression;
            if (!methodInvocation.getTypeArguments().isEmpty()) {
                builder.open(plusFour);
                addTypeArguments(methodInvocation.getTypeArguments(), ZERO);
                // TODO(jdd): Should indent the name -4.
                builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, tyargTag);
                builder.close();
            }
            visit(getMethodName(methodInvocation));
            break;
        case IDENTIFIER:
            visit(((IdentifierTree) expression).getName());
            break;
        default:
            scan(expression, null);
            break;
    }
}
 
Example #7
Source File: CodeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private AnnotationTree computeAnnotationTree(AnnotationMirror am) {
    List<ExpressionTree> params = new LinkedList<ExpressionTree>();

    for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : am.getElementValues().entrySet()) {
        ExpressionTree val = createTreeForAnnotationValue(make, entry.getValue());

        if (val == null) {
            LOG.log(Level.WARNING, "Cannot create annotation for: {0}", entry.getValue());
            continue;
        }

        ExpressionTree vt = make.Assignment(make.Identifier(entry.getKey().getSimpleName()), val);

        params.add(vt);
    }

    return make.Annotation(make.Type(am.getAnnotationType()), params);
}
 
Example #8
Source File: AddCastFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TypeMirror resolvedTargetType = targetType.resolve(ctx.getWorkingCopy());
    
    if (resolvedTargetType == null) {
        //cannot resolve anymore:
        return;
    }
    
    TreePath resolvedIdealTypeTree = idealTypeTree != null ? idealTypeTree.resolve(ctx.getWorkingCopy()) : null;
    
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    ExpressionTree toCast = (ExpressionTree) ctx.getPath().getLeaf();

    Class interf = toCast.getKind().asInterface();
    boolean wrapWithBrackets = interf == BinaryTree.class || interf == ConditionalExpressionTree.class;

    if (/*TODO: replace with JavaFixUtilities.requiresparenthesis*/wrapWithBrackets) {
        toCast = make.Parenthesized(toCast);
    }

    ExpressionTree cast = make.TypeCast(resolvedIdealTypeTree != null ? resolvedIdealTypeTree.getLeaf() : make.Type(resolvedTargetType), toCast);

    ctx.getWorkingCopy().rewrite(ctx.getPath().getLeaf(), cast);
}
 
Example #9
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
private void visitPackage(
    ExpressionTree packageName, List<? extends AnnotationTree> packageAnnotations) {
  if (!packageAnnotations.isEmpty()) {
    for (AnnotationTree annotation : packageAnnotations) {
      builder.forcedBreak();
      scan(annotation, null);
    }
    builder.forcedBreak();
  }
  builder.open(plusFour);
  token("package");
  builder.space();
  visitName(packageName);
  builder.close();
  token(";");
}
 
Example #10
Source File: MethodTest2.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Void visitMethod(MethodTree node, Object p) {
    super.visitMethod(node, p);
    if (method.equals(node)) {
        MethodTree njuMethod = make.Method(
                node.getModifiers(),
                node.getName().toString(),
                make.Identifier(newType),
                node.getTypeParameters(),
                node.getParameters(),
                node.getThrows(),
                node.getBody(),
                (ExpressionTree) node.getDefaultValue()
                );
        copy.rewrite(node, njuMethod);
        method = njuMethod;
    }
    return null;
}
 
Example #11
Source File: LoggerStringConcat.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath invocation = ctx.getPath();
    TreePath message    = FixImpl.this.message.resolve(wc);
    MethodInvocationTree mit = (MethodInvocationTree) invocation.getLeaf();
    ExpressionTree level = null;

    if (logMethodName != null) {
        String logMethodNameUpper = logMethodName.toUpperCase();
        VariableElement c = findConstant(wc, logMethodNameUpper);

        level = wc.getTreeMaker().QualIdent(c);
    } else {
        level = mit.getArguments().get(0);
    }

    rewrite(wc, level, mit, message);
}
 
Example #12
Source File: Trees.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
     * Returns the string name of an operator, including assignment and compound assignment.
     */
    static String operatorName(ExpressionTree expression) {
//        JCTree.Tag tag = ((JCTree) expression).getTag();
//        if (tag == JCTree.Tag.ASSIGN) {
//            return "=";
//        }
//        boolean assignOp = expression instanceof CompoundAssignmentTree;
//        if (assignOp) {
//            tag = tag.noAssignOp();
//        }
        int tag = ((JCTree) expression).getTag();
        if (tag == JCTree.ASSIGN) {
            return "=";
        }
        boolean assignOp = expression instanceof CompoundAssignmentTree;
        if (assignOp) {
//            tag = tag.noAssignOp();
            // TODO: 22-Jul-17  ?????
        }

        String name = new Pretty(/*writer*/ null, /*sourceOutput*/ true).operatorName(tag);
        return assignOp ? name + "=" : name;
    }
 
Example #13
Source File: EqualsHashCodeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static MethodTree createHashCodeMethod(WorkingCopy wc, Iterable<? extends VariableElement> hashCodeFields, Scope scope) {
    TreeMaker make = wc.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);        

    int startNumber = generatePrimeNumber(2, 10);
    int multiplyNumber = generatePrimeNumber(10, 100);
    List<StatementTree> statements = new ArrayList<>();
    //int hash = <startNumber>;
    statements.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "hash", make.PrimitiveType(TypeKind.INT), make.Literal(startNumber))); //NOI18N        
    for (VariableElement ve : hashCodeFields) {
        TypeMirror tm = ve.asType();
        ExpressionTree variableRead = prepareExpression(wc, HASH_CODE_PATTERNS, tm, ve, scope);
        statements.add(make.ExpressionStatement(make.Assignment(make.Identifier("hash"), make.Binary(Tree.Kind.PLUS, make.Binary(Tree.Kind.MULTIPLY, make.Literal(multiplyNumber), make.Identifier("hash")), variableRead)))); //NOI18N
    }
    statements.add(make.Return(make.Identifier("hash"))); //NOI18N        
    BlockTree body = make.Block(statements, false);
    ModifiersTree modifiers = prepareModifiers(wc, mods,make);
    
    return make.Method(modifiers, "hashCode", make.PrimitiveType(TypeKind.INT), Collections.<TypeParameterTree> emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N
}
 
Example #14
Source File: MagicSurroundWithTryCatchFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static StatementTree createRethrowAsRuntimeExceptionStatement(WorkingCopy info, TreeMaker make, String name) {
    if (!ErrorFixesFakeHint.isRethrowAsRuntimeException(ErrorFixesFakeHint.getPreferences(info.getFileObject(), FixKind.SURROUND_WITH_TRY_CATCH))) {
        return null;
    }

    TypeElement runtimeException = info.getElements().getTypeElement("java.lang.RuntimeException");

    if (runtimeException == null) {
        return null;
    }

    ExpressionTree exceptionName = make.QualIdent(runtimeException);
    StatementTree result = make.Throw(make.NewClass(null, Collections.<ExpressionTree>emptyList(), exceptionName, Arrays.asList(make.Identifier(name)), null));

    info.tag(exceptionName, Utilities.TAG_SELECT);
    
    return result;
}
 
Example #15
Source File: ExtendsImplements.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TreePath clazz = findClass(ctx.getPath());
    
    if (clazz == null) {
        //TODO: should not happen - warn?
        return ;
    }
    
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    ClassTree original = (ClassTree) clazz.getLeaf();
    ClassTree nue;
    
    if (extends2Implements) {
        nue = make.insertClassImplementsClause(make.setExtends(original, null), 0, ctx.getPath().getLeaf());
    } else {
        nue = make.setExtends(make.removeClassImplementsClause(original, ctx.getPath().getLeaf()), (ExpressionTree) ctx.getPath().getLeaf());
    }
    
    ctx.getWorkingCopy().rewrite(original, nue);
}
 
Example #16
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean isIterbale(ExpressionTree expression) {
    TypeMirror tm = workingCopy.getTrees().getTypeMirror(TreePath.getPath(workingCopy.getCompilationUnit(), expression));
    if (!Utilities.isValidType(tm)) {
        return false;
    }
    if (tm.getKind() == TypeKind.ARRAY) {
        return false;
    } else {
        tm = workingCopy.getTypes().erasure(tm);
        TypeElement typeEl = workingCopy.getElements().getTypeElement("java.util.Collection");
        if (typeEl != null) {
            TypeMirror collection = typeEl.asType();
            collection = workingCopy.getTypes().erasure(collection);
            if (this.workingCopy.getTypes().isSubtype(tm, collection)) {
                return true;
            }
        }
    }

    return false;
}
 
Example #17
Source File: ToStringGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<StatementTree> createToStringMethodBodyWithPlusOperator(TreeMaker make, String typeName, Iterable<? extends VariableElement> fields) {
    ExpressionTree exp = make.Literal(typeName + '{');
    boolean first = true;
    for (VariableElement variableElement : fields) {
        StringBuilder sb = new StringBuilder();
        if (!first) {
            sb.append(", ");
        }
        sb.append(variableElement.getSimpleName().toString()).append('=');
        exp = make.Binary(Tree.Kind.PLUS, exp, make.Literal(sb.toString()));
        exp = make.Binary(Tree.Kind.PLUS, exp, make.Identifier(variableElement.getSimpleName()));
        first = false;
    }
    StatementTree stat = make.Return(make.Binary(Tree.Kind.PLUS, exp, make.Literal('}'))); //NOI18N
    return Collections.singletonList(stat);
}
 
Example #18
Source File: CreateClassFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ChangeInfo implement() throws Exception {
    //use the original cp-info so it is "sure" that the target can be resolved:
    JavaSource js = JavaSource.create(cpInfo, targetFile);
    
    ModificationResult diff = js.runModificationTask(new Task<WorkingCopy>() {

        public void run(final WorkingCopy working) throws IOException {
            working.toPhase(Phase.RESOLVED);
            TypeElement targetType = target.resolve(working);
            
            if (targetType == null) {
                ErrorHintsProvider.LOG.log(Level.INFO, "Cannot resolve target."); // NOI18N
                return;
            }
            
            TreePath targetTree = working.getTrees().getPath(targetType);
            
            if (targetTree == null) {
                ErrorHintsProvider.LOG.log(Level.INFO, "Cannot resolve target tree: " + targetType.getQualifiedName() + "."); // NOI18N
                return;
            }
            
            TreeMaker make = working.getTreeMaker();
            MethodTree constr = make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), "<init>", null, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}" /*XXX*/, null); // NOI18N
            ClassTree innerClass = make.Class(make.Modifiers(modifiers), name, Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>singletonList(constr));
            
            innerClass = createConstructor(working, new TreePath(targetTree, innerClass));
            
            working.rewrite(targetTree.getLeaf(), GeneratorUtilities.get(working).insertClassMember((ClassTree)targetTree.getLeaf(), innerClass));
        }
    });
    
    return Utilities.commitAndComputeChangeInfo(targetFile, diff, null);
}
 
Example #19
Source File: ExpressionToTypeInfo.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private ExpressionInfo treeToInfo(TreePath tp) {
    if (tp != null) {
        Tree tree = tp.getLeaf();
        if (tree instanceof ExpressionTree) {
            ExpressionInfo ei = new ExpressionInfo();
            ei.tree = (ExpressionTree) tree;
            Type type = pathToType(tp, tree);
            if (type != null) {
                switch (type.getKind()) {
                    case VOID:
                    case NONE:
                    case ERROR:
                    case OTHER:
                        break;
                    case NULL:
                        ei.isNonVoid = true;
                        ei.typeName = OBJECT_TYPE_NAME;
                        break;
                    default: {
                        ei.isNonVoid = true;
                        ei.typeName = varTypeName(type);
                        if (ei.typeName == null) {
                            ei.typeName = OBJECT_TYPE_NAME;
                        }
                        break;
                    }
                }
            }
            return ei;
        }
    }
    return null;
}
 
Example #20
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
  if (overLaps(tree, state)) {
    return Description.NO_MATCH;
  }
  ExpressionTree et = tree.getExpression();
  if (et != null && et.getKind().equals(Kind.BOOLEAN_LITERAL)) {
    return Description.NO_MATCH;
  }

  Value x = evalExpr(et, state);
  boolean update = false;
  String replacementString = EMPTY;

  if (x.equals(Value.TRUE)) {
    update = true;
    replacementString = TRUE;
  } else if (x.equals(Value.FALSE)) {
    update = true;
    replacementString = FALSE;
  }

  if (update) {
    Description.Builder builder = buildDescription(tree);
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    fixBuilder.replace(et, replacementString);
    decrementAllSymbolUsages(et, state, fixBuilder);
    builder.addFix(fixBuilder.build());
    endPos = state.getEndPosition(tree);
    return builder.build();
  }
  return Description.NO_MATCH;
}
 
Example #21
Source File: Ifs.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ExpressionTree negateBinaryOperator(WorkingCopy copy, Tree original, Kind newKind, boolean negateOperands) {
    BinaryTree bt = (BinaryTree) original;
    if (negateOperands) {
        negate(copy, bt.getLeftOperand(), original);
        negate(copy, bt.getRightOperand(), original);
    }
    return copy.getTreeMaker().Binary(newKind, bt.getLeftOperand(), bt.getRightOperand());
}
 
Example #22
Source File: MagicSurroundWithTryCatchFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private StatementTree createFinallyCloseBlockStatement(VariableTree origDeclaration) {
    Trees trees = info.getTrees();
    TypeMirror tm = trees.getTypeMirror(statement);
    ElementUtilities elUtils = info.getElementUtilities();
    Iterable iterable = elUtils.getMembers(tm, new ElementAcceptor() {
        public boolean accept(Element e, TypeMirror type) {
            return e.getKind() == ElementKind.METHOD && "close".equals(e.getSimpleName().toString()); // NOI18N
        }
    });
    boolean throwsIO = false;
    for (Iterator iter = iterable.iterator(); iter.hasNext(); ) {
        ExecutableElement elem = (ExecutableElement) iter.next();
        if (!elem.getParameters().isEmpty()) {
            continue;
        } else {
             for (TypeMirror typeMirror : elem.getThrownTypes()) {
                 if ("java.io.IOException".equals(typeMirror.toString())) { // NOI18N
                     throwsIO = true;
                     break;
                 }
             }
        }
    }
    
    CharSequence name = origDeclaration.getName();
    StatementTree close = make.ExpressionStatement(make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.MemberSelect(make.Identifier(name), "close"), Collections.<ExpressionTree>emptyList()));
    StatementTree result = close;
    if (throwsIO) {
        result = make.Try(make.Block(Collections.singletonList(close), false), Collections.singletonList(createCatch(info, make, statement, inferName(info, statement), info.getElements().getTypeElement("java.io.IOException").asType())), null);
        }
    
    return result;
}
 
Example #23
Source File: MethodTest2.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public MethodTree makeMethod() {
    Set<Modifier> emptyModifs = Collections.emptySet();
    List<TypeParameterTree> emptyTpt= Collections.emptyList();
    List<VariableTree> emptyVt = Collections.emptyList();
    List<ExpressionTree> emptyEt = Collections.emptyList();
    return make.Method(
              make.Modifiers(emptyModifs),
              (CharSequence)"",
              (ExpressionTree) null,
              emptyTpt,
              emptyVt,
              emptyEt,
              (BlockTree) null,
              (ExpressionTree)null);                    
}
 
Example #24
Source File: AddJavaFXPropertyMaker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private VariableTree createField(DeclaredType selectedType, ExpressionTree implementationType) {
    String initializer = config.getInitializer();
    NewClassTree newClass = make.NewClass(null,
            Collections.emptyList(),
            implementationType,
            Collections.singletonList(make.Identifier(initializer)), null);
    VariableTree property = make.Variable(
            make.Modifiers(EnumSet.of(Modifier.PRIVATE, Modifier.FINAL)),
            config.getName(),
            getTypeTree(selectedType),
            newClass);
    return property;
}
 
Example #25
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitNewClass(NewClassTree tree, Void p) {
    NewClassTree n = make.NewClass((ExpressionTree)tree.getEnclosingExpression(),
            (List<? extends ExpressionTree>)tree.getTypeArguments(),
            tree.getIdentifier(), tree.getArguments(), tree.getClassBody());
    model.setElement(n, model.getElement(tree));
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
 
Example #26
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testLambdaExpression2FullBody() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public static void taragui() {\n" +
        "        ChangeListener l = (e) -> 1;\n" + 
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public static void taragui() {\n" +
        "        ChangeListener l = (e) -> {\n" +
        "            return 1;\n" +
        "        };\n" + 
        "    }\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(final WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            final TreeMaker make = workingCopy.getTreeMaker();
            new ErrorAwareTreeScanner<Void, Void>() {
                @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void p) {
                    workingCopy.rewrite(node, make.setLambdaBody(node, make.Block(Collections.singletonList(make.Return((ExpressionTree) node.getBody())), false)));
                    return super.visitLambdaExpression(node, p);
                }
            }.scan(workingCopy.getCompilationUnit(), null);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #27
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
private void visitToDeclare(
    DeclarationKind kind,
    Direction annotationsDirection,
    VariableTree node,
    Optional<ExpressionTree> initializer,
    String equals,
    Optional<String> trailing) {
  sync(node);
  Optional<TypeWithDims> typeWithDims;
  Tree type;
  if (node.getType() != null) {
    TypeWithDims extractedDims = DimensionHelpers.extractDims(node.getType(), SortedDims.YES);
    typeWithDims = Optional.of(extractedDims);
    type = extractedDims.node;
  } else {
    typeWithDims = Optional.empty();
    type = null;
  }
  declareOne(
      kind,
      annotationsDirection,
      Optional.of(node.getModifiers()),
      type,
      node.getName(),
      "",
      equals,
      initializer,
      trailing,
      /* receiverExpression= */ Optional.empty(),
      typeWithDims);
}
 
Example #28
Source File: OWSMPoliciesEditor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private AnnotationTree createPolicyAnnotation( TreeMaker maker , String id) {
    ExpressionTree idTree = maker.Assignment(maker.Identifier(
            PoliciesVisualPanel.URI), maker.Literal(id));
    return maker.Annotation(
            maker.QualIdent(PoliciesVisualPanel.OWSM_SECURITY_POLICY), 
            Collections.singletonList( idTree ) );
}
 
Example #29
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 */
private ExpressionTree generateNoArgConstructorCall(TreeMaker maker,
                                                    TypeElement cls,
                                                    CharSequence instanceClsName) {
    return maker.NewClass(
            null,                                   //enclosing instance
            Collections.<ExpressionTree>emptyList(),//type arguments
            instanceClsName != null
                    ? maker.Identifier(instanceClsName)
                    : maker.QualIdent(cls),         //class identifier
            Collections.<ExpressionTree>emptyList(),//arguments list
            null);                                  //class body
}
 
Example #30
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;
}