com.sun.source.tree.ImportTree Java Examples
The following examples show how to use
com.sun.source.tree.ImportTree.
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: TreeDiffer.java From compile-testing with Apache License 2.0 | 6 votes |
@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; }
Example #2
Source File: T6963934.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
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: JpaControllerUtil.java From netbeans with Apache License 2.0 | 6 votes |
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 }
Example #4
Source File: UnusedImports.java From netbeans with Apache License 2.0 | 6 votes |
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); } } } } } }
Example #5
Source File: ImportClass.java From netbeans with Apache License 2.0 | 6 votes |
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; }
Example #6
Source File: FindLocalUsagesQuery.java From netbeans with Apache License 2.0 | 6 votes |
@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); }
Example #7
Source File: UnusedImports.java From netbeans with Apache License 2.0 | 6 votes |
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()); } } } } }
Example #8
Source File: T6963934.java From hottub with GNU General Public License v2.0 | 6 votes |
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 #9
Source File: T6963934.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
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 #10
Source File: Imports.java From netbeans with Apache License 2.0 | 6 votes |
@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); }
Example #11
Source File: IsSigMethodCriterion.java From annotation-tools with MIT License | 6 votes |
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 #12
Source File: ImportFormatTest.java From netbeans with Apache License 2.0 | 6 votes |
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"); }
Example #13
Source File: ImportFormatTest.java From netbeans with Apache License 2.0 | 6 votes |
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"); }
Example #14
Source File: ImportFormatTest.java From netbeans with Apache License 2.0 | 6 votes |
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"); }
Example #15
Source File: T6963934.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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 #16
Source File: Imports.java From netbeans with Apache License 2.0 | 6 votes |
@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; }
Example #17
Source File: TreePruner.java From bazel with Apache License 2.0 | 6 votes |
private static void removeUnusedImports(JCCompilationUnit unit) { Set<String> usedNames = new HashSet<>(); // TODO(cushon): consider folding this into PruningVisitor to avoid a second pass new TreePathScanner<Void, Void>() { @Override public Void visitImport(ImportTree importTree, Void usedSymbols) { return null; } @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { if (tree == null) { return null; } usedNames.add(tree.getName().toString()); return null; } }.scan(unit, null); com.sun.tools.javac.util.List<JCTree> replacements = com.sun.tools.javac.util.List.nil(); for (JCTree def : unit.defs) { if (!def.hasTag(JCTree.Tag.IMPORT) || !isUnused(unit, usedNames, (JCImport) def)) { replacements = replacements.append(def); } } unit.defs = replacements; }
Example #18
Source File: T6963934.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
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 #19
Source File: FindLocalUsagesQuery.java From netbeans with Apache License 2.0 | 6 votes |
@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); }
Example #20
Source File: RemoveUnusedImportFix.java From netbeans with Apache License 2.0 | 5 votes |
public ChangeInfo implement() { JavaSource js = JavaSource.forFileObject(file); if (js == null) { StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(JavaFixAllImports.class, "MSG_CannotFixImports")); //NOI18N } else { try { js.runModificationTask(new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws Exception { copy.toPhase(Phase.PARSED); CompilationUnitTree nueCUT = copy.getCompilationUnit(); for (TreePathHandle handle : importsToRemove) { TreePath tp = handle.resolve(copy); if (tp == null) { //cannot resolve Logger.getLogger(RemoveUnusedImportFix.class.getName()).info("Cannot resolve import to remove."); //NOI18N return ; } nueCUT = copy.getTreeMaker().removeCompUnitImport(nueCUT, (ImportTree) tp.getLeaf()); } copy.rewrite(copy.getCompilationUnit(), nueCUT); } }).commit(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } return null; }
Example #21
Source File: JaxWsCodeGenerator.java From netbeans with Apache License 2.0 | 5 votes |
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 #22
Source File: GeneratorUtilitiesTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testAddImports12() throws Exception { performTest("package test;\nimport Bar;\nimport org.me.Foo;\npublic class Test { }\n", "1.5", new AddImportsTask("java.util.List"), new Validator() { public void validate(CompilationInfo info) { assertEquals(2, info.getDiagnostics().size()); List<? extends ImportTree> imports = info.getCompilationUnit().getImports(); assertEquals(3, imports.size()); assertEquals("Bar.<error>", imports.get(0).getQualifiedIdentifier().toString()); assertEquals("java.util.List", imports.get(1).getQualifiedIdentifier().toString()); assertEquals("org.me.Foo", imports.get(2).getQualifiedIdentifier().toString()); } }, false); }
Example #23
Source File: GeneratorUtilitiesTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testAddImports6() throws Exception { Preferences preferences = MimeLookup.getLookup(JavaTokenId.language().mimeType()).lookup(Preferences.class); preferences.putBoolean("allowConvertToStarImport", true); performTest("package test;\nimport java.util.AbstractList;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Vector;\npublic class Test { }\n", "1.5", new AddImportsTask("java.util.Collection"), new Validator() { public void validate(CompilationInfo info) { assertEquals(0, info.getDiagnostics().size()); List<? extends ImportTree> imports = info.getCompilationUnit().getImports(); assertEquals(1, imports.size()); assertEquals("java.util.*", imports.get(0).getQualifiedIdentifier().toString()); } }, false); preferences.putBoolean("allowConvertToStarImport", false); }
Example #24
Source File: GeneratorUtilitiesTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testAddImports5() throws Exception { Preferences preferences = MimeLookup.getLookup(JavaTokenId.language().mimeType()).lookup(Preferences.class); preferences.putBoolean("allowConvertToStarImport", true); performTest("package test;\nimport java.util.AbstractList;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Vector;\npublic class Test { }\n", "1.5", new AddImportsTask("java.util.Collection"), new Validator() { public void validate(CompilationInfo info) { assertEquals(0, info.getDiagnostics().size()); List<? extends ImportTree> imports = info.getCompilationUnit().getImports(); assertEquals(1, imports.size()); assertEquals("java.util.*", imports.get(0).getQualifiedIdentifier().toString()); } }, false); preferences.putBoolean("allowConvertToStarImport", false); }
Example #25
Source File: GeneratorUtilitiesTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testAddImports3() throws Exception { performTest("package test;\nimport java.util.List;\nimport javax.swing.*;\npublic class Test { }\n", "1.5", new AddImportsTask("java.util.ArrayList", "javax.swing.JTable"), new Validator() { public void validate(CompilationInfo info) { assertEquals(0, info.getDiagnostics().size()); List<? extends ImportTree> imports = info.getCompilationUnit().getImports(); assertEquals(3, imports.size()); assertEquals("java.util.ArrayList", imports.get(0).getQualifiedIdentifier().toString()); assertEquals("java.util.List", imports.get(1).getQualifiedIdentifier().toString()); assertEquals("javax.swing.*", imports.get(2).getQualifiedIdentifier().toString()); } }, false); }
Example #26
Source File: UnusedImports.java From netbeans with Apache License 2.0 | 5 votes |
private void addUnresolvableImport(Name name, ImportTree imp) { String key = name.toString(); Collection<ImportTree> l = simpleName2UnresolvableImports.get(key); if (l == null) { simpleName2UnresolvableImports.put(key, l = new LinkedList<ImportTree>()); } l.add(imp); }
Example #27
Source File: GeneratorUtilitiesTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testAddImports1() throws Exception { performTest("package test;\nimport java.util.List;\nimport javax.swing.JLabel;\npublic class Test { }\n", "1.5", new AddImportsTask("javax.swing.JTable", "java.util.ArrayList"), new Validator() { public void validate(CompilationInfo info) { assertEquals(0, info.getDiagnostics().size()); List<? extends ImportTree> imports = info.getCompilationUnit().getImports(); assertEquals(4, imports.size()); assertEquals("java.util.ArrayList", imports.get(0).getQualifiedIdentifier().toString()); assertEquals("java.util.List", imports.get(1).getQualifiedIdentifier().toString()); assertEquals("javax.swing.JLabel", imports.get(2).getQualifiedIdentifier().toString()); assertEquals("javax.swing.JTable", imports.get(3).getQualifiedIdentifier().toString()); } }, false); }
Example #28
Source File: JavaInputAstVisitor.java From google-java-format with Apache License 2.0 | 5 votes |
@Override public Void visitImport(ImportTree node, Void unused) { sync(node); token("import"); builder.space(); if (node.isStatic()) { token("static"); builder.space(); } visitName(node.getQualifiedIdentifier()); token(";"); // TODO(cushon): remove this if https://bugs.openjdk.java.net/browse/JDK-8027682 is fixed dropEmptyDeclarations(); return null; }
Example #29
Source File: CreateElementUtilities.java From netbeans with Apache License 2.0 | 5 votes |
private static List<? extends TypeMirror> computeImport(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) { ImportTree tree = (ImportTree) parent.getLeaf(); if (tree.getQualifiedIdentifier() == error) { types.add(ElementKind.ANNOTATION_TYPE); types.add(ElementKind.CLASS); types.add(ElementKind.ENUM); types.add(ElementKind.INTERFACE); return Collections.singletonList(info.getElements().getTypeElement("java.lang.Object").asType()); } return null; }
Example #30
Source File: CodeGenerator.java From netbeans with Apache License 2.0 | 5 votes |
static CompilationUnitTree generateCode(WorkingCopy wc, Element te) { TreeMaker make = wc.getTreeMaker(); Tree clazz = new TreeBuilder(make, wc).visit(te); CompilationUnitTree cut = make.CompilationUnit( te.getKind() == ElementKind.MODULE ? null : make.Identifier(((PackageElement) te.getEnclosingElement()).getQualifiedName()), Collections.<ImportTree>emptyList(), Collections.singletonList(clazz), wc.getCompilationUnit().getSourceFile()); return cut; }