下面列出了com.sun.source.tree.ImportTree#getQualifiedIdentifier ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
@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);
}
@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;
}
@SuppressWarnings("TreeToString")
@Override
public Description matchImport(ImportTree importTree, VisitorState visitorState) {
if (importTree.isStatic()) {
Tree importIdentifier = importTree.getQualifiedIdentifier();
if (importIdentifier.getKind().equals(Kind.MEMBER_SELECT)) {
MemberSelectTree memberSelectTree = (MemberSelectTree) importIdentifier;
if (memberSelectTree.getIdentifier().toString().endsWith(xpFlagName)
|| (treatmentGroupsEnum != null
&& memberSelectTree.getExpression().toString().startsWith(treatmentGroupsEnum))) {
return buildDescription(importTree)
.addFix(SuggestedFix.replace(importTree, "", 0, 1))
.build();
} else if (treatmentGroup.length() > 0 && treatmentGroupsEnum == null) {
// Check if this import is for values in the same enum that includes the treatmentGroup
Symbol importSymbol = ASTHelpers.getSymbol(memberSelectTree.getExpression());
if (importSymbol.getKind().equals(ElementKind.ENUM)
&& isTreatmentGroupEnum((Symbol.ClassSymbol) importSymbol)) {
treatmentGroupsEnum = ((Symbol.ClassSymbol) importSymbol).fullname.toString();
return buildDescription(importTree)
.addFix(SuggestedFix.replace(importTree, "", 0, 1))
.build();
}
}
}
}
return Description.NO_MATCH;
}
private boolean isStar(ImportTree tree) {
Tree qualIdent = tree.getQualifiedIdentifier();
if (qualIdent == null || qualIdent.getKind() == Kind.IDENTIFIER) {
return false;
}
return ((MemberSelectTree) qualIdent).getIdentifier().contentEquals("*");
}
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;
}
@Hint(displayName = "#DN_Imports_STAR", description = "#DESC_Imports_STAR", category="imports", id="Imports_STAR", enabled=false, options=Options.QUERY, suppressWarnings={"", "OnDemandImport"})
@TriggerTreeKind(Kind.IMPORT)
public static ErrorDescription starImport(HintContext ctx) {
ImportTree it = (ImportTree) ctx.getPath().getLeaf();
if (it.isStatic() || !(it.getQualifiedIdentifier() instanceof MemberSelectTree)) {
return null; // XXX
}
MemberSelectTree ms = (MemberSelectTree) it.getQualifiedIdentifier();
if (!"*".equals(ms.getIdentifier().toString())) return null;
return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), NbBundle.getMessage(Imports.class, "DN_Imports_STAR"));
}
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;
}
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 typeMirrorCollectionOrNull(info, "java.lang.Object");
}
return null;
}
private static void handleImport(Trees trees, ImportsTracker imports, TreePath importTreePath) {
ImportTree importTree = (ImportTree) importTreePath.getLeaf();
MemberSelectTree importedExpression = (MemberSelectTree) importTree.getQualifiedIdentifier();
TreePath importedExpressionPath = new TreePath(importTreePath, importedExpression);
Name simpleName = importedExpression.getIdentifier();
boolean isStarImport = simpleName.contentEquals("*");
if (!isStarImport && !importTree.isStatic()) {
TypeElement importedType = (TypeElement) trees.getElement(importedExpressionPath);
imports.importType(importedType, importedExpressionPath);
} else {
ExpressionTree containingElementExpression = importedExpression.getExpression();
TreePath containingElementExpressionPath =
new TreePath(importedExpressionPath, containingElementExpression);
QualifiedNameable containingElement =
(QualifiedNameable) trees.getElement(containingElementExpressionPath);
if (importTree.isStatic()) {
TypeElement containingType = (TypeElement) containingElement;
if (isStarImport) {
imports.importStaticMembers((TypeElement) containingElement);
} else {
imports.importStatic(containingType, simpleName);
}
} else {
// Normal star import
imports.importMembers(containingElement, containingElementExpressionPath);
}
}
}
private boolean isStarImport(ImportTree imp) {
Tree qualIdent = imp.getQualifiedIdentifier();
boolean isStar = qualIdent.getKind() == Tree.Kind.MEMBER_SELECT && ((MemberSelectTree)qualIdent).getIdentifier().contentEquals("*"); // NOI18N
return isStar;
}
public void testRenameIdentifier() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"import java.util.List;\n" +
"import java.util.ArrayList;\n" +
"\n" +
"import java.util.Collections; // test\n" +
"/** test */\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" }\n" +
"}\n");
String golden =
"import java.util.List;\n" +
"import java.util.ArrayList;\n" +
"\n" +
"import java.util.Jitko; // test\n" +
"/** test */\n" +
"public class Test {\n" +
" public void taragui() {\n" +
" }\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();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ImportTree dovoz = cut.getImports().get(2);
MemberSelectTree mst = (MemberSelectTree) dovoz.getQualifiedIdentifier();
workingCopy.rewrite(mst, make.setLabel(mst, "Jitko"));
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
@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);
}
@Override
public Void visitImport(ImportTree tree, Void d) {
if (parseErrorInImport(tree)) {
return super.visitImport(tree, null);
}
if (tree.getQualifiedIdentifier() == null ||
tree.getQualifiedIdentifier().getKind() != Tree.Kind.MEMBER_SELECT) {
return super.visitImport(tree, null);
}
MemberSelectTree qualIdent = (MemberSelectTree) tree.getQualifiedIdentifier();
boolean assign = false;
// static imports and star imports only use the qualifier part
boolean star = isStar(tree);
TreePath tp = tree.isStatic() || star ?
new TreePath(new TreePath(getCurrentPath(), qualIdent), qualIdent.getExpression()) :
new TreePath(getCurrentPath(), tree.getQualifiedIdentifier());
Element decl = info.getTrees().getElement(tp);
import2Highlight.put(tree, getCurrentPath());
if (decl != null && !isErroneous(decl)) {
if (!tree.isStatic()) {
if (star) {
List<TypeElement> types = ElementFilter.typesIn(decl.getEnclosedElements());
for (TypeElement te : types) {
assign = true;
if (!element2Import.containsKey(te)) {
element2Import.put(te, tree);
}
}
} else {
element2Import.put(decl, tree);
importedBySingleImport.add(decl);
}
} else if (decl.getKind().isClass() || decl.getKind().isInterface()) {
Name simpleName = star ? null : qualIdent.getIdentifier();
for (Element e : info.getElements().getAllMembers((TypeElement) decl)) {
if (!e.getModifiers().contains(Modifier.STATIC)) continue;
if (simpleName != null && !e.getSimpleName().equals(simpleName)) {
continue;
}
if (!star || !element2Import.containsKey(e)) {
element2Import.put(e, tree);
}
assign = true;
}
}
}
if (!assign) {
if (!tree.isStatic() && star) {
unresolvablePackageImports.add(tree);
} else {
addUnresolvableImport(qualIdent.getIdentifier(), tree);
}
}
super.visitImport(tree, null);
return null;
}
/**
* 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);
}
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]);
}
}
private static void analyzeImports(CompilationUnitTree cut, Source src, EndPosTable endPosTable) {
CachedASMReflector cachedASMReflector = CachedASMReflector.getInstance();
long firstLine = 0;
for (ImportTree imp : cut.getImports()) {
JCTree.JCImport jcImport = (JCTree.JCImport) imp;
int startPos = jcImport.getPreferredPosition();
int endPos = jcImport.getEndPosition(endPosTable);
Range range = Range.create(src, startPos + 1, endPos);
firstLine = range.begin.line;
String importClass = imp.getQualifiedIdentifier().toString();
String simpleName = ClassNameUtils.getSimpleName(importClass);
if (imp.isStatic()) {
// TODO static asterisk
Tree tree = imp.getQualifiedIdentifier();
if (tree instanceof JCTree.JCFieldAccess) {
JCTree.JCFieldAccess fieldAccess = (JCTree.JCFieldAccess) tree;
com.sun.tools.javac.util.Name name = fieldAccess.getIdentifier();
JCTree.JCExpression expression = fieldAccess.getExpression();
String methodName = name.toString();
String decClazz = expression.toString();
src.addStaticImport(methodName, decClazz);
} else {
log.warn("Not impl");
}
} else {
if (simpleName.equals("*")) {
// wild
for (String s : cachedASMReflector.getPackageClasses(importClass).values()) {
src.addImport(s);
}
} else {
src.addImport(importClass);
}
}
}
src.setClassStartLine(firstLine);
}