Java Code Examples for com.sun.source.tree.CompilationUnitTree#getImports()

The following examples show how to use com.sun.source.tree.CompilationUnitTree#getImports() . 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: T6963934.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
            fileManager.getJavaFileObjects(thisSrc));
    CompilationUnitTree tree = task.parse().iterator().next();
    int count = 0;
    for (ImportTree importTree : tree.getImports()) {
        System.out.println(importTree);
        count++;
    }
    int expected = 7;
    if (count != expected)
        throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
 
Example 2
Source File: T6963934.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
            fileManager.getJavaFileObjects(thisSrc));
    CompilationUnitTree tree = task.parse().iterator().next();
    int count = 0;
    for (ImportTree importTree : tree.getImports()) {
        System.out.println(importTree);
        count++;
    }
    int expected = 7;
    if (count != expected)
        throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
 
Example 3
Source File: ImportFormatTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testReplaceLine() throws IOException, FileStateInvalidException {
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            List<ImportTree> imports = new ArrayList<ImportTree>(cut.getImports());
            ImportTree oneImport = imports.remove(4);
            imports.add(4, make.Import(make.Identifier("java.util.Collection"), false));
            CompilationUnitTree unit = make.CompilationUnit(
                    cut.getPackageName(),
                    imports,
                    cut.getTypeDecls(),
                    cut.getSourceFile()
            );
            workingCopy.rewrite(cut, unit);
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertFiles("testReplaceLine_ImportFormatTest.pass");
}
 
Example 4
Source File: IsSigMethodCriterion.java    From annotation-tools with MIT License 6 votes vote down vote up
private static Context initImports(TreePath path) {
  CompilationUnitTree topLevel = path.getCompilationUnit();
  Context result = contextCache.get(topLevel);
  if (result != null) {
    return result;
  }

  ExpressionTree packageTree = topLevel.getPackageName();
  String packageName;
  if (packageTree == null) {
    packageName = ""; // the default package
  } else {
    packageName = packageTree.toString();
  }

  List<String> imports = new ArrayList<>();
  for (ImportTree i : topLevel.getImports()) {
    String imported = i.getQualifiedIdentifier().toString();
    imports.add(imported);
  }

  result = new Context(packageName, imports);
  contextCache.put(topLevel, result);
  return result;
}
 
Example 5
Source File: T6963934.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
            fileManager.getJavaFileObjects(thisSrc));
    CompilationUnitTree tree = task.parse().iterator().next();
    int count = 0;
    for (ImportTree importTree : tree.getImports()) {
        System.out.println(importTree);
        count++;
    }
    int expected = 7;
    if (count != expected)
        throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
 
Example 6
Source File: T6963934.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
            fileManager.getJavaFileObjects(thisSrc));
    CompilationUnitTree tree = task.parse().iterator().next();
    int count = 0;
    for (ImportTree importTree : tree.getImports()) {
        System.out.println(importTree);
        count++;
    }
    int expected = 7;
    if (count != expected)
        throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
 
Example 7
Source File: ImportFormatTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testRemoveLastImport() throws IOException, FileStateInvalidException {
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            List<ImportTree> imports = new ArrayList<ImportTree>(cut.getImports());
            imports.remove(1);
            CompilationUnitTree unit = make.CompilationUnit(
                    cut.getPackageName(),
                    imports,
                    cut.getTypeDecls(),
                    cut.getSourceFile()
            );
            workingCopy.rewrite(cut, unit);
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertFiles("testRemoveLastImport_ImportFormatTest.pass");
}
 
Example 8
Source File: ImportFormatTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAddSeveral() throws IOException, FileStateInvalidException {
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            List<ImportTree> imports = (List<ImportTree>) cut.getImports();
            imports.add(make.Import(make.Identifier("java.util.List"), false));
            imports.add(make.Import(make.Identifier("java.util.Set"), false));
            imports.add(make.Import(make.Identifier("javax.swing.CellRendererPane"), false));
            imports.add(make.Import(make.Identifier("javax.swing.BorderFactory"), false));
            imports.add(make.Import(make.Identifier("javax.swing.ImageIcon"), false));
            imports.add(make.Import(make.Identifier("javax.swing.InputVerifier"), false));
            imports.add(make.Import(make.Identifier("javax.swing.GrayFilter"), false));
            imports.add(make.Import(make.Identifier("javax.swing.JFileChooser"), false));
            imports.add(make.Import(make.Identifier("javax.swing.AbstractAction"), false));
            CompilationUnitTree unit = make.CompilationUnit(
                    cut.getPackageName(),
                    imports,
                    cut.getTypeDecls(),
                    cut.getSourceFile()
            );
            workingCopy.rewrite(cut, unit);
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertFiles("testAddSeveral_ImportFormatTest.pass");
}
 
Example 9
Source File: OrganizeImports.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind(Kind.COMPILATION_UNIT)
public static ErrorDescription checkImports(final HintContext context) {
    Source source = context.getInfo().getSnapshot().getSource();
    ModificationResult result = null;
    try {
        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);
                doOrganizeImports(copy, context.isBulkMode());
            }
        });
    } catch (ParseException ex) {
        Exceptions.printStackTrace(ex);
    }
    List<? extends Difference> diffs = result != null ? result.getDifferences(source.getFileObject()) : null;
    if (diffs != null && !diffs.isEmpty()) {
        Fix fix = new OrganizeImportsFix(context.getInfo(), context.getPath(), context.isBulkMode()).toEditorFix();
        SourcePositions sp = context.getInfo().getTrees().getSourcePositions();
        int offset = diffs.get(0).getStartPosition().getOffset();
        CompilationUnitTree cu = context.getInfo().getCompilationUnit();
        for (ImportTree imp : cu.getImports()) {
            if (sp.getEndPosition(cu, imp) >= offset)
                return ErrorDescriptionFactory.forTree(context, imp, NbBundle.getMessage(OrganizeImports.class, "MSG_OragnizeImports"), fix); //NOI18N
        }
        return ErrorDescriptionFactory.forTree(context, context.getInfo().getCompilationUnit().getImports().get(0), NbBundle.getMessage(OrganizeImports.class, "MSG_OragnizeImports"), fix); //NOI18N
    }
    return null;
}
 
Example 10
Source File: Imports.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<TreePathHandle> getAllImportsOfKind(CompilationInfo ci, ImportHintKind kind) {
    //allow only default and samepackage
    assert (kind == ImportHintKind.DEFAULT_PACKAGE || kind == ImportHintKind.SAME_PACKAGE);

    CompilationUnitTree cut = ci.getCompilationUnit();
    TreePath topLevel = new TreePath(cut);
    List<TreePathHandle> result = new ArrayList<TreePathHandle>(3);

    List<? extends ImportTree> imports = cut.getImports();
    for (ImportTree it : imports) {
        if (it.isStatic()) {
            continue; // XXX
        }
        if (it.getQualifiedIdentifier() instanceof MemberSelectTree) {
            MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();
            if (kind == ImportHintKind.DEFAULT_PACKAGE) {
                if (ms.getExpression().toString().equals(DEFAULT_PACKAGE)) {
                    result.add(TreePathHandle.create(new TreePath(topLevel, it), ci));
                }
            }
            if (kind == ImportHintKind.SAME_PACKAGE) {
                ExpressionTree packageName = cut.getPackageName();
                if (packageName != null &&
                    ms.getExpression().toString().equals(packageName.toString())) {
                    result.add(TreePathHandle.create(new TreePath(topLevel, it), ci));
                }
            }
        }
    }
    return result;
}
 
Example 11
Source File: InsertTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Collection<String> getImports(CompilationController controller) {
    Set<String> imports = new HashSet<String>();
    CompilationUnitTree cu = controller.getCompilationUnit();
    
    if (cu != null) {
        List<? extends ImportTree> importTrees = cu.getImports();
        
        for (ImportTree importTree : importTrees) {
            imports.add(importTree.getQualifiedIdentifier().toString());
        }
    }
    
    return imports;
}
 
Example 12
Source File: ImportsTrackerTestHelper.java    From buck with Apache License 2.0 5 votes vote down vote up
public static ImportsTracker loadImports(
    Elements elements, Types types, Trees trees, CompilationUnitTree compilationUnit) {
  TreePath compilationUnitPath = new TreePath(compilationUnit);
  ImportsTracker result =
      new ImportsTracker(elements, types, (PackageElement) trees.getElement(compilationUnitPath));
  for (ImportTree importTree : compilationUnit.getImports()) {
    handleImport(trees, result, new TreePath(compilationUnitPath, importTree));
  }
  return result;
}
 
Example 13
Source File: JaxWsCodeGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static boolean foundImport(String importStatement, CompilationUnitTree tree) {
    List<? extends ImportTree> imports = tree.getImports();
    for (ImportTree imp : imports) {
        if (importStatement.equals(imp.getQualifiedIdentifier().toString())) {
            return true;
        }
    }
    return false;
}
 
Example 14
Source File: SrcClassUtil.java    From manifold with Apache License 2.0 4 votes vote down vote up
private SrcClass makeSrcClass( String fqn, SrcClass enclosing, Symbol.ClassSymbol classSymbol, CompilationUnitTree compilationUnit, BasicJavacTask javacTask, IModule module, JavaFileManager.Location location, DiagnosticListener<JavaFileObject> errorHandler, boolean withMembers )
  {
    SrcClass srcClass;
    if( enclosing == null )
    {
      srcClass = new SrcClass( fqn, SrcClass.Kind.from( classSymbol.getKind() ), location, module, errorHandler )
        .modifiers( classSymbol.getModifiers() );
    }
    else
    {
      srcClass = new SrcClass( fqn, enclosing, SrcClass.Kind.from( classSymbol.getKind() ) )
        .modifiers( classSymbol.getModifiers() );
    }
    if( classSymbol.getEnclosingElement() instanceof Symbol.PackageSymbol && compilationUnit != null )
    {
      for( ImportTree imp: compilationUnit.getImports() )
      {
        if( imp.isStatic() )
        {
          srcClass.addStaticImport( imp.getQualifiedIdentifier().toString() );
        }
        else
        {
          srcClass.addImport( imp.getQualifiedIdentifier().toString() );
        }
      }
    }
    addAnnotations( srcClass, classSymbol );
    for( Symbol.TypeVariableSymbol typeVar: classSymbol.getTypeParameters() )
    {
      srcClass.addTypeVar( makeTypeVarType( typeVar ) );
    }
    Type superclass = classSymbol.getSuperclass();
    if( !(superclass instanceof NoType) )
    {
      srcClass.superClass( makeNestedType( superclass ) );
    }
    for( Type iface: classSymbol.getInterfaces() )
    {
      srcClass.addInterface( makeNestedType( iface ) );
    }
    if( withMembers )
    {
      java.util.List<Symbol> members = classSymbol.getEnclosedElements();
      for( Symbol sym: members )
      {
// include private members because:
// 1. @Jailbreak can expose private members
// 2. Compiler error messages are better when referencing an inaccessible method vs. a non-existent one
//        long modifiers = SrcAnnotated.modifiersFrom( sym.getModifiers() );
//        if( Modifier.isPrivate( (int)modifiers ) )
//        {
//          continue;
//        }

        if( sym instanceof Symbol.ClassSymbol )
        {
          addInnerClass( module, srcClass, sym, javacTask );
        }
        else if( sym instanceof Symbol.VarSymbol )
        {
          addField( srcClass, sym );
        }
        else if( sym instanceof Symbol.MethodSymbol )
        {
          if( !isEnumMethod( sym ) )
          {
            addMethod( module, srcClass, (Symbol.MethodSymbol)sym, javacTask );
          }
        }
      }

      addDefaultCtorForEnum( classSymbol, srcClass, members );
    }
    return srcClass;
  }
 
Example 15
Source File: JaxWsUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static void setSOAP12Binding(final FileObject implClassFo, 
        final boolean isSOAP12) 
{
    final JavaSource javaSource = JavaSource.forFileObject(implClassFo);
    final boolean isIncomplete[] = new boolean[1];
    final CancellableTask<WorkingCopy> modificationTask = 
        new CancellableTask<WorkingCopy>() 
    {
        @Override
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            TypeElement typeElement = SourceUtils.
                getPublicTopLevelElement(workingCopy);
            ClassTree javaClass = workingCopy.getTrees().getTree(typeElement);

            TypeElement bindingElement = workingCopy.getElements().
                getTypeElement(BINDING_TYPE_ANNOTATION);
            if (bindingElement == null) {
                isIncomplete[0] = true;
            }
            else {
                AnnotationTree bindingAnnotation = null;
                List<? extends AnnotationTree> annots = 
                    javaClass.getModifiers().getAnnotations();
                for (AnnotationTree an : annots) {
                    Tree ident = an.getAnnotationType();
                    TreePath anTreePath = workingCopy.getTrees().
                        getPath(workingCopy.getCompilationUnit(), ident);
                    TypeElement anElement = (TypeElement) workingCopy.getTrees().
                        getElement(anTreePath);
                    if ( anTreePath == null ){
                        isIncomplete[0] = true;
                    }
                    else if (anElement.getQualifiedName().
                            contentEquals(BINDING_TYPE_ANNOTATION)) 
                    {
                        bindingAnnotation = an;
                        break;
                    }
                }
                if (isSOAP12 && bindingAnnotation == null) {

                    ModifiersTree modifiersTree = javaClass.getModifiers();

                    AssignmentTree soapVersion = make.Assignment(
                            make.Identifier("value"),                   //NOI18N
                            make.Literal(OLD_SOAP12_NAMESPACE)); 
                    AnnotationTree soapVersionAnnotation = make.Annotation(
                            make.QualIdent(bindingElement),
                            Collections.<ExpressionTree>singletonList(soapVersion));

                    ModifiersTree newModifiersTree = make.
                        addModifiersAnnotation(modifiersTree, soapVersionAnnotation);

                    workingCopy.rewrite(modifiersTree, newModifiersTree);
                } 
                else if (!isSOAP12 && bindingAnnotation != null) {
                    ModifiersTree modifiers = javaClass.getModifiers();
                    ModifiersTree newModifiers = make.
                        removeModifiersAnnotation(modifiers, bindingAnnotation);
                    workingCopy.rewrite(modifiers, newModifiers);
                    CompilationUnitTree compileUnitTree = workingCopy.
                        getCompilationUnit();
                    List<? extends ImportTree> imports = 
                        compileUnitTree.getImports();
                    for (ImportTree imp : imports) {
                        Tree impTree = imp.getQualifiedIdentifier();
                        TreePath impTreePath = workingCopy.getTrees().
                            getPath(workingCopy.getCompilationUnit(), impTree);
                        TypeElement impElement = (TypeElement) workingCopy.getTrees().
                            getElement(impTreePath);
                        if ( impElement == null ){
                            isIncomplete[0] = true;
                        }
                        else if (impElement.getQualifiedName().
                                contentEquals(BINDING_TYPE_ANNOTATION)) 
                        {
                            CompilationUnitTree newCompileUnitTree = 
                                make.removeCompUnitImport(compileUnitTree, imp);
                            workingCopy.rewrite(compileUnitTree, newCompileUnitTree);
                            break;
                        }
                    }
                }
            }
        }

        @Override
        public void cancel() {
        }
    };
    if (SwingUtilities.isEventDispatchThread()) {
        modifySoap12Binding(javaSource, modificationTask, implClassFo, 
                isIncomplete[0]);
    } else {
        doModifySoap12Binding(javaSource, modificationTask, implClassFo, 
                isIncomplete[0]);
    }
}
 
Example 16
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Void visitCompilationUnit(CompilationUnitTree node, Void unused) {
    boolean first = true;
    if (node.getPackageName() != null) {
        markForPartialFormat();
        visitPackage(node.getPackageName(), node.getPackageAnnotations());
        builder.forcedBreak();
        first = false;
    }
    if (!node.getImports().isEmpty()) {
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.YES);
        }
        for (ImportTree importDeclaration : node.getImports()) {
            markForPartialFormat();
            builder.blankLineWanted(PRESERVE);
            scan(importDeclaration, null);
            builder.forcedBreak();
        }
        first = false;
    }
    dropEmptyDeclarations();
    for (Tree type : node.getTypeDecls()) {
        if (type.getKind() == Tree.Kind.IMPORT) {
            // javac treats extra semicolons in the import list as type declarations
            // TODO(cushon): remove this if https://bugs.openjdk.java.net/browse/JDK-8027682 is fixed
            continue;
        }
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.YES);
        }
        markForPartialFormat();
        scan(type, null);
        builder.forcedBreak();
        first = false;
        dropEmptyDeclarations();
    }
    // set a partial format marker at EOF to make sure we can format the entire file
    markForPartialFormat();
    return null;
}
 
Example 17
Source File: ImportFormatTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testSort() throws IOException, FileStateInvalidException {
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            List<ImportTree> imports = new ArrayList<ImportTree>(cut.getImports());
            ImportTree oneImport = imports.remove(4);
            imports.add(4, make.Import(make.Identifier("java.util.Collection"), false));
            Collections.sort(imports, new Comparator() {
                public int compare(Object o1, Object o2) {
                    if (o1 == o2) {
                        return 0;
                    }
                    ImportTree i1 = (ImportTree) o1;
                    ImportTree i2 = (ImportTree) o2;

                    return i1.toString().compareTo(i2.toString());
                }

                @Override
                public boolean equals(Object obj) {
                    return this == obj ? true : false;
                }

                @Override
                public int hashCode() {
                    int hash = 7;
                    return hash;
                }
            });
            CompilationUnitTree unit = make.CompilationUnit(
                    cut.getPackageName(),
                    imports,
                    cut.getTypeDecls(),
                    cut.getSourceFile()
            );
            workingCopy.rewrite(cut, unit);
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertFiles("testSort_ImportFormatTest.pass");
}
 
Example 18
Source File: JavaElementFoldVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("fallthrough")
public Object visitCompilationUnit(CompilationUnitTree node, Object p) {
    int importsStart = Integer.MAX_VALUE;
    int importsEnd   = -1;

    TokenHierarchy<?> th = info.getTokenHierarchy();
    TokenSequence<JavaTokenId>  ts = th.tokenSequence(JavaTokenId.language());
    
    IMP: for (ImportTree imp : node.getImports()) {
        // eliminate invalid imports; erroenous imports at the start/end of import block
        // will not be folder.
        Tree qualIdent = imp.getQualifiedIdentifier();
        if (qualIdent == null) {
            continue;
        }
        while (qualIdent.getKind() == Tree.Kind.MEMBER_SELECT) {
            MemberSelectTree mst = (MemberSelectTree)qualIdent;
            if (mst.getIdentifier().contentEquals("<error>")) { // NOI18N
                // ignore erroneous imports
                continue IMP;
            }
            qualIdent = mst.getExpression();
        }

        // don't rely on Javac for the end position: in case of missing semicolon the import consumes all whitespace
        // including comments / javadocs up to the following declaration or text. Rather scan tokens and consume only the import
        // identifier + semi.
        int start = (int) sp.getStartPosition(cu, imp);
        int identPos = (int) sp.getStartPosition(cu, qualIdent);
        int end = identPos;
        boolean firstNewline = true;
        ts.move(identPos);
        IDENT: while (ts.moveNext()) {
            Token<JavaTokenId>  tukac = ts.token();
            switch (tukac.id()) {
                case IDENTIFIER:
                case DOT:
                case STAR:
                    firstNewline = false;
                    end = ts.offset() + tukac.length();
                    break;
                case SEMICOLON:
                    end = (int) sp.getEndPosition(cu, imp);
                    break IDENT;
                case WHITESPACE: {
                    if (firstNewline) {
                        int endl = tukac.text().toString().indexOf("\n"); // NOI18N
                        if (endl > -1) {
                            // remember the first newline after some ident/star/dot content
                            end = ts.offset() + endl; 
                            firstNewline = true;
                        }
                    }
                    // fall through
                }
                case LINE_COMMENT: case BLOCK_COMMENT: 
                    continue;
                default:
                    break IDENT;
            }
        }

        if (importsStart > start)
            importsStart = start;

        if (end > importsEnd) {
            importsEnd = end;
        }
    }

    if (importsEnd != (-1) && importsStart != (-1)) {
        if (importsStart < initialCommentStopPos) {
            initialCommentStopPos = importsStart;
        }
        importsStart += 7/*"import ".length()*/;

        if (importsStart < importsEnd) {
            addFold(creator.createImportsFold(importsStart, importsEnd), importsStart);
        }
    }
    return super.visitCompilationUnit(node, p);
}
 
Example 19
Source File: CompletenessStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider = "crawler")
public void testFile(String fileName) throws IOException {
    File file = getSourceFile(fileName);
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    boolean success = true;
    StringWriter writer = new StringWriter();
    writer.write("Testing : " + file.toString() + "\n");
    String text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file);
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Trees trees = Trees.instance(task);
    SourcePositions sp = trees.getSourcePositions();

    for (CompilationUnitTree cut : asts) {
        for (ImportTree imp : cut.getImports()) {
            success &= testStatement(writer, sp, text, cut, imp);
        }
        for (Tree decl : cut.getTypeDecls()) {
            success &= testStatement(writer, sp, text, cut, decl);
            if (decl instanceof ClassTree) {
                ClassTree ct = (ClassTree) decl;
                for (Tree mem : ct.getMembers()) {
                    if (mem instanceof MethodTree) {
                        MethodTree mt = (MethodTree) mem;
                        BlockTree bt = mt.getBody();
                        // No abstract methods or constructors
                        if (bt != null && mt.getReturnType() != null) {
                            // The modifiers synchronized, abstract, and default are not allowed on
                            // top-level declarations and are errors.
                            Set<Modifier> modifier = mt.getModifiers().getFlags();
                            if (!modifier.contains(Modifier.ABSTRACT)
                                    && !modifier.contains(Modifier.SYNCHRONIZED)
                                    && !modifier.contains(Modifier.DEFAULT)) {
                                success &= testStatement(writer, sp, text, cut, mt);
                            }
                            testBlock(writer, sp, text, cut, bt);
                        }
                    }
                }
            }
        }
    }
    fileManager.close();
    if (!success) {
        throw new AssertionError(writer.toString());
    }
}
 
Example 20
Source File: OrganizeImports.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Performs 'organize imports' in two modes. If 'addImports' is null, it optimizes imports according to coding style.
 * However if addImports is not null && not empty, it will add the elements in addImports, and reorder the set
 * of import statements, but will not remove unused imports.
 * Combination of bulk + addImports is not tested.
 * 
 * @param copy working copy to change
 * @param addImports if not null, just adds and reorders imports. If null, performs optimization
 * @param isBulkMode called from batch processing
 * @throws IllegalStateException 
 */
public static void doOrganizeImports(WorkingCopy copy, Set<Element> addImports, boolean isBulkMode) throws IllegalStateException {
    CompilationUnitTree cu = copy.getCompilationUnit();
    List<? extends ImportTree> imports = cu.getImports();
    if (imports.isEmpty()) {
        if (addImports == null) {
            return;
        }
    } else if (addImports == null) {
        // check diag code only if in the 'optimize all' mode.
        List<Diagnostic> diags = copy.getDiagnostics();
        if (!diags.isEmpty()) {
            SourcePositions sp = copy.getTrees().getSourcePositions();
            long startPos = sp.getStartPosition(cu, imports.get(0));
            long endPos = sp.getEndPosition(cu, imports.get(imports.size() - 1));
            for (Diagnostic d : diags) {
                if (startPos <= d.getPosition() && d.getPosition() <= endPos) {
                    if (ERROR_CODE.contentEquals(d.getCode()))
                        return;
                }
            }
        }
    }
    final CodeStyle cs = CodeStyle.getDefault(copy.getFileObject());
    Set<Element> starImports = new HashSet<Element>();
    Set<Element> staticStarImports = new HashSet<Element>();
    Set<Element> toImport = getUsedElements(copy, cu, starImports, staticStarImports);
    List<ImportTree> imps = new LinkedList<ImportTree>();  
    TreeMaker maker = copy.getTreeMaker();
    
    if (addImports != null) {
        // copy over all imports to be added + existing imports.
        toImport.addAll(addImports);
        imps.addAll(cu.getImports());
    } else if (!toImport.isEmpty() || isBulkMode) {
        // track import star import scopes, so only one star import/scope appears in imps - #251977
        Set<Element> starImportScopes = new HashSet<>();
        Trees trees = copy.getTrees();
        for (ImportTree importTree : cu.getImports()) {
            Tree qualIdent = importTree.getQualifiedIdentifier();
            if (qualIdent.getKind() == Tree.Kind.MEMBER_SELECT && "*".contentEquals(((MemberSelectTree)qualIdent).getIdentifier())) {
                ImportTree imp = null;
                Element importedScope = trees.getElement(TreePath.getPath(cu, ((MemberSelectTree)qualIdent).getExpression()));
                
                if (importTree.isStatic()) {
                    if (staticStarImports != null && 
                        staticStarImports.contains(importedScope) &&
                        !starImportScopes.contains(importedScope)) {
                        imp = maker.Import(qualIdent, true);
                    }
                } else {
                    if (starImports != null && 
                        starImports.contains(importedScope) &&
                        !starImportScopes.contains(importedScope)) {
                        imp = maker.Import(qualIdent, false);
                    }
                }
                if (imp != null) {
                    starImportScopes.add(importedScope);
                    imps.add(imp);
                }
            }
        }
    } else {
        return;
    }
    if (!imps.isEmpty()) {
        Collections.sort(imps, new Comparator<ImportTree>() {

            private CodeStyle.ImportGroups groups = cs.getImportGroups();

            @Override
            public int compare(ImportTree o1, ImportTree o2) {
                if (o1 == o2)
                    return 0;
                String s1 = o1.getQualifiedIdentifier().toString();
                String s2 = o2.getQualifiedIdentifier().toString();
                int bal = groups.getGroupId(s1, o1.isStatic()) - groups.getGroupId(s2, o2.isStatic());
                return bal == 0 ? s1.compareTo(s2) : bal;
            }
        });
    }
    CompilationUnitTree cut = maker.CompilationUnit(cu.getPackageAnnotations(), cu.getPackageName(), imps, cu.getTypeDecls(), cu.getSourceFile());
    ((JCCompilationUnit)cut).packge = ((JCCompilationUnit)cu).packge;
    if (starImports != null || staticStarImports != null) {
        ((JCCompilationUnit)cut).starImportScope = ((JCCompilationUnit)cu).starImportScope;
    }
    CompilationUnitTree ncu = toImport.isEmpty() ? cut : GeneratorUtilities.get(copy).addImports(cut, toImport);
    copy.rewrite(cu, ncu);
}