类org.eclipse.jdt.core.dom.PackageDeclaration源码实例Demo

下面列出了怎么用org.eclipse.jdt.core.dom.PackageDeclaration的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: SnowGraph   文件: NameResolver.java
/**
 * Evaluates fully qualified name of the TypeDeclaration object.
 */
public static String getFullName(TypeDeclaration decl) {
    String name = decl.getName().getIdentifier();
    ASTNode parent = decl.getParent();
    // resolve full name e.g.: A.B
    while (parent != null && parent.getClass() == TypeDeclaration.class) {
        name = ((TypeDeclaration) parent).getName().getIdentifier() + "." + name;
        parent = parent.getParent();
    }
    // resolve fully qualified name e.g.: some.package.A.B
    if (decl.getRoot().getClass() == CompilationUnit.class) {
        CompilationUnit root = (CompilationUnit) decl.getRoot();
        if (root.getPackage() != null) {
            PackageDeclaration pack = root.getPackage();
            name = pack.getName().getFullyQualifiedName() + "." + name;
        }
    }
    return name;
}
 
源代码2 项目: RefactoringMiner   文件: UMLModelASTReader.java
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);
       	}
       }
}
 
源代码3 项目: compiler   文件: UglyMathCommentsExtractor.java
private static int getNodeStartPosition(final ASTNode node) {
    if (node instanceof MethodDeclaration) {
        MethodDeclaration decl = (MethodDeclaration) node;
        return decl.isConstructor() ? decl.getName().getStartPosition() : decl.getReturnType2().getStartPosition();
    } else if (node instanceof FieldDeclaration) {
        return ((FieldDeclaration) node).getType().getStartPosition();
    } else if (node instanceof AbstractTypeDeclaration) {
        return ((AbstractTypeDeclaration) node).getName().getStartPosition();
    } else if (node instanceof AnnotationTypeMemberDeclaration) {
        return ((AnnotationTypeMemberDeclaration) node).getName().getStartPosition();
    } else if (node instanceof EnumConstantDeclaration) {
        return ((EnumConstantDeclaration) node).getName().getStartPosition();
    } else if (node instanceof PackageDeclaration) {
        return ((PackageDeclaration) node).getName().getStartPosition();
    }
    /* TODO: Initializer */

    return node.getStartPosition();
}
 
源代码4 项目: txtUML   文件: SharedUtils.java
public static String qualifiedName(TypeDeclaration decl) {
	String name = decl.getName().getIdentifier();
	ASTNode parent = decl.getParent();
	// resolve full name e.g.: A.B
	while (parent != null && parent.getClass() == TypeDeclaration.class) {
		name = ((TypeDeclaration) parent).getName().getIdentifier() + "." + name;
		parent = parent.getParent();
	}
	// resolve fully qualified name e.g.: some.package.A.B
	if (decl.getRoot().getClass() == CompilationUnit.class) {
		CompilationUnit root = (CompilationUnit) decl.getRoot();
		if (root.getPackage() != null) {
			PackageDeclaration pack = root.getPackage();
			name = pack.getName().getFullyQualifiedName() + "." + name;
		}
	}
	return name;
}
 
源代码5 项目: txtUML   文件: ElementTypeTeller.java
public static boolean isModelElement(CompilationUnit unit) {
	// careful nullchecking is required below
	// to prevent the workspace problem window from appearing

	PackageDeclaration packageDeclaration = unit.getPackage();
	if (packageDeclaration == null) {
		// the model cannot be in default package
		return false;
	}

	IPackageBinding packageBinding = packageDeclaration.resolveBinding();
	if (packageBinding == null) {
		// wrong package declaration, can't validate
		return false;
	}

	IJavaElement javaElement = packageBinding.getJavaElement();
	if (javaElement == null) {
		// something went wrong during the lookup, can't validate
		return false;
	}

	return isModelPackage((IPackageFragment) javaElement);
}
 
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());
}
 
private void visitCompilationUnit(IFile file) {
	ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file);
	if (cu != null) {
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		CompilationUnit root= (CompilationUnit)parser.createAST(null);
		PackageDeclaration packDecl= root.getPackage();
		
		IPath packPath= file.getParent().getFullPath();
		String cuName= file.getName();
		if (packDecl == null) {
			addToMap(fSourceFolders, packPath, new Path(cuName));
		} else {
			IPath relPath= new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			IPath folderPath= getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(fSourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
	//look for an existing package declaration
	IJavaElement[] children = getCompilationUnit().getChildren();
	for (int i = 0; i < children.length; i++) {
		if (children[i].getElementType() ==  IJavaElement.PACKAGE_DECLARATION && this.name.equals(children[i].getElementName())) {
			//equivalent package declaration already exists
			this.creationOccurred = false;
			return null;
		}
	}
	AST ast = this.cuAST.getAST();
	PackageDeclaration pkgDeclaration = ast.newPackageDeclaration();
	Name astName = ast.newName(this.name);
	pkgDeclaration.setName(astName);
	return pkgDeclaration;
}
 
源代码9 项目: sarl   文件: SarlClassPathDetector.java
/** Visit the given Java compilation unit.
 *
 * @param jfile the compilation unit.
 */
protected void visitJavaCompilationUnit(IFile jfile) {
	final ICompilationUnit cu = JavaCore.createCompilationUnitFrom(jfile);
	if (cu != null) {
		final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		final CompilationUnit root = (CompilationUnit) parser.createAST(null);
		final PackageDeclaration packDecl = root.getPackage();

		final IPath packPath = jfile.getParent().getFullPath();
		final String cuName = jfile.getName();
		if (packDecl == null) {
			addToMap(this.sourceFolders, packPath, new Path(cuName));
		} else {
			final IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			final IPath folderPath = getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(this.sourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
源代码10 项目: buck   文件: JavaFileParser.java
@Nullable
private String getFullyQualifiedTypeName(AbstractTypeDeclaration node) {
  LinkedList<String> nameParts = new LinkedList<>();
  nameParts.add(node.getName().toString());
  ASTNode parent = node.getParent();
  while (!(parent instanceof CompilationUnit)) {
    if (parent instanceof AbstractTypeDeclaration) {
      nameParts.addFirst(((AbstractTypeDeclaration) parent).getName().toString());
      parent = parent.getParent();
    } else if (parent instanceof AnonymousClassDeclaration) {
      // If this is defined in an anonymous class, then there is no meaningful fully qualified
      // name.
      return null;
    } else {
      throw new RuntimeException("Unexpected parent " + parent + " for " + node);
    }
  }

  // A Java file might not have a package. Hopefully all of ours do though...
  PackageDeclaration packageDecl = ((CompilationUnit) parent).getPackage();
  if (packageDecl != null) {
    nameParts.addFirst(packageDecl.getName().toString());
  }

  return Joiner.on(".").join(nameParts);
}
 
/**
 * Adds copyright header to the compilation unit
 *
 * @param compilationUnit
 *            compilation unit affected
 * @return compilation unit change
 */
public CompilationUnitChange addCopyrightsHeader(final CompilationUnit compilationUnit) {
	final ICompilationUnit unit = (ICompilationUnit) compilationUnit.getJavaElement();
	change = new CompilationUnitChange(ADD_COPYRIGHT, unit);
	rewriter = ASTRewrite.create(compilationUnit.getAST());
	final ListRewrite listRewrite = rewriter.getListRewrite(compilationUnit.getPackage(),
			PackageDeclaration.ANNOTATIONS_PROPERTY);
	final Comment placeHolder = (Comment) rewriter.createStringPlaceholder(getCopyrightText() + NEW_LINE_SEPARATOR,
			ASTNode.BLOCK_COMMENT);
	listRewrite.insertFirst(placeHolder, null);
	rewriteCompilationUnit(unit, getNewUnitSource(unit, null));
	return change;
}
 
/**
 * Checks whether {@link CompilationUnit} has copyright header
 *
 * @param compilationUnit
 *            checked compilation unit
 * @return true if {@link CompilationUnit} has copyright header
 */
public boolean hasCopyrightsComment(final CompilationUnit compilationUnit) {
	final List<Comment> comments = getCommentList(compilationUnit);
	boolean hasCopyrights = false;
	if (!comments.isEmpty()) {
		final PackageDeclaration packageNode = compilationUnit.getPackage();
		final boolean commentBeforePackage = comments.get(0).getStartPosition() <= packageNode.getStartPosition();
		final boolean hasJavaDoc = packageNode.getJavadoc() != null;
		hasCopyrights = commentBeforePackage || hasJavaDoc;
	}
	return hasCopyrights;
}
 
源代码13 项目: eclipse.jdt.ls   文件: JDTUtils.java
public static String getPackageName(IJavaProject javaProject, String fileContent) {
	if (fileContent == null) {
		return "";
	}
	//TODO probably not the most efficient way to get the package name as this reads the whole file;
	char[] source = fileContent.toCharArray();
	ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setProject(javaProject);
	parser.setIgnoreMethodBodies(true);
	parser.setSource(source);
	CompilationUnit ast = (CompilationUnit) parser.createAST(null);
	PackageDeclaration pkg = ast.getPackage();
	return (pkg == null || pkg.getName() == null)?"":pkg.getName().getFullyQualifiedName();
}
 
源代码14 项目: eclipse.jdt.ls   文件: FlowAnalyzer.java
@Override
public void endVisit(PackageDeclaration node) {
	if (skipNode(node)) {
		return;
	}
	assignFlowInfo(node, node.getName());
}
 
源代码15 项目: eclipse.jdt.ls   文件: ReorgPolicyFactory.java
private void copyPackageDeclarationToDestination(IPackageDeclaration declaration, ASTRewrite targetRewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException {
	if (destinationCuNode.getPackage() != null) {
		return;
	}
	PackageDeclaration sourceNode= ASTNodeSearchUtil.getPackageDeclarationNode(declaration, sourceCuNode);
	PackageDeclaration copiedNode= (PackageDeclaration) ASTNode.copySubtree(targetRewrite.getAST(), sourceNode);
	targetRewrite.set(destinationCuNode, CompilationUnit.PACKAGE_PROPERTY, copiedNode, null);
}
 
源代码16 项目: eclipse.jdt.ls   文件: JavadocContentAccess.java
private static Javadoc getPackageJavadocNode(IJavaElement element, String cuSource) {
	CompilationUnit cu= createAST(element, cuSource);
	if (cu != null) {
		PackageDeclaration packDecl= cu.getPackage();
		if (packDecl != null) {
			return packDecl.getJavadoc();
		}
	}
	return null;
}
 
源代码17 项目: eclipse.jdt.ls   文件: JavadocContentAccess2.java
private static Javadoc getPackageJavadocNode(IJavaElement element, String cuSource) {
	CompilationUnit cu = createAST(element, cuSource);
	if (cu != null) {
		PackageDeclaration packDecl = cu.getPackage();
		if (packDecl != null) {
			return packDecl.getJavadoc();
		}
	}
	return null;
}
 
源代码18 项目: xtext-xtend   文件: JavaASTFlattener.java
@Override
public boolean visit(final CompilationUnit it) {
  boolean _isDummyType = this._aSTFlattenerUtils.isDummyType(IterableExtensions.<AbstractTypeDeclaration>head(it.types()));
  boolean _not = (!_isDummyType);
  if (_not) {
    PackageDeclaration _package = it.getPackage();
    if (_package!=null) {
      _package.accept(this);
    }
    this.visitAll(it.imports());
  }
  this.visitAll(it.types());
  return false;
}
 
源代码19 项目: xtext-xtend   文件: JavaASTFlattener.java
@Override
public boolean visit(final PackageDeclaration it) {
  Javadoc _javadoc = it.getJavadoc();
  boolean _tripleNotEquals = (_javadoc != null);
  if (_tripleNotEquals) {
    it.getJavadoc().accept(this);
  }
  this.visitAll(it.annotations(), " ");
  this.appendToBuffer("package ");
  it.getName().accept(this);
  this.appendLineWrapToBuffer();
  return false;
}
 
源代码20 项目: compiler   文件: UglyMathCommentsExtractor.java
private final int getNodeFirstLeadingCommentIndex(final ASTNode node) {
    if (node instanceof PackageDeclaration) {
        if (commentsVisited.length > 0) {
            final Comment comment = (Comment) comments.get(0);
            if (comment.getStartPosition() + comment.getLength() <= ((PackageDeclaration) node).getName()
                    .getStartPosition()) {
                return 0;
            }
        }
        return -1;
    } else {
        return cu.firstLeadingCommentIndex(node);
    }
}
 
源代码21 项目: txtUML   文件: AbstractSourceExporter.java
@Override
public ModelId getModelOf(Class<?> element, ElementExporter elementExporter) throws ElementExportationException {
	try {
		Package ownPackage = element.getPackage();

		if (ownPackage.getAnnotation(Model.class) != null) {
			return new ModelIdImpl(ownPackage.getName());
		}
		String ownPackageName = ownPackage.getName();

		IJavaProject javaProject = ProjectUtils.findJavaProject(elementExporter.getSourceProjectName());

		Stream<ICompilationUnit> stream = PackageUtils.findAllPackageFragmentsAsStream(javaProject)
				.filter(p -> ownPackageName.startsWith(p.getElementName() + "."))
				.map(pf -> pf.getCompilationUnit(PackageUtils.PACKAGE_INFO)).filter(ICompilationUnit::exists);

		String topPackageName = Stream.of(SharedUtils.parseICompilationUnitStream(stream, javaProject))
				.map(CompilationUnit::getPackage).filter(Objects::nonNull).map(PackageDeclaration::resolveBinding)
				.filter(Objects::nonNull).filter(pb -> ModelUtils.findModelNameInTopPackage(pb).isPresent())
				.map(IPackageBinding::getName).findFirst().get();

		return new ModelIdImpl(topPackageName);

	} catch (NotFoundException | JavaModelException | IOException | NoSuchElementException e) {
		e.printStackTrace();
		throw new ElementExportationException();
	}
}
 
@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);
	}
}
 
private void copyPackageDeclarationToDestination(IPackageDeclaration declaration, ASTRewrite targetRewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException {
	if (destinationCuNode.getPackage() != null)
		return;
	PackageDeclaration sourceNode= ASTNodeSearchUtil.getPackageDeclarationNode(declaration, sourceCuNode);
	PackageDeclaration copiedNode= (PackageDeclaration) ASTNode.copySubtree(targetRewrite.getAST(), sourceNode);
	targetRewrite.set(destinationCuNode, CompilationUnit.PACKAGE_PROPERTY, copiedNode, null);
}
 
private static Javadoc getPackageJavadocNode(IJavaElement element, String cuSource) {
	CompilationUnit cu= createAST(element, cuSource);
	if (cu != null) {
		PackageDeclaration packDecl= cu.getPackage();
		if (packDecl != null) {
			return packDecl.getJavadoc();
		}
	}
	return null;
}
 
private int getPackageStatementEndPos(CompilationUnit root) {
	PackageDeclaration packDecl= root.getPackage();
	if (packDecl != null) {
		int afterPackageStatementPos= -1;
		int lineNumber= root.getLineNumber(packDecl.getStartPosition() + packDecl.getLength());
		if (lineNumber >= 0) {
			int lineAfterPackage= lineNumber + 1;
			afterPackageStatementPos= root.getPosition(lineAfterPackage, 0);
		}
		if (afterPackageStatementPos < 0) {
			this.flags|= F_NEEDS_LEADING_DELIM;
			return packDecl.getStartPosition() + packDecl.getLength();
		}
		int firstTypePos= getFirstTypeBeginPos(root);
		if (firstTypePos != -1 && firstTypePos <= afterPackageStatementPos) {
			this.flags|= F_NEEDS_TRAILING_DELIM;
			if (firstTypePos == afterPackageStatementPos) {
				this.flags|= F_NEEDS_LEADING_DELIM;
			}
			return firstTypePos;
		}
		this.flags|= F_NEEDS_LEADING_DELIM;
		return afterPackageStatementPos; // insert a line after after package statement
	}
	this.flags |= F_NEEDS_TRAILING_DELIM;
	return 0;
}
 
源代码26 项目: buck   文件: JavaFileParser.java
public Optional<String> getPackageNameFromSource(String code) {
  CompilationUnit compilationUnit = makeCompilationUnitFromSource(code);

  // A Java file might not have a package. Hopefully all of ours do though...
  PackageDeclaration packageDecl = compilationUnit.getPackage();
  if (packageDecl != null) {
    return Optional.of(packageDecl.getName().toString());
  }
  return Optional.empty();
}
 
源代码27 项目: junion   文件: ReadableFlattener.java
public boolean br(ASTNode node) {
	return node instanceof ExpressionStatement || node instanceof VariableDeclarationStatement || node instanceof BreakStatement || node instanceof ContinueStatement || node instanceof PackageDeclaration || node instanceof ImportDeclaration || node instanceof Javadoc;
}
 
private static String getPackageOfJavaFile(CompilationUnit cu) {
  PackageDeclaration pkg = cu.getPackage();
  return pkg == null ? "" : pkg.getName().getFullyQualifiedName();
}
 
源代码29 项目: SnowGraph   文件: NameResolver.java
public boolean visit(PackageDeclaration node) {
    String pckgName = node.getName().getFullyQualifiedName();
    checkInDir(pckgName);
    return true;
}
 
源代码30 项目: eclipse.jdt.ls   文件: ASTNodeSearchUtil.java
public static PackageDeclaration getPackageDeclarationNode(IPackageDeclaration reference, CompilationUnit cuNode) throws JavaModelException {
	return (PackageDeclaration) findNode(reference.getSourceRange(), cuNode);
}
 
 类所在包
 同包方法