Java Code Examples for com.sun.source.tree.ClassTree#getMembers()

The following examples show how to use com.sun.source.tree.ClassTree#getMembers() . 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: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
public void visitAnnotationType(ClassTree node) {
    sync(node);
    builder.open(ZERO);
    visitAndBreakModifiers(node.getModifiers(), Direction.VERTICAL, Optional.<BreakTag>absent());
    builder.open(ZERO);
    token("@");
    token("interface");
    builder.breakOp(" ");
    visit(node.getSimpleName());
    builder.close();
    builder.close();
    if (node.getMembers() == null) {
        builder.open(plusFour);
        token(";");
        builder.close();
    } else {
        addBodyDeclarations(node.getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
    }
    builder.guessToken(";");
}
 
Example 2
Source File: AddPropertyCodeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitClass(ClassTree node, Void p) {
    final SourcePositions sourcePositions = wc.getTrees().getSourcePositions();
    final TreeMaker make = wc.getTreeMaker();
    List<Tree> members = new LinkedList<Tree>();
    ClassTree classTree = node;
    for (Tree member : node.getMembers()) {
        int s = (int) sourcePositions.getStartPosition(wc.getCompilationUnit(), member);
        int e = (int) sourcePositions.getEndPosition(wc.getCompilationUnit(), member);
        if (s >= start && e <= end) {
            classTree = make.removeClassMember(classTree, member);
            members.add(member);
        }
    }
    classTree = GeneratorUtils.insertClassMembers(wc, classTree, members, start);
    wc.rewrite(node, classTree);
    return super.visitClass(classTree, p);
}
 
Example 3
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
public void visitAnnotationType(ClassTree node) {
  sync(node);
  builder.open(ZERO);
  visitAndBreakModifiers(
      node.getModifiers(),
      Direction.VERTICAL,
      /* declarationAnnotationBreak= */ Optional.empty());
  builder.open(ZERO);
  token("@");
  token("interface");
  builder.breakOp(" ");
  visit(node.getSimpleName());
  builder.close();
  builder.close();
  if (node.getMembers() == null) {
    builder.open(plusFour);
    token(";");
    builder.close();
  } else {
    addBodyDeclarations(node.getMembers(), BracesOrNot.YES, FirstDeclarationsOrNot.YES);
  }
  builder.guessToken(";");
}
 
Example 4
Source File: UClassDecl.java    From Refaster with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public Unifier visitClass(ClassTree node, @Nullable Unifier unifier) {
  // We want to skip e.g. autogenerated init members, so we do this by hand...
  Iterator<UMethodDecl> membersItr = getMembers().iterator();
  for (Tree targetMember : node.getMembers()) {
    if (targetMember instanceof MethodTree) {
      MethodTree targetMethodDecl = (MethodTree) targetMember;
      if (targetMethodDecl.getReturnType() != null) {
        unifier = membersItr.hasNext()
            ? membersItr.next().unify(targetMethodDecl, unifier)
            : null;
      }
    }
  }
  return membersItr.hasNext() ? null : unifier;
}
 
Example 5
Source File: GeneratorUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static ClassTree insertClassMembers(WorkingCopy wc, ClassTree clazz, List<? extends Tree> members, int offset) throws IllegalStateException {
    if (offset < 0 || getCodeStyle(wc).getClassMemberInsertionPoint() != CodeStyle.InsertionPoint.CARET_LOCATION)
        return GeneratorUtilities.get(wc).insertClassMembers(clazz, members);
    int index = 0;
    SourcePositions sp = wc.getTrees().getSourcePositions();
    GuardedDocument gdoc = null;
    try {
        Document doc = wc.getDocument();
        if (doc != null && doc instanceof GuardedDocument)
            gdoc = (GuardedDocument)doc;
    } catch (IOException ioe) {}
    Tree lastMember = null;
    for (Tree tree : clazz.getMembers()) {
        if (offset <= sp.getStartPosition(wc.getCompilationUnit(), tree)) {
            if (gdoc == null)
                break;
            int pos = (int)(lastMember != null ? sp.getEndPosition(wc.getCompilationUnit(), lastMember) : sp.getStartPosition(wc.getCompilationUnit(), clazz));
            pos = gdoc.getGuardedBlockChain().adjustToBlockEnd(pos);
            if (pos <= sp.getStartPosition(wc.getCompilationUnit(), tree))
                break;
        }
        index++;
        lastMember = tree;
    }
    TreeMaker tm = wc.getTreeMaker();
    for (int i = members.size() - 1; i >= 0; i--) {
        clazz = tm.insertClassMember(clazz, index, members.get(i));
    }
    return clazz;
}
 
Example 6
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 */
private ClassTree generateMissingSuiteClassMembers(
                                        ClassTree tstClass,
                                        TreePath tstClassTreePath,
                                        List<String> suiteMembers,
                                        boolean isNewTestClass,
                                        WorkingCopy workingCopy) {
    final TreeMaker maker = workingCopy.getTreeMaker();

    List<? extends Tree> tstMembersOrig = tstClass.getMembers();
    List<Tree> tstMembers = new ArrayList<Tree>(tstMembersOrig.size() + 2);
    tstMembers.addAll(tstMembersOrig);
    boolean membersChanged = false;

    ClassMap classMap = ClassMap.forClass(tstClass,
                                          tstClassTreePath,
                                          workingCopy.getTrees());

    membersChanged |= generateMissingInitMembers(tstMembers,
                                                     classMap,
                                                     workingCopy);

    return finishSuiteClass(tstClass,
                            tstClassTreePath,
                            tstMembers,
                            suiteMembers,
                            membersChanged,
                            classMap,
                            workingCopy);
}
 
Example 7
Source File: GeneratorUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static ClassTree insertClassMembers(WorkingCopy wc, ClassTree clazz, List<? extends Tree> members, int offset) throws IllegalStateException {
    if (offset < 0 || getCodeStyle(wc).getClassMemberInsertionPoint() != CodeStyle.InsertionPoint.CARET_LOCATION) {
        return GeneratorUtilities.get(wc).insertClassMembers(clazz, members);
    }
    int index = 0;
    SourcePositions sp = wc.getTrees().getSourcePositions();
    GuardedDocument gdoc = null;
    try {
        Document doc = wc.getDocument();
        if (doc != null && doc instanceof GuardedDocument) {
            gdoc = (GuardedDocument)doc;
        }
    } catch (IOException ioe) {}
    Tree lastMember = null;
    for (Tree tree : clazz.getMembers()) {
        if (offset <= sp.getStartPosition(wc.getCompilationUnit(), tree)) {
            if (gdoc == null) {
                break;
            }
            int pos = (int)(lastMember != null ? sp.getEndPosition(wc.getCompilationUnit(), lastMember) : sp.getStartPosition(wc.getCompilationUnit(), clazz));
            pos = gdoc.getGuardedBlockChain().adjustToBlockEnd(pos);
            if (pos <= sp.getStartPosition(wc.getCompilationUnit(), tree)) {
                break;
            }
        }
        index++;
        lastMember = tree;
    }
    TreeMaker tm = wc.getTreeMaker();
    for (int i = members.size() - 1; i >= 0; i--) {
        clazz = tm.insertClassMember(clazz, index, members.get(i));
    }
    return clazz;
}
 
Example 8
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertEnum(ClassTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  TypeElement element = (TypeElement) getElement(path);
  if (ElementUtil.isAnonymous(element)) {
    return convertClassDeclaration(node, parent).setPosition(getPosition(node));
  }
  EnumDeclaration newNode = new EnumDeclaration();
  convertBodyDeclaration(node, parent, node.getModifiers(), newNode);
  newNode
      .setName(convertSimpleName(element, getTypeMirror(path), getNamePosition(node)))
      .setTypeElement(element);
  for (Tree bodyDecl : node.getMembers()) {
    if (bodyDecl.getKind() == Kind.VARIABLE) {
      TreeNode var = convertVariableDeclaration((VariableTree) bodyDecl, path);
      if (var.getKind() == TreeNode.Kind.ENUM_CONSTANT_DECLARATION) {
        newNode.addEnumConstant((EnumConstantDeclaration) var);
      } else {
        newNode.addBodyDeclaration((BodyDeclaration) var);
      }
    } else if (bodyDecl.getKind() == Kind.BLOCK) {
      BlockTree javacBlock = (BlockTree) bodyDecl;
      Block block = (Block) convert(javacBlock, path);
      newNode.addBodyDeclaration(new Initializer(block, javacBlock.isStatic()));
    } else {
      newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl, path));
    }
  }
  return newNode;
}
 
Example 9
Source File: GeneratorUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void validate(CompilationInfo info) {
    TypeElement test = info.getElements().getTypeElement("test.Test");
    ClassTree ct = info.getTrees().getTree(test);
    assertNotNull(ct);

    int foundTestIdx = -1;

    int idx = 0;
    for (Tree t : ct.getMembers()) {
        Name name = null;
        switch(t.getKind()) {
        case VARIABLE:
            name = ((VariableTree)t).getName();
            break;
        case METHOD:
            name = ((MethodTree)t).getName();
            break;
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            name = ((ClassTree)t).getSimpleName();
            break;
        }
        if (name != null) {
            if (name.contentEquals("test")) {
                assertEquals(-1, foundTestIdx);
                foundTestIdx = idx;
            } else if (name.contentEquals("<init>") && ((MethodTree)t).getParameters().size() > 0) {
                assertEquals(-1, foundTestIdx);
                foundTestIdx = idx;
            }
        }
        idx++;
    }

    assertEquals(testIdx, foundTestIdx);
}
 
Example 10
Source File: StreamNullabilityPropagator.java    From NullAway with MIT License 5 votes vote down vote up
private void handleFilterAnonClass(
    StreamTypeRecord streamType,
    MethodInvocationTree observableDotFilter,
    ClassTree annonClassBody,
    VisitorState state) {
  for (Tree t : annonClassBody.getMembers()) {
    if (t instanceof MethodTree && ((MethodTree) t).getName().toString().equals("test")) {
      filterMethodOrLambdaSet.add(t);
      observableCallToInnerMethodOrLambda.put(observableDotFilter, t);
      handleChainFromFilter(streamType, observableDotFilter, t, state);
    }
  }
}
 
Example 11
Source File: TestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 */
@Override
protected ClassTree generateMissingInitMembers(ClassTree tstClass,
                                               TreePath tstClassTreePath,
                                               WorkingCopy workingCopy) {
    if (!setup.isGenerateBefore() && !setup.isGenerateAfter()
            && !setup.isGenerateBeforeClass() && !setup.isGenerateAfterClass()) {
        return tstClass;
    }

    ClassMap classMap = ClassMap.forClass(tstClass, tstClassTreePath,
                                          workingCopy.getTrees());

    if ((!setup.isGenerateBefore() || classMap.containsBefore())
            && (!setup.isGenerateAfter() || classMap.containsAfter())
            && (!setup.isGenerateBeforeClass() || classMap.containsBeforeClass())
            && (!setup.isGenerateAfterClass() || classMap.containsAfterClass())) {
        return tstClass;
    }

    final TreeMaker maker = workingCopy.getTreeMaker();

    List<? extends Tree> tstMembersOrig = tstClass.getMembers();
    List<Tree> tstMembers = new ArrayList<Tree>(tstMembersOrig.size() + 4);
    tstMembers.addAll(tstMembersOrig);

    generateMissingInitMembers(tstMembers, classMap, workingCopy);

    ClassTree newClass = maker.Class(
            tstClass.getModifiers(),
            tstClass.getSimpleName(),
            tstClass.getTypeParameters(),
            tstClass.getExtendsClause(),
            (List<? extends ExpressionTree>) tstClass.getImplementsClause(),
            tstMembers);
    return newClass;
}
 
Example 12
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testObjectEditing1() throws Exception {
    FileObject java = FileUtil.createData(fo, "X.java");
    final String what1 = "package java.lang; public class Object {\n" +
                         "  public int hashCode() {return 0;}" +
                         "  public static int hashCode(Object o) {return 0;}" +
                         "  public boolean equals(Object o) {return false;}" +
                         "  public boolean equals(Object o1, Object o2) {return false;}" +
                         "  \n";

    String what2 =
        "}\n";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);

    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);

    class TaskImpl implements Task<WorkingCopy> {
        public void run(WorkingCopy copy) throws Exception {
            copy.toPhase(JavaSource.Phase.RESOLVED);
            ClassTree clazzTree = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
            TreePath clazz = new TreePath(new TreePath(copy.getCompilationUnit()), clazzTree);
            List<VariableElement> vars = new LinkedList<VariableElement>();

            for (Tree m : clazzTree.getMembers()) {
                if (m.getKind() == Kind.VARIABLE) {
                    vars.add((VariableElement) copy.getTrees().getElement(new TreePath(clazz, m)));
                }
            }

            EqualsHashCodeGenerator.overridesHashCodeAndEquals(copy, copy.getTrees().getElement(clazz), null);
        }
    }

    TaskImpl t = new TaskImpl();

    js.runModificationTask(t);
}
 
Example 13
Source File: EntityManagerGenerationStrategySupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected int getIndexForField(ClassTree clazz){
    int result = 0;
    for (Tree each : clazz.getMembers()){
        if (Tree.Kind.VARIABLE == each.getKind()){
            result++;
        }
    }
    return result;
}
 
Example 14
Source File: ClassStructure.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean testClassMayBeInterface(Trees trees, TreeUtilities treeUtilities, TreePath path) {
    final ClassTree cls = (ClassTree) path.getLeaf();
    if (!treeUtilities.isClass(cls)) {
        return true;
    }
    final Element element = trees.getElement(path);
    if (element == null) return false; //see bug #221820
    final TypeMirror superclass = element.getKind().isClass() ? ((TypeElement) element).getSuperclass() : null;
    if (superclass == null || superclass.getKind() != TypeKind.DECLARED
            || !"java.lang.Object".contentEquals(((TypeElement) ((DeclaredType) superclass).asElement()).getQualifiedName())) { //NOI18N
        return false;
    }
    for (Tree member : cls.getMembers()) {
        TreePath memberPath = TreePath.getPath(path, member);
        if (!treeUtilities.isSynthetic(memberPath)) {
            switch (member.getKind()) {
                case VARIABLE:
                    if (!((VariableTree) member).getModifiers().getFlags().containsAll(EnumSet.of(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL))) {
                        return false;
                    }
                    break;
                case METHOD:
                    if (!((MethodTree) member).getModifiers().getFlags().containsAll(EnumSet.of(Modifier.PUBLIC, Modifier.ABSTRACT))) {
                        return false;
                    }
                    break;
                case ANNOTATION_TYPE:
                case CLASS:
                case ENUM:
                case INTERFACE:
                    if (!testClassMayBeInterface(trees, treeUtilities, memberPath)) {
                        return false;
                    }
                    break;
                default:
                    return false;
            }
        }
    }
    return true;
}
 
Example 15
Source File: EntityResourcesGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void generateResourceMethods( FileObject fileObject , 
        final String entityFQN, final String idClass) throws IOException 
{
    JavaSource javaSource = JavaSource.forFileObject( fileObject );
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        
        @Override
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree tree = workingCopy.getCompilationUnit();
            
            ClassTree classTree = (ClassTree)tree.getTypeDecls().get(0);
            TypeElement classElement = (TypeElement)workingCopy.getTrees().
                getElement(TreePath.getPath( tree, classTree));
            
            List<String> imports = getResourceImports( entityFQN );
            JavaSourceHelper.addImports(workingCopy, imports.toArray(
                    new String[ imports.size()]));
            
            GenerationUtils genUtils = GenerationUtils.newInstance(workingCopy);
            TreeMaker maker = workingCopy.getTreeMaker();
            
            List<Tree> members = new ArrayList<Tree>(classTree.getMembers());
            // make empty CTOR
            MethodTree constructor = maker.Constructor(
                    genUtils.createModifiers(Modifier.PUBLIC),
                    Collections.<TypeParameterTree>emptyList(),
                    Collections.<VariableTree>emptyList(),
                    Collections.<ExpressionTree>emptyList(),
                    "{}");                                      //NOI18N
            members.add(constructor);
            
            List<RestGenerationOptions> restGenerationOptions = 
                getRestFacadeMethodOptions(entityFQN, idClass);
            
            for(RestGenerationOptions option: restGenerationOptions) {
                generateRestMethod(classElement, genUtils, maker, members,
                        option);
            }
            
            ModifiersTree modifiersTree = addResourceAnnotation(entityFQN,
                    classTree, genUtils, maker);
            
            // final step : generate new class tree
            List<Tree> implementsClause = new ArrayList<Tree>(
                    classTree.getImplementsClause());
            ClassTree newClassTree = maker.Class(
                    modifiersTree,
                    classTree.getSimpleName(),
                    classTree.getTypeParameters(),
                    classTree.getExtendsClause(),
                    implementsClause,
                    members);

            workingCopy.rewrite(classTree, newClassTree);
        }

    };
    javaSource.runModificationTask(task).commit();
}
 
Example 16
Source File: Java14InputAstVisitor.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
public void visitRecordDeclaration(ClassTree node) {
  sync(node);
  List<Op> breaks =
      visitModifiers(
          node.getModifiers(),
          Direction.VERTICAL,
          /* declarationAnnotationBreak= */ Optional.empty());
  Verify.verify(node.getExtendsClause() == null);
  boolean hasSuperInterfaceTypes = !node.getImplementsClause().isEmpty();
  builder.addAll(breaks);
  token("record");
  builder.space();
  visit(node.getSimpleName());
  if (!node.getTypeParameters().isEmpty()) {
    token("<");
  }
  builder.open(plusFour);
  {
    if (!node.getTypeParameters().isEmpty()) {
      typeParametersRest(node.getTypeParameters(), hasSuperInterfaceTypes ? plusFour : ZERO);
    }
    ImmutableList<JCVariableDecl> parameters =
        compactRecordConstructor(node)
            .map(m -> ImmutableList.copyOf(m.getParameters()))
            .orElseGet(() -> recordVariables(node));
    token("(");
    if (!parameters.isEmpty()) {
      // Break before args.
      builder.breakToFill("");
    }
    // record headers can't declare receiver parameters
    visitFormals(/* receiver= */ Optional.empty(), parameters);
    token(")");
    if (hasSuperInterfaceTypes) {
      builder.breakToFill(" ");
      builder.open(node.getImplementsClause().size() > 1 ? plusFour : ZERO);
      token("implements");
      builder.space();
      boolean first = true;
      for (Tree superInterfaceType : node.getImplementsClause()) {
        if (!first) {
          token(",");
          builder.breakOp(" ");
        }
        scan(superInterfaceType, null);
        first = false;
      }
      builder.close();
    }
  }
  builder.close();
  if (node.getMembers() == null) {
    token(";");
  } else {
    List<Tree> members =
        node.getMembers().stream()
            .filter(t -> (TreeInfo.flags((JCTree) t) & Flags.GENERATED_MEMBER) == 0)
            .collect(toImmutableList());
    addBodyDeclarations(members, BracesOrNot.YES, FirstDeclarationsOrNot.YES);
  }
  dropEmptyDeclarations();
}
 
Example 17
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void test142212() throws Exception {
    EqualsHashCodeGenerator.randomNumber = 1;
    
    FileObject java = FileUtil.createData(fo, "X.java");
    final String what1 = "class X {\n" +
                         "  private byte b;\n" +
                         "  private int[] x;\n" +
                         "  private String[] y;\n" +
                         "  private String s;\n" +
                         "  private Object o;\n";

    String what2 =
        "}\n";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);

    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);

    class TaskImpl implements Task<WorkingCopy> {
        public void run(WorkingCopy copy) throws Exception {
            copy.toPhase(JavaSource.Phase.RESOLVED);
            ClassTree clazzTree = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
            TreePath clazz = new TreePath(new TreePath(copy.getCompilationUnit()), clazzTree);
            List<VariableElement> vars = new LinkedList<VariableElement>();

            for (Tree m : clazzTree.getMembers()) {
                if (m.getKind() == Kind.VARIABLE) {
                    vars.add((VariableElement) copy.getTrees().getElement(new TreePath(clazz, m)));
                }
            }

            EqualsHashCodeGenerator.generateEqualsAndHashCode(copy, clazz, vars, vars, -1);
        }
    }

    TaskImpl t = new TaskImpl();

    js.runModificationTask(t).commit();

    DataObject dObj = DataObject.find(java);
    EditorCookie ec = dObj != null ? dObj.getCookie(org.openide.cookies.EditorCookie.class) : null;
    Document doc = ec != null ? ec.getDocument() : null;
    
    String result = doc != null ? doc.getText(0, doc.getLength()) : TestUtilities.copyFileToString(FileUtil.toFile(java));
    String golden = "\nimport java.util.Arrays;\n" +
                    "class X {\n" +
                    "  private byte b;\n" +
                    "  private int[] x;\n" +
                    "  private String[] y;\n" +
                    "  private String s;\n" +
                    "  private Object o;\n" +
                    "    @Override\n" +
                    "    public int hashCode() {\n" +
                    "        int hash = 1;\n" +
                    "        hash = 1 * hash + this.b;\n" +
                    "        hash = 1 * hash + Arrays.hashCode(this.x);\n" +
                    "        hash = 1 * hash + Arrays.deepHashCode(this.y);\n" +
                    "        hash = 1 * hash + (this.s != null ? this.s.hashCode() : 0);\n" +
                    "        hash = 1 * hash + (this.o != null ? this.o.hashCode() : 0);\n" +
                    "        return hash;\n" +
                    "    }\n" +
                    "    @Override\n" +
                    "    public boolean equals(Object obj) {\n" +
                    "        if (this == obj) {\n" +
                    "            return true;\n" +
                    "        }\n" +
                    "        if (obj == null) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (getClass() != obj.getClass()) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        final X other = (X) obj;\n" +
                    "        if (this.b != other.b) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if ((this.s == null) ? (other.s != null) : !this.s.equals(other.s)) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (!Arrays.equals(this.x, other.x)) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (!Arrays.deepEquals(this.y, other.y)) {\n" +
                    "            return false;\n" +
                    "        }" +
                    "        if (this.o != other.o && (this.o == null || !this.o.equals(other.o))) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        return true;\n" +
                    "    }\n" +
                    "}\n";

    result = result.replaceAll("[ \t\n]+", " ");
    golden = golden.replaceAll("[ \t\n]+", " ");
    
    assertEquals(golden, result);
}
 
Example 18
Source File: NullAway.java    From NullAway with MIT License 4 votes vote down vote up
/**
 * @param enclosingClassPath TreePath to class
 * @param state visitor state
 * @return a map from each initializer <em>i</em> to the fields known to be initialized before
 *     <em>i</em> executes
 */
private Multimap<Tree, Element> computeTree2Init(
    TreePath enclosingClassPath, VisitorState state) {
  ClassTree enclosingClass = (ClassTree) enclosingClassPath.getLeaf();
  ImmutableMultimap.Builder<Tree, Element> builder = ImmutableMultimap.builder();
  // NOTE: this set includes both instance and static fields
  Set<Element> initThusFar = new LinkedHashSet<>();
  Set<MethodTree> constructors = new LinkedHashSet<>();
  AccessPathNullnessAnalysis nullnessAnalysis = getNullnessAnalysis(state);
  // NOTE: we assume the members are returned in their syntactic order.  This has held
  // true in our testing
  for (Tree memberTree : enclosingClass.getMembers()) {
    if (memberTree instanceof VariableTree || memberTree instanceof BlockTree) {
      // putAll does not keep a reference to initThusFar, so we don't need to make a copy here
      builder.putAll(memberTree, initThusFar);
    }
    if (memberTree instanceof BlockTree) {
      BlockTree blockTree = (BlockTree) memberTree;
      // add whatever gets initialized here
      TreePath memberPath = new TreePath(enclosingClassPath, memberTree);
      if (blockTree.isStatic()) {
        initThusFar.addAll(
            nullnessAnalysis.getNonnullStaticFieldsAtExit(memberPath, state.context));
      } else {
        initThusFar.addAll(
            nullnessAnalysis.getNonnullFieldsOfReceiverAtExit(memberPath, state.context));
      }
    }
    if (memberTree instanceof MethodTree) {
      MethodTree methodTree = (MethodTree) memberTree;
      if (isConstructor(methodTree)) {
        constructors.add(methodTree);
      }
    }
  }
  // all the initializer blocks have run before any code inside a constructor
  constructors.stream().forEach((c) -> builder.putAll(c, initThusFar));
  Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol(enclosingClass);
  FieldInitEntities entities = class2Entities.get(classSymbol);
  if (entities.instanceInitializerMethods().size() == 1) {
    MethodTree initMethod = entities.instanceInitializerMethods().iterator().next();
    // collect the fields that may not be initialized by *some* constructor NC
    Set<Symbol> constructorUninitSymbols = class2ConstructorUninit.get(classSymbol);
    // fields initialized after constructors is initThusFar + (nonNullFields - constructorUninit)
    Sets.SetView<Element> initAfterConstructors =
        Sets.union(
            initThusFar,
            Sets.difference(entities.nonnullInstanceFields(), constructorUninitSymbols));
    builder.putAll(initMethod, initAfterConstructors);
  }
  if (entities.staticInitializerMethods().size() == 1) {
    MethodTree staticInitMethod = entities.staticInitializerMethods().iterator().next();
    // constructors aren't relevant here; just use initThusFar
    builder.putAll(staticInitMethod, initThusFar);
  }
  return builder.build();
}
 
Example 19
Source File: OrganizeMembers.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription checkMembers(final HintContext context) {
    for (Diagnostic<?> d : context.getInfo().getDiagnostics()) {
        if (Hacks.isSyntaxError(d)) {
            return null;
        }
    }
    Source source = context.getInfo().getSnapshot().getSource();
    try {
        ModificationResult result = ModificationResult.runModificationTask(Collections.singleton(source), new UserTask() {
            @Override
            public void run(ResultIterator resultIterator) throws Exception {
                WorkingCopy copy = WorkingCopy.get(resultIterator.getParserResult());
                copy.toPhase(Phase.RESOLVED);
                doOrganizeMembers(copy, context.getPath());
            }
        });
        List<? extends Difference> diffs = result.getDifferences(source.getFileObject());
        if (diffs != null && !diffs.isEmpty() && !checkGuarded(context.getInfo().getDocument(), diffs)) {
            Fix fix = new OrganizeMembersFix(context.getInfo(), context.getPath()).toEditorFix();
            SourcePositions sp = context.getInfo().getTrees().getSourcePositions();
            int offset = diffs.get(0).getStartPosition().getOffset();
            LineMap lm = context.getInfo().getCompilationUnit().getLineMap();
            long lno = lm.getLineNumber(offset);
            if (lno >= 1) {
                offset = (int)lm.getStartPosition(lno);
            }
            CompilationUnitTree cut = context.getPath().getCompilationUnit();
            ClassTree clazz = (ClassTree) context.getPath().getLeaf();
            for (Tree member : clazz.getMembers()) {
                if (context.getInfo().getTreeUtilities().isSynthetic(new TreePath(context.getPath(), member))) continue;
                if (sp.getStartPosition(cut, member) >= offset) {
                    return ErrorDescriptionFactory.forTree(context, member, NbBundle.getMessage(OrganizeMembers.class, "MSG_OragnizeMembers"), fix); //NOI18N
                }
            }
            return ErrorDescriptionFactory.forTree(context, clazz, NbBundle.getMessage(OrganizeMembers.class, "MSG_OragnizeMembers"), fix); //NOI18N
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}
 
Example 20
Source File: JaxWsCodeGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
        public void run(CompilationController controller) throws IOException {
            controller.toPhase(Phase.ELEMENTS_RESOLVED);
            CompilationUnitTree cut = controller.getCompilationUnit();

            TypeElement thisTypeEl = SourceUtils.getPublicTopLevelElement(controller);
            if (thisTypeEl != null) {
                ClassTree javaClass = controller.getTrees().getTree(thisTypeEl);
                // find if class is Injection Target
                generateWsRefInjection[0] = InjectionTargetQuery.isInjectionTarget(controller, thisTypeEl);
//                if (generateWsRefInjection[0]) {
//                    // issue 126014 : check if J2EE Container supports EJBs (e.g. Tomcat 6 doesn't)
//                    Project project = FileOwnerQuery.getOwner(controller.getFileObject());
//                    generateWsRefInjection[0] = JaxWsUtils.isEjbSupported(project);
//                }

                insertServiceDef[0] = !generateWsRefInjection[0];
                if (isServletClass(controller, thisTypeEl)) {
                    // PENDING Need to compute pronter name from the method
                    printerName[0] = "out"; //NOI18N
                    argumentInitPart[0] = fixNamesInInitializationPart(argumentInitPart[0]);
                    argumentDeclPart[0] = fixNamesInDeclarationPart(argumentDeclPart[0]);
                }
                // compute the service field name
                if (generateWsRefInjection[0]) {
                    Set<String> serviceFieldNames = new HashSet<String>();
                    boolean injectionExists = false;
                    int memberOrder = 0;
                    for (Tree member : javaClass.getMembers()) {
                        // for the first inner class in top level
                        ++memberOrder;
                        if (VARIABLE == member.getKind()) {
                            // get variable type
                            VariableTree var = (VariableTree) member;
                            Tree typeTree = var.getType();
                            TreePath typeTreePath = controller.getTrees().getPath(cut, typeTree);
                            TypeElement typeEl = (TypeElement) controller.getTrees().getElement(typeTreePath);
                            if (typeEl != null) {
                                String variableType = typeEl.getQualifiedName().toString();
                                if (serviceJavaName.equals(variableType)) {
                                    serviceFName[0] = var.getName().toString();
                                    generateWsRefInjection[0] = false;
                                    injectionExists = true;
                                    break;
                                }
                            }
                            serviceFieldNames.add(var.getName().toString());
                        }
                    }
                    if (!injectionExists) {
                        serviceFName[0] = findProperServiceFieldName(serviceFieldNames);
                    }
                }
            }
        }