org.eclipse.jdt.core.dom.ImportDeclaration Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.ImportDeclaration. 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: ReferenceAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(QualifiedName node) {
	if (isMovedMember(node.resolveBinding())) {
		if (node.getParent() instanceof ImportDeclaration) {
			ITypeBinding typeBinding= node.resolveTypeBinding();
			if (typeBinding != null)
			 	fCuRewrite.getImportRewrite().removeImport(typeBinding.getQualifiedName());
			String imp= fCuRewrite.getImportRewrite().addImport(fTarget.getQualifiedName() + '.' + node.getName().getIdentifier());
			fCuRewrite.getImportRemover().registerAddedImport(imp);
		} else {
			rewrite(node, fTarget);
		}
		return false;
	} else {
		return super.visit(node);
	}
}
 
Example #2
Source File: JavaTypeHierarchyExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public boolean visit(final CompilationUnit node) {
	if (node.getPackage() != null) {
		currentPackageName = node.getPackage().getName()
				.getFullyQualifiedName();
	}
	for (final Object decl : node.imports()) {
		final ImportDeclaration imp = (ImportDeclaration) decl;
		if (!imp.isStatic()) {
			final String fqn = imp.getName().getFullyQualifiedName();
			importedNames.put(fqn.substring(fqn.lastIndexOf('.') + 1),
					fqn);
		}
	}
	return true;
}
 
Example #3
Source File: UnusedImportsNodeCollector.java    From j2cl with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void endVisit(CompilationUnit compilationUnit) {
  List<ImportDeclaration> imports = compilationUnit.imports();
  for (ImportDeclaration importDeclaration : imports) {
    if (importDeclaration.isOnDemand()) {
      // Assume .* imports are always needed.
      continue;
    }
    SimpleName importedClass =
        importDeclaration.getName().isSimpleName()
            ? (SimpleName) importDeclaration.getName()
            : ((QualifiedName) importDeclaration.getName()).getName();

    if (!referencedNames.contains(importedClass.getIdentifier())) {
      unusedImports.add(importDeclaration);
    }
  }
}
 
Example #4
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void updateImportDeclarations(ASTRewrite rewrite, CompilationUnit compilationUnit) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(compilationUnit);

    if (isUpdateImports()) {
        final AST ast = rewrite.getAST();
        SortedSet<ImportDeclaration> imports = new TreeSet<>(importComparator);
        imports.add(createImportDeclaration(ast, PrivilegedAction.class));
        if (!isStaticImport()) {
            imports.add(createImportDeclaration(ast, AccessController.class));
        } else {
            imports.add(createImportDeclaration(ast, AccessController.class, DO_PRIVILEGED_METHOD_NAME));
        }
        addImports(rewrite, compilationUnit, imports);
    }
}
 
Example #5
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 6 votes vote down vote up
protected void processCompilationUnit(String sourceFilePath, CompilationUnit compilationUnit) {
	PackageDeclaration packageDeclaration = compilationUnit.getPackage();
	String packageName = null;
	if(packageDeclaration != null)
		packageName = packageDeclaration.getName().getFullyQualifiedName();
	else
		packageName = "";
	
	List<ImportDeclaration> imports = compilationUnit.imports();
	List<String> importedTypes = new ArrayList<String>();
	for(ImportDeclaration importDeclaration : imports) {
		importedTypes.add(importDeclaration.getName().getFullyQualifiedName());
	}
	List<AbstractTypeDeclaration> topLevelTypeDeclarations = compilationUnit.types();
       for(AbstractTypeDeclaration abstractTypeDeclaration : topLevelTypeDeclarations) {
       	if(abstractTypeDeclaration instanceof TypeDeclaration) {
       		TypeDeclaration topLevelTypeDeclaration = (TypeDeclaration)abstractTypeDeclaration;
       		processTypeDeclaration(compilationUnit, topLevelTypeDeclaration, packageName, sourceFilePath, importedTypes);
       	}
       	else if(abstractTypeDeclaration instanceof EnumDeclaration) {
       		EnumDeclaration enumDeclaration = (EnumDeclaration)abstractTypeDeclaration;
       		processEnumDeclaration(compilationUnit, enumDeclaration, packageName, sourceFilePath, importedTypes);
       	}
       }
}
 
Example #6
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static StubTypeContext createStubTypeContext(ICompilationUnit cu, CompilationUnit root, int focalPosition) throws CoreException {
	StringBuffer bufBefore= new StringBuffer();
	StringBuffer bufAfter= new StringBuffer();

	int introEnd= 0;
	PackageDeclaration pack= root.getPackage();
	if (pack != null)
		introEnd= pack.getStartPosition() + pack.getLength();
	List<ImportDeclaration> imports= root.imports();
	if (imports.size() > 0) {
		ImportDeclaration lastImport= imports.get(imports.size() - 1);
		introEnd= lastImport.getStartPosition() + lastImport.getLength();
	}
	bufBefore.append(cu.getBuffer().getText(0, introEnd));

	fillWithTypeStubs(bufBefore, bufAfter, focalPosition, root.types());
	bufBefore.append(' ');
	bufAfter.insert(0, ' ');
	return new StubTypeContext(cu, bufBefore.toString(), bufAfter.toString());
}
 
Example #7
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void copyImportsToDestination(IImportContainer container, ASTRewrite rewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException {
	ListRewrite listRewrite= rewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY);

	IJavaElement[] importDeclarations= container.getChildren();
	for (int i= 0; i < importDeclarations.length; i++) {
		IImportDeclaration declaration= (IImportDeclaration) importDeclarations[i];

		ImportDeclaration sourceNode= ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode);
		ImportDeclaration copiedNode= (ImportDeclaration) ASTNode.copySubtree(rewrite.getAST(), sourceNode);

		if (getLocation() == IReorgDestination.LOCATION_BEFORE) {
			listRewrite.insertFirst(copiedNode, null);
		} else {
			listRewrite.insertLast(copiedNode, null);
		}
	}
}
 
Example #8
Source File: ASTVisitors.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean visit(final ImportDeclaration node) {
	final String qName = node.getName().getFullyQualifiedName();
	final String imprt = node.toString().trim();
	if (!node.isStatic()) {
		if (!imprt.endsWith(".*;") && qName.matches(pattern))
			fqImports.add(qName);
	} else {
		if (!imprt.endsWith(".*;") && qName.matches(pattern)) {
			final String name = qName.substring(qName.lastIndexOf('.') + 1);
			if (Character.isLowerCase(name.charAt(0)))
				fqMethodImports.add(qName);
		}
	}
	return false;
}
 
Example #9
Source File: ASTUtil.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void addImports(ListRewrite importRewrite, Comparator<? super ImportDeclaration> comparator,
        Iterator<ImportDeclaration> newImports) {
    try {
        ImportDeclaration newImport = newImports.next();
        List<?> imports = importRewrite.getRewrittenList();
        for (Object importObj : imports) {
            ImportDeclaration anImport = (ImportDeclaration) importObj;
            int comp = comparator.compare(newImport, anImport);
            if (comp > 0) {
                continue;
            }
            if (comp < 0) {
                importRewrite.insertBefore(newImport, anImport, null);
            }
            newImport = newImports.next();
        }
        importRewrite.insertLast(newImport, null);
        while (newImports.hasNext()) {
            importRewrite.insertLast(newImports.next(), null);
        }
    } catch (NoSuchElementException e) {
        // do nothing
    }
}
 
Example #10
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void copyImportsToDestination(IImportContainer container, ASTRewrite rewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException {
	ListRewrite listRewrite= rewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY);

	IJavaElement[] importDeclarations= container.getChildren();
	for (int i= 0; i < importDeclarations.length; i++) {
		IImportDeclaration declaration= (IImportDeclaration) importDeclarations[i];

		ImportDeclaration sourceNode= ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode);
		ImportDeclaration copiedNode= (ImportDeclaration) ASTNode.copySubtree(rewrite.getAST(), sourceNode);

		if (getLocation() == IReorgDestination.LOCATION_BEFORE) {
			listRewrite.insertFirst(copiedNode, null);
		} else {
			listRewrite.insertLast(copiedNode, null);
		}
	}
}
 
Example #11
Source File: NameResolver.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
public boolean visit(ImportDeclaration node) {
    if (node.isOnDemand()) {
        String pckgName = node.getName().getFullyQualifiedName();
        checkInDir(pckgName);
    } else {
        String importName = node.getName().getFullyQualifiedName();
        if (importName.endsWith("." + nameParts[0])) {
            fullName = importName;
            for (int i = 1; i < nameParts.length; i++) {
                fullName += "." + nameParts[i];
            }
            found = true;
        }
    }
    return true;
}
 
Example #12
Source File: ImportRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IRegion evaluateReplaceRange(CompilationUnit root) {
	List imports= root.imports();
	if (!imports.isEmpty()) {
		ImportDeclaration first= (ImportDeclaration) imports.get(0);
		ImportDeclaration last= (ImportDeclaration) imports.get(imports.size() - 1);

		int startPos= first.getStartPosition(); // no extended range for first: bug 121428
		int endPos= root.getExtendedStartPosition(last) + root.getExtendedLength(last);
		int endLine= root.getLineNumber(endPos);
		if (endLine > 0) {
			int nextLinePos= root.getPosition(endLine + 1, 0);
			if (nextLinePos >= 0) {
				int firstTypePos= getFirstTypeBeginPos(root);
				if (firstTypePos != -1 && firstTypePos < nextLinePos) {
					endPos= firstTypePos;
				} else {
					endPos= nextLinePos;
				}
			}
		}
		return new Region(startPos, endPos - startPos);
	} else {
		int start= getPackageStatementEndPos(root);
		return new Region(start, 0);
	}
}
 
Example #13
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private OccurrenceUpdate<? extends ASTNode> createOccurrenceUpdate(ASTNode node, CompilationUnitRewrite cuRewrite, RefactoringStatus result) {
	if (BUG_89686 && node instanceof SimpleName && node.getParent() instanceof EnumConstantDeclaration)
		node= node.getParent();

	if (Invocations.isInvocationWithArguments(node))
		return new ReferenceUpdate(node, cuRewrite, result);

	else if (node instanceof SimpleName && node.getParent() instanceof MethodDeclaration)
		return new DeclarationUpdate((MethodDeclaration) node.getParent(), cuRewrite, result);

	else if (node instanceof MemberRef || node instanceof MethodRef)
		return new DocReferenceUpdate(node, cuRewrite, result);

	else if (ASTNodes.getParent(node, ImportDeclaration.class) != null)
		return new StaticImportUpdate((ImportDeclaration) ASTNodes.getParent(node, ImportDeclaration.class), cuRewrite, result);

	else if (node instanceof LambdaExpression)
		return new LambdaExpressionUpdate((LambdaExpression) node, cuRewrite, result);

	else if (node.getLocationInParent() == ExpressionMethodReference.NAME_PROPERTY)
		return new ExpressionMethodRefUpdate((ExpressionMethodReference) node.getParent(), cuRewrite, result);

	else
		return new NullOccurrenceUpdate(node, cuRewrite, result);
}
 
Example #14
Source File: JavaTypeHierarchyExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public boolean visit(final CompilationUnit node) {
	if (node.getPackage() != null) {
		currentPackageName = node.getPackage().getName()
				.getFullyQualifiedName();
	}
	for (final Object decl : node.imports()) {
		final ImportDeclaration imp = (ImportDeclaration) decl;
		if (!imp.isStatic()) {
			final String fqn = imp.getName().getFullyQualifiedName();
			importedNames.put(fqn.substring(fqn.lastIndexOf('.') + 1),
					fqn);
		}
	}
	return true;
}
 
Example #15
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final ImportDeclaration it) {
  this.appendToBuffer("import ");
  boolean _isStatic = it.isStatic();
  if (_isStatic) {
    this.appendToBuffer("static ");
  }
  it.getName().accept(this);
  boolean _isOnDemand = it.isOnDemand();
  if (_isOnDemand) {
    this.appendToBuffer(".*");
  }
  this.appendLineWrapToBuffer();
  return false;
}
 
Example #16
Source File: SM_Type.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
private void setImportList(CompilationUnit unit) {
	ImportVisitor importVisitor = new ImportVisitor();
	unit.accept(importVisitor);
	List<ImportDeclaration> imports = importVisitor.getImports();
	if (imports.size() > 0)
		importList.addAll(imports);
}
 
Example #17
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static UnusedCodeFix createRemoveUnusedImportFix(CompilationUnit compilationUnit, IProblemLocation problem) {
	if (isUnusedImport(problem)) {
		ImportDeclaration node= getImportDeclaration(problem, compilationUnit);
		if (node != null) {
			String label= FixMessages.UnusedCodeFix_RemoveImport_description;
			RemoveImportOperation operation= new RemoveImportOperation(node);
			Map<String, String> options= new Hashtable<String, String>();
			options.put(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS, CleanUpOptions.TRUE);
			return new UnusedCodeFix(label, compilationUnit, new CompilationUnitRewriteOperation[] {operation}, options);
		}
	}
	return null;
}
 
Example #18
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ImportDeclaration getImportDeclaration(IProblemLocation problem, CompilationUnit compilationUnit) {
	ASTNode selectedNode= problem.getCoveringNode(compilationUnit);
	if (selectedNode != null) {
		ASTNode node= ASTNodes.getParent(selectedNode, ASTNode.IMPORT_DECLARATION);
		if (node instanceof ImportDeclaration) {
			return (ImportDeclaration)node;
		}
	}
	return null;
}
 
Example #19
Source File: Resolver.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
private SM_Type manualLookupForUnresolvedType(SM_Project parentProject, String unresolvedTypeName,
		SM_Type callerType) {
	SM_Type matchedType = null;

	int numberOfDots = new StringTokenizer(" " + unresolvedTypeName + " ", ".").countTokens() - 1;

	// Case of static call Type.field
	if (numberOfDots == 1) {
		unresolvedTypeName = unresolvedTypeName.substring(0, unresolvedTypeName.indexOf("."));
	}
	// Case of static call with full class name :: package.package.Type.field
	else if (numberOfDots > 1) {
		String packageName = getPackageName(unresolvedTypeName);
		String typeName = getTypeName(unresolvedTypeName);
		matchedType = findType(typeName, packageName, parentProject);
		if (matchedType != null) {
			return matchedType;
		}
	}

	if ((matchedType = findType(unresolvedTypeName, callerType.getParentPkg())) != null) {
		return matchedType;
	}
	// TODO break it to different lookups for * and simple.
	else {
		List<ImportDeclaration> importList = callerType.getImportList();
		for (ImportDeclaration importEntry : importList) {
			matchedType = findType(unresolvedTypeName, getPackageName(importEntry.getName().toString()),
					parentProject);
			if (matchedType != null) {
				return matchedType;
			}
		}
	}
	return null;
}
 
Example #20
Source File: UsagePointExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean visit(final ImportDeclaration node) {
	final String qualifiedName = node.getName().getFullyQualifiedName();
	if (qualifiedName.startsWith(fullyQualifiedName)) {
		className.add(getImportedClass(qualifiedName));
		className.add(qualifiedName);
	}
	return false;
}
 
Example #21
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final QualifiedName it) {
  it.getQualifier().accept(this);
  if (((this.fallBackStrategy && this._aSTFlattenerUtils.isStaticMemberCall(it)) && 
    (!((it.getParent() instanceof SimpleType) || (it.getParent() instanceof ImportDeclaration))))) {
    this.appendToBuffer("::");
  } else {
    this.appendToBuffer(".");
  }
  it.getName().accept(this);
  return false;
}
 
Example #22
Source File: FileVisitor.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(ImportDeclaration node) {
	imports.add(new AbstractImport(
			node.getName().getFullyQualifiedName(), 
			node.isStatic(), node.isOnDemand()));
	return true;
}
 
Example #23
Source File: UsagePointExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean visit(final ImportDeclaration node) {
	final String qualifiedName = node.getName().getFullyQualifiedName();
	if (qualifiedName.startsWith(fullyQualifiedName)) {
		className.add(getImportedClass(qualifiedName));
		className.add(qualifiedName);
	}
	return false;
}
 
Example #24
Source File: UsagePointExtractor.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(final ImportDeclaration node) {
	final String qualifiedName = node.getName().getFullyQualifiedName();
	if (qualifiedName.startsWith(fullyQualifiedName)) {
		className.add(getImportedClass(qualifiedName));
		className.add(qualifiedName);
	}
	return false;
}
 
Example #25
Source File: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final void endVisit(final SimpleName node) {
	final ASTNode parent= node.getParent();
	if (!(parent instanceof ImportDeclaration) && !(parent instanceof PackageDeclaration) && !(parent instanceof AbstractTypeDeclaration)) {
		final IBinding binding= node.resolveBinding();
		if (binding instanceof IVariableBinding && !(parent instanceof MethodDeclaration))
			endVisit((IVariableBinding) binding, null, node);
		else if (binding instanceof ITypeBinding && parent instanceof MethodDeclaration)
			endVisit((ITypeBinding) binding, node);
	}
}
 
Example #26
Source File: ASTVisitors.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(final ImportDeclaration node) {
	final String qName = node.getName().getFullyQualifiedName();
	final String imprt = node.toString().trim();
	if (!node.isStatic()) {
		if (imprt.endsWith(".*;") && qName.matches(pattern))
			wildcardImports.add(qName);
	} else {
		if (imprt.endsWith(".*;") && qName.matches(pattern))
			wildcardMethodImports.add(qName);
	}
	return false;
}
 
Example #27
Source File: JavaApproximateTypeInferencer.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(final ImportDeclaration node) {
	if (!node.isStatic()) {
		final String qName = node.getName().getFullyQualifiedName();
		importedNames.put(qName.substring(qName.lastIndexOf('.') + 1), qName);
	}
	return false;
}
 
Example #28
Source File: APICallVisitor.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(final ImportDeclaration node) {
	final String qName = node.getName().getFullyQualifiedName();
	if (!node.isStatic()) {
		importedNames.put(qName.substring(qName.lastIndexOf('.') + 1), qName);
	} else {
		final String name = qName.substring(qName.lastIndexOf('.') + 1);
		if (Character.isLowerCase(name.charAt(0))) // ignore constants
			methodImports.put(name, qName.substring(0, qName.lastIndexOf('.')));
	}
	return false;
}
 
Example #29
Source File: ASTVisitors.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Add imports as single node to foldable tree */
protected void addImportsTree() {

	@SuppressWarnings("unchecked")
	final List<ImportDeclaration> imports = (List<ImportDeclaration>) cu.imports();
	if (!imports.isEmpty()) {

		// Get range of imports (starting after first import statement)
		final ImportDeclaration firstImport = imports.get(0);
		final int startChar = firstImport.getStartPosition() + firstImport.getLength() - 1;
		final ImportDeclaration lastImport = imports.get(imports.size() - 1);
		final int endChar = lastImport.getStartPosition() + lastImport.getLength() - 1;

		// Add import identifiers to identifier list
		final List<String> importIdentifiers = Lists.newArrayList();
		for (final ImportDeclaration importNode : imports)
			putTokenizedImports(importIdentifiers, importNode.getName().getFullyQualifiedName());

		// Remove import identifiers from root token list
		tree.getRoot().removeTerms(importIdentifiers);

		// Add imports as single node to tree
		final ImportDeclaration node = cu.getAST().newImportDeclaration();
		node.setSourceRange(startChar, endChar - startChar + 1);
		final FoldableNode fn = tree.new FoldableNode(node);
		fn.addTerms(importIdentifiers);
		tree.getRoot().addChild(fn);

		// Add import range to allFolds
		importBlock = Range.closed(startChar, endChar);
		allFolds.add(importBlock);
	}
}
 
Example #30
Source File: ImportRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getQualifier(ImportDeclaration decl) {
	String name = decl.getName().getFullyQualifiedName();
	/*
	 * If it's on demand import, return the fully qualified name. (e.g. pack1.Foo.* => pack.Foo, pack1.* => pack1)
	 * This is because we need to have pack1.Foo.* and pack1.Bar under different qualifier groups.
	 */
	if (decl.isOnDemand()) {
		return name;
	}
	return getQualifier(name, decl.isStatic());
}