ClassModel(ASTNodeFactory astNodeFactory, String className, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<TypeModel> innerTypes, List<ASTNode> modifiers) { groovism = provide(); this.className = className; this.packageDeclaration = packageDeclaration; this.fields = fieldDeclarations(fields); this.methods = unmodifiableList(new LinkedList<>(methods)); this.modifiers = unmodifiableList(new LinkedList<>(modifiers)); this.imports = imports; this.innerTypes = unmodifiableList(new LinkedList<>(innerTypes)); if (isTestClass(methods)) { this.superClassType = Optional.of(astNodeFactory.simpleType(Specification.class.getSimpleName())); imports.add(0, astNodeFactory.importDeclaration(Specification.class)); } else { this.superClassType = Optional.ofNullable(superClassType); } }
InterfaceModel(String typeName, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<ASTNode> modifiers) { groovism = provide(); LinkedList<ImportDeclaration> importDeclarations = new LinkedList<>(imports); this.superClassType = Optional.ofNullable(superClassType).map(Object::toString); this.typeName = typeName; this.packageDeclaration = packageDeclaration; this.fields = unmodifiableList(new LinkedList<>(fields)); this.methods = unmodifiableList(new LinkedList<>(methods)); this.imports = unmodifiableList(importDeclarations); this.modifiers = unmodifiableList(modifiers); }
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; }
static UnresolvableImportMatcher forCompilationUnit(CompilationUnit cu) { Collection<ImportDeclaration> unresolvableImports= determineUnresolvableImports(cu); Map<String, Set<String>> typeImportsBySimpleName= new HashMap<>(); Map<String, Set<String>> staticImportsBySimpleName= new HashMap<>(); for (ImportDeclaration importDeclaration : unresolvableImports) { String qualifiedName= importDeclaration.isOnDemand() ? importDeclaration.getName().getFullyQualifiedName() + ".*" //$NON-NLS-1$ : importDeclaration.getName().getFullyQualifiedName(); String simpleName= qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1); Map<String, Set<String>> importsBySimpleName= importDeclaration.isStatic() ? staticImportsBySimpleName : typeImportsBySimpleName; Set<String> importsWithSimpleName= importsBySimpleName.get(simpleName); if (importsWithSimpleName == null) { importsWithSimpleName= new HashSet<>(); importsBySimpleName.put(simpleName, importsWithSimpleName); } importsWithSimpleName.add(qualifiedName); } return new UnresolvableImportMatcher(typeImportsBySimpleName, staticImportsBySimpleName); }
@Override public void endVisit(ImportDeclaration node) { boolean filtered = false; if (!node.isOnDemand()) { // if it is not x.y.* ITypeBinding tb = (ITypeBinding) node.resolveBinding(); String qualifiedName = tb.getQualifiedName(); for (String filter : filters) { Pattern patternJava = Pattern.compile(filter); Matcher matcherJava = patternJava.matcher(qualifiedName); if (matcherJava.matches()) { filtered = true; } } /* * if (!model.hasMapping(qualifiedName) && !filtered) { * model.addMapping(new Entry(qualifiedName)); } */ } }
private boolean hasImportDeclaration(CompilationUnit unit) { List imports = unit.imports(); for(Iterator iter = imports.iterator(); iter.hasNext() ; ) { Object next = iter.next(); if (next instanceof ImportDeclaration ) { ImportDeclaration importDecl = (ImportDeclaration)next; Name name = importDecl.getName(); if (name instanceof QualifiedName ) { QualifiedName qName = (QualifiedName)name; String qNameString = qName.getFullyQualifiedName(); if (qNameString.startsWith("edu.cmu.cs.aliasjava.annotations") ) { return true; } } } } return false; }
public Collection<String> getUsedVariableNames(int offset, int length) { HashSet<String> result = new HashSet<String>(); IBinding[] bindingsBefore = getDeclarationsInScope(offset, VARIABLES); for (int i = 0; i < bindingsBefore.length; i++) { result.add(bindingsBefore[i].getName()); } IBinding[] bindingsAfter = getDeclarationsAfter(offset + length, VARIABLES); for (int i = 0; i < bindingsAfter.length; i++) { result.add(bindingsAfter[i].getName()); } List<ImportDeclaration> imports = fRoot.imports(); for (int i = 0; i < imports.size(); i++) { ImportDeclaration decl = imports.get(i); if (decl.isStatic() && !decl.isOnDemand()) { result.add(ASTNodes.getSimpleNameIdentifier(decl.getName())); } } return result; }
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); }
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); } } }
private void copyImportToDestination( IImportDeclaration declaration, ASTRewrite targetRewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException { ImportDeclaration sourceNode = ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode); ImportDeclaration copiedNode = (ImportDeclaration) ASTNode.copySubtree(targetRewrite.getAST(), sourceNode); ListRewrite listRewrite = targetRewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY); if (getJavaElementDestination() instanceof IImportDeclaration) { ImportDeclaration destinationNode = ASTNodeSearchUtil.getImportDeclarationNode( (IImportDeclaration) getJavaElementDestination(), destinationCuNode); insertRelative(copiedNode, destinationNode, listRewrite); } else { // dropped on container, we could be better here listRewrite.insertLast(copiedNode, null); } }
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()); }
@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; }
@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); } }
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); }
@Override public final void endVisit(final QualifiedName node) { final ASTNode parent= node.getParent(); final Name qualifier= node.getQualifier(); IBinding binding= qualifier.resolveBinding(); if (binding instanceof ITypeBinding) { final ConstraintVariable2 variable= fModel.createTypeVariable((ITypeBinding) binding, new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(node), new SourceRange(qualifier.getStartPosition(), qualifier.getLength()))); if (variable != null) qualifier.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable); } binding= node.getName().resolveBinding(); if (binding instanceof IVariableBinding && !(parent instanceof ImportDeclaration)) endVisit((IVariableBinding) binding, qualifier, node); else if (binding instanceof ITypeBinding && parent instanceof MethodDeclaration) endVisit((ITypeBinding) binding, node); }
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); } } }
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()); }
public Collection<String> getUsedVariableNames(int offset, int length) { HashSet<String> result= new HashSet<String>(); IBinding[] bindingsBefore= getDeclarationsInScope(offset, VARIABLES); for (int i= 0; i < bindingsBefore.length; i++) { result.add(bindingsBefore[i].getName()); } IBinding[] bindingsAfter= getDeclarationsAfter(offset + length, VARIABLES); for (int i= 0; i < bindingsAfter.length; i++) { result.add(bindingsAfter[i].getName()); } List<ImportDeclaration> imports= fRoot.imports(); for (int i= 0; i < imports.size(); i++) { ImportDeclaration decl= imports.get(i); if (decl.isStatic() && !decl.isOnDemand()) { result.add(ASTNodes.getSimpleNameIdentifier(decl.getName())); } } return result; }
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); } }
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 return new NullOccurrenceUpdate(node, cuRewrite, result); }
/** * Adds an import to a compilation unit, if missing * * @param node * @param newImportName */ @SuppressWarnings("unchecked") private static void addImportToCompilationUnitIfMissing(final ASTNode node, final String newImportName) { final CompilationUnit compilationUnit = (CompilationUnit) node.getRoot(); boolean hasImport = false; for (final Iterator<?> iterator = compilationUnit.imports().iterator(); iterator.hasNext() && !hasImport;) { final ImportDeclaration importDeclaration = (ImportDeclaration) iterator.next(); final String importName = importDeclaration.getName().getFullyQualifiedName(); if (importName.equals(newImportName)) { hasImport = true; } } if (!hasImport) { final ImportDeclaration newImportDeclaration = node.getAST().newImportDeclaration(); newImportDeclaration.setName(node.getAST().newName(newImportName)); compilationUnit.imports().add(newImportDeclaration); } }
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<ImportDeclaration>(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); } }
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 } }
private boolean isImportExists(CompilationUnit compilationUnit, String generatedFullyQualifiedName) { return ((List<ImportDeclaration>) compilationUnit.imports()) .stream() .filter(importDeclaration -> importDeclaration.getName().toString().equals(generatedFullyQualifiedName)) .findFirst() .map(found -> Boolean.TRUE) .orElse(Boolean.FALSE); }
private static Collection<ImportDeclaration> determineUnresolvableImports(CompilationUnit cu) { Collection<ImportDeclaration> unresolvableImports= new ArrayList<>(cu.imports().size()); for (IProblem problem : cu.getProblems()) { if (problem.getID() == IProblem.ImportNotFound) { ImportDeclaration problematicImport= getProblematicImport(problem, cu); if (problematicImport != null) { unresolvableImports.add(problematicImport); } } } return unresolvableImports; }
private static ImportDeclaration getProblematicImport(IProblem problem, CompilationUnit astRoot) { ASTNode coveringNode = new NodeFinder(astRoot, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart()).getCoveringNode(); if (coveringNode != null) { ASTNode importNode= ASTNodes.getParent(coveringNode, ASTNode.IMPORT_DECLARATION); if (importNode instanceof ImportDeclaration) { return (ImportDeclaration) importNode; } } return null; }
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<>(); options.put(CleanUpConstants.REMOVE_UNUSED_CODE_IMPORTS, CleanUpOptions.TRUE); return new UnusedCodeFix(label, compilationUnit, new CompilationUnitRewriteOperation[] {operation}, options); } } return null; }
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; }
@Override public void endVisit(ImportDeclaration node) { if (skipNode(node)) { return; } assignFlowInfo(node, node.getName()); }
@Test public void testCorrectMappingBetweenImport_Depend() { for(ImportDeclaration importDecl: visitor.getImportDeclarations()){ kieSession.insert(importDecl); } kieSession.fireAllRules(); Assert.assertEquals(2, uClass.getDepends().size()); Assert.assertEquals("java.util.*", uClass.getDepends().get(0).getName()); Assert.assertEquals("java.io.*", uClass.getDepends().get(1).getName()); }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { ImportDeclaration node = fImportDeclaration; TextEditGroup group = createTextEditGroup(FixMessages.UnusedCodeFix_RemoveImport_description, cuRewrite); cuRewrite.getASTRewrite().remove(node, group); }
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; }