Java 类com.sun.source.tree.ImportTree 实例源码

项目:incubator-netbeans    文件:JpaControllerUtil.java   
public static CompilationUnitTree createImport(WorkingCopy wc, CompilationUnitTree modifiedCut, String fq) {
    if (modifiedCut == null) {
        modifiedCut = wc.getCompilationUnit();  //use committed cut as modifiedCut
    }
    List<? extends ImportTree> imports = modifiedCut.getImports();
    boolean found = false;
    for (ImportTree imp : imports) {
       if (fq.equals(imp.getQualifiedIdentifier().toString())) {
           found = true; 
           break;
       }
    }
    if (!found) {
        TreeMaker make = wc.getTreeMaker();
        CompilationUnitTree newCut = make.addCompUnitImport(
            modifiedCut, 
            make.Import(make.Identifier(fq), false)
        );                                              //create a newCut from modifiedCut
        wc.rewrite(wc.getCompilationUnit(), newCut);    //replace committed cut with newCut in change map
        return newCut;                                  //return the newCut we just created
    }
    return modifiedCut; //no newCut created from modifiedCut, so just return modifiedCut
}
项目:incubator-netbeans    文件:ImportFormatTest.java   
public void testAddFirstImport() throws IOException, FileStateInvalidException {
    System.err.println("testAddFirstImport");
    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());
            imports.add(0, make.Import(make.Identifier("java.util.AbstractList"), 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("testAddFirstImport_ImportFormatTest.pass");
}
项目:incubator-netbeans    文件:ImportFormatTest.java   
public void testAddLastImport() 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());
            imports.add(make.Import(make.Identifier("java.io.IOException"), 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("testAddLastImport_ImportFormatTest.pass");
}
项目:incubator-netbeans    文件:ImportFormatTest.java   
public void testRemoveInnerImport() 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());
            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("testRemoveInnerImport_ImportFormatTest.pass");
}
项目:incubator-netbeans    文件:ImportFormatTest.java   
public void testRemoveFirstImport() 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());
            imports.remove(0);
            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("testRemoveFirstImport_ImportFormatTest.pass");
}
项目:incubator-netbeans    文件:ImportFormatTest.java   
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");
}
项目:incubator-netbeans    文件:ImportFormatTest.java   
public void testRemoveInside() 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());
            imports.remove(4);
            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("testRemoveInside_ImportFormatTest.pass");
}
项目:incubator-netbeans    文件:ImportFormatTest.java   
public void testMoveFirst() 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(0);
            imports.add(3, oneImport);
            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("testMoveFirst_ImportFormatTest.pass");
}
项目:incubator-netbeans    文件:ImportFormatTest.java   
public void testMoveLast() 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(7);
            imports.add(1, oneImport);
            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("testMoveLast_ImportFormatTest.pass");
}
项目:incubator-netbeans    文件:ImportFormatTest.java   
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");
}
项目:incubator-netbeans    文件:FindLocalUsagesQuery.java   
@Override
public Void visitImport(ImportTree node, Stack<Tree> p) {
    if (node.isStatic() && toFind.getModifiers().contains(Modifier.STATIC)) {
        Tree qualIdent = node.getQualifiedIdentifier();
        if (qualIdent.getKind() == Kind.MEMBER_SELECT) {
            MemberSelectTree mst = (MemberSelectTree) qualIdent;
            if (toFind.getSimpleName().contentEquals(mst.getIdentifier())) {
                Element el = info.getTrees().getElement(new TreePath(getCurrentPath(), mst.getExpression()));
                if (el != null && el.equals(toFind.getEnclosingElement())) {
                    Token<JavaTokenId> t = Utilities.getToken(info, doc, new TreePath(getCurrentPath(), mst));
                    if (t != null)
                        usages.add(t);
                }
            }
        }
    }
    return super.visitImport(node, p);
}
项目:incubator-netbeans    文件:UnusedImports.java   
private void typeUsed(Element decl, TreePath expr, boolean methodInvocation) {
    if (decl != null && (expr == null || expr.getLeaf().getKind() == Kind.IDENTIFIER || expr.getLeaf().getKind() == Kind.PARAMETERIZED_TYPE)) {
        if (!isErroneous(decl)) {
            ImportTree imp = element2Import.get(decl);

            if (imp != null) {
                addUsage(imp);
                if (isStar(imp)) {
                    //TODO: explain
                    handleUnresolvableImports(decl, methodInvocation, false);
                }
            }
        } else {
            handleUnresolvableImports(decl, methodInvocation, true);

            for (Entry<Element, ImportTree> e : element2Import.entrySet()) {
                if (importedBySingleImport.contains(e.getKey())) continue;

                if (e.getKey().getSimpleName().equals(decl.getSimpleName())) {
                    import2Highlight.remove(e.getValue());
                }
            }
        }
    }
}
项目:incubator-netbeans    文件:UnusedImports.java   
private void handleUnresolvableImports(Element decl,
        boolean methodInvocation, boolean removeStarImports) {
    Name simpleName = decl.getSimpleName();
    if (simpleName != null) {
        Collection<ImportTree> imps = simpleName2UnresolvableImports.get(simpleName.toString());

        if (imps != null) {
            for (ImportTree imp : imps) {
                if (!methodInvocation || imp.isStatic()) {
                    import2Highlight.remove(imp);
                }
            }
        } else {
            if (removeStarImports) {
                //TODO: explain
                for (ImportTree unresolvable : unresolvablePackageImports) {
                    if (!methodInvocation || unresolvable.isStatic()) {
                        import2Highlight.remove(unresolvable);
                    }
                }
            }
        }
    }
}
项目:incubator-netbeans    文件:FindLocalUsagesQuery.java   
@Override
public Void visitImport(ImportTree node, Void p) {
    if (node.isStatic() && toFind.getModifiers().contains(Modifier.STATIC)) {
        Tree qualIdent = node.getQualifiedIdentifier();
        if (qualIdent.getKind() == Kind.MEMBER_SELECT) {
            MemberSelectTree mst = (MemberSelectTree) qualIdent;
            if (toFind.getSimpleName().contentEquals(mst.getIdentifier())) {
                Element el = info.getTrees().getElement(new TreePath(getCurrentPath(), mst.getExpression()));
                if (el != null && el.equals(toFind.getEnclosingElement())) {
                    try {
                        int[] span = treeUtils.findNameSpan(mst);
                        if(span != null) {
                            MutablePositionRegion region = createRegion(doc, span[0], span[1]);
                            usages.add(region);
                        }
                    } catch (BadLocationException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }
            }
        }
    }
    return super.visitImport(node, p);
}
项目:incubator-netbeans    文件:Imports.java   
@Hint(displayName = "#DN_Imports_EXCLUDED", description = "#DESC_Imports_EXCLUDED", category="imports", id="Imports_EXCLUDED", options=Options.QUERY)
@TriggerTreeKind(Kind.IMPORT)
public static ErrorDescription exlucded(HintContext ctx) throws IOException {
    ImportTree it = (ImportTree) ctx.getPath().getLeaf();

    if (it.isStatic() || !(it.getQualifiedIdentifier() instanceof MemberSelectTree)) {
        return null; // XXX
    }

    MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();
    String pkg = ms.getExpression().toString();
    String klass = ms.getIdentifier().toString();
    String exp = pkg + "." + (!klass.equals("*") ? klass : ""); //NOI18N
    if (Utilities.isExcluded(exp)) {
        return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), NbBundle.getMessage(Imports.class, "DN_Imports_EXCLUDED"));
    }

    return null;
}
项目:incubator-netbeans    文件:Imports.java   
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy copy = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    CompilationUnitTree cut = copy.getCompilationUnit();

    TreeMaker make = copy.getTreeMaker();

    CompilationUnitTree newCut = cut;
    for (TreePathHandle tph : tphList) {
        TreePath path = tph.resolve(copy);
        if ( path != null && path.getLeaf() instanceof ImportTree) {
             newCut = make.removeCompUnitImport(newCut, (ImportTree)path.getLeaf());
        }
    }
    copy.rewrite(cut, newCut);

}
项目:incubator-netbeans    文件:ImportClass.java   
public FixImport(FileObject file, String fqn, ElementHandle<Element> toImport, String sortText, boolean isValid, CompilationInfo info, @NullAllowed TreePath replacePath, @NullAllowed String replaceSuffix, 
        boolean doOrganize) {
    super(file, fqn, toImport, sortText, isValid);
    if (replacePath != null) {
        this.replacePathHandle = TreePathHandle.create(replacePath, info);
        this.suffix = replaceSuffix;
        while (replacePath != null && replacePath.getLeaf().getKind() != Kind.IMPORT) {
            replacePath = replacePath.getParentPath();
        }
        this.statik = replacePath != null ? ((ImportTree) replacePath.getLeaf()).isStatic() : false;
    } else {
        this.replacePathHandle = null;
        this.suffix = null;
        this.statik = false;
    }
    this.doOrganize = doOrganize;
}
项目:openjdk-jdk10    文件:T6963934.java   
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();
    try (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);
    }
}
项目:openjdk9    文件:T6963934.java   
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();
    try (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);
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:T6963934.java   
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);
}
项目:source-code-metrics    文件:ImportsVisitor.java   
@Override
public Set<String> visitImport(ImportTree node, AbstractMap.Entry<ProjectImpl, PackageImpl> p) {

    ProjectImpl projectImpl = p.getKey();
    PackageImpl packageImpl = p.getValue();

    if (node != null) {
        String importIndentifier = node.getQualifiedIdentifier().toString();

        // check if this import identifier belongs to any of the packages
        String pkgStr = MethodUtil.belongsToPackages(importIndentifier, projectImpl.getPackagesMap().keySet()); 
        if (pkgStr != null) {
            PackageImpl pi = projectImpl.getPackagesMap().get(pkgStr); // retrieval of the package

            // adding input and output dependencies
            packageImpl.getOutputDependencies().add(pi);
            pi.getInputDependencies().add(packageImpl);

            HashSet<String> set = new HashSet<String>();
            set.add(importIndentifier);
            return set;
        }
    }
    return null;
}
项目:jsr308-langtools    文件:T6963934.java   
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);
}
项目:adalid    文件:MetaJavaCompiler.java   
private static void scanParsedTrees(Iterable<? extends CompilationUnitTree> units) {
        logger.info("units");
        for (CompilationUnitTree unit : units) {
            logger.info("unit" + CL + unit.getKind() + SP + unit.getSourceFile().getName()); // + NL + unit
            List<? extends Tree> typeDecls = unit.getTypeDecls();
            logger.info("type declarations" + CL + StringUtils.join(typeDecls, CM));
            logger.info("package" + CL + unit.getPackageName());
            List<? extends AnnotationTree> annotationsTrees = unit.getPackageAnnotations();
            logger.info("package annotations" + CL + StringUtils.join(annotationsTrees, CM));
            List<? extends ImportTree> importTrees = unit.getImports();
            logger.info("imports" + CL + LF + StringUtils.join(importTrees, ""));
//          LineMap lineMap = unit.getLineMap();
//          logger.info("line map" + CL + lineMap);
            logger.info("");
        }
    }
项目:annotation-tools    文件:IsSigMethodCriterion.java   
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<String>();
  for (ImportTree i : topLevel.getImports()) {
    String imported = i.getQualifiedIdentifier().toString();
    imports.add(imported);
  }

  result = new Context(packageName, imports);
  contextCache.put(topLevel, result);
  return result;
}
项目:infobip-open-jdk-8    文件:T6963934.java   
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);
}
项目:error-prone    文件:StaticImports.java   
/**
 * Returns a {@link StaticImports} if the given import is a static single-type import. Returns
 * {@code null} otherwise, e.g. because the import is non-static, or an on-demand import, or
 * statically imports a field or method.
 */
@Nullable
public static StaticImportInfo tryCreate(ImportTree tree, VisitorState state) {
  if (!tree.isStatic()) {
    return null;
  }
  if (!(tree.getQualifiedIdentifier() instanceof JCTree.JCFieldAccess)) {
    return null;
  }
  JCTree.JCFieldAccess access = (JCTree.JCFieldAccess) tree.getQualifiedIdentifier();
  String importedName = access.toString();
  Type result = state.getTypeFromString(importedName);
  if (result == null) {
    // If the full imported name isn't a type, it might be a field or
    // method:
    return tryAsStaticMember(access, state);
  }
  String canonicalName = state.getTypes().erasure(result).toString();
  if (canonicalName == null) {
    return null;
  }
  return StaticImportInfo.create(importedName, canonicalName);
}
项目:error-prone    文件:WildcardImport.java   
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
  ImmutableList<ImportTree> wildcardImports = getWildcardImports(tree.getImports());
  if (wildcardImports.isEmpty()) {
    return NO_MATCH;
  }

  // Find all of the types that need to be imported.
  Set<TypeToImport> typesToImport = ImportCollector.collect((JCCompilationUnit) tree);

  Fix fix = createFix(wildcardImports, typesToImport, state);
  if (fix.isEmpty()) {
    return NO_MATCH;
  }
  return describeMatch(wildcardImports.get(0), fix);
}
项目:error-prone    文件:WildcardImport.java   
/** Collect all on demand imports. */
private static ImmutableList<ImportTree> getWildcardImports(List<? extends ImportTree> imports) {
  ImmutableList.Builder<ImportTree> result = ImmutableList.builder();
  for (ImportTree tree : imports) {
    // javac represents on-demand imports as a member select where the selected name is '*'.
    Tree ident = tree.getQualifiedIdentifier();
    if (!(ident instanceof MemberSelectTree)) {
      continue;
    }
    MemberSelectTree select = (MemberSelectTree) ident;
    if (select.getIdentifier().contentEquals("*")) {
      result.add(tree);
    }
  }
  return result.build();
}
项目:openjdk-source-code-learn    文件:T6963934.java   
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);
}
项目:OLD-OpenJDK8    文件:T6963934.java   
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);
}
项目:s4j    文件:T6963934.java   
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);
}
项目:jdk7-langtools    文件:T6963934.java   
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);
}
项目:groundhog    文件:CodeAnalyzerProcessor.java   
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) {
    CodeAnalyzerTreeVisitor visitor = new CodeAnalyzerTreeVisitor(counters);

    for (Element e : roundEnvironment.getRootElements()) {
        TreePath tp = trees.getPath(e);

        if (tp != null) {
            CompilationUnitTree compUnitTree = tp.getCompilationUnit();
            int lines = countAllLines(compUnitTree.toString()); // count lines
            setCounterValue("line count", compUnitTree.getSourceFile().getName(), lines);
            for (ImportTree it : compUnitTree.getImports()) { // count imports
                visitor.count("import", it.getQualifiedIdentifier().toString());
            }
            visitor.scan(tp, trees); // count everything else
        }
    }
    return true;
}
项目:openjdk-icedtea7    文件:T6963934.java   
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);
}
项目:xapi    文件:JavacServiceImpl.java   
@Override
public String getQualifiedName(CompilationUnitTree cup, Tree tree) {
  if (tree instanceof CompilationUnitTree) {
    return getQualifiedName((CompilationUnitTree)tree);
  } else if (tree instanceof ImportTree) {
    ImportTree importTree = (ImportTree) tree;
    return getQualifiedName(cup, importTree.getQualifiedIdentifier());
  } else if (tree instanceof ClassTree) {
    return getQualifiedName(cup, (ClassTree)tree);
  } else if (tree instanceof ExpressionTree){
    final TypeMirror type = findType((ExpressionTree) tree);
    return type.toString();
  } else {
    X_Log.error(getClass(), "Unhandled tree subclass ", tree.getKind(), " with class ", tree.getClass());
    throw new UnsupportedOperationException("Not able to determine qualified name of " + tree);
  }
}
项目:INF5000-StaticProxy    文件:T6963934.java   
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);
}
项目:netbeans-plugin    文件:AbstractJavaFix.java   
protected void addImport( String ifaceFqn,
        ElementHandle<TypeElement> handle, WorkingCopy copy,
        TreeMaker treeMaker )
{
    // Don't add import if the interface is in the same package
    TypeElement sourceElement = handle.resolve(copy);
    PackageElement pkg = copy.getElements().getPackageOf(sourceElement);
    String pkgName = pkg.getQualifiedName().toString();
    if (ifaceFqn.startsWith(pkgName)) {
        String suffix = ifaceFqn.substring(pkgName.length());
        int index = suffix.indexOf('.');
        if (index == 0 && 0 == suffix.lastIndexOf('.')) {
            return;
        }
    }

    ImportTree imprt =
            treeMaker.Import(treeMaker.QualIdent(ifaceFqn), false);

    CompilationUnitTree unitTree = copy.getCompilationUnit();
    CompilationUnitTree withImport =
            treeMaker.addCompUnitImport(copy.getCompilationUnit(), imprt);

    copy.rewrite(unitTree, withImport);
}
项目:compile-testing    文件:TreeDiffer.java   
@Override
public Void visitImport(ImportTree expected, Tree actual) {
  Optional<ImportTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  checkForDiff(expected.isStatic() == other.get().isStatic(),
      "Expected import to be <%s> but was <%s>.",
      expected.isStatic() ? "static" : "non-static",
      other.get().isStatic() ? "static" : "non-static");

  scan(expected.getQualifiedIdentifier(), other.get().getQualifiedIdentifier());
  return null;
}
项目:incubator-netbeans    文件:TreeDuplicator.java   
@Override
public Tree visitImport(ImportTree tree, Void p) {
    ImportTree n = make.Import(tree.getQualifiedIdentifier(), tree.isStatic());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
项目:incubator-netbeans    文件:ImportAnalysis2Test.java   
public void testStringQualIdentNewlyCreatedSamePackage() throws Exception {
    clearWorkDir();
    testFile = new File(getWorkDir(), "hierbas/del/litoral/Test.java");
    assertTrue(testFile.getParentFile().mkdirs());
    TestUtilities.copyStringToFile(testFile,
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "\n" +
        "    A l;\n" +
        "}\n";

    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();
            ClassTree nueClass = make.Class(make.Modifiers(EnumSet.noneOf(Modifier.class)), "A", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList());
            CompilationUnitTree nueCUT = make.CompilationUnit(FileUtil.toFileObject(getWorkDir()), "hierbas/del/litoral/A.java", Collections.<ImportTree>emptyList(), Collections.singletonList(nueClass));
            workingCopy.rewrite(null, nueCUT);
            CompilationUnitTree node = workingCopy.getCompilationUnit();
            ClassTree clazz = (ClassTree) node.getTypeDecls().get(0);
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "l", make.QualIdent("hierbas.del.litoral.A"), null);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, vt));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}