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

The following examples show how to use org.eclipse.jdt.core.dom.PackageDeclaration. 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: 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 #2
Source File: NameResolver.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: JavaFileParser.java    From buck with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: ClassPathDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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));
			}
		}
	}
}
 
Example #5
Source File: ElementTypeTeller.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #6
Source File: SharedUtils.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: UglyMathCommentsExtractor.java    From compiler with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #8
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 #9
Source File: SarlClassPathDetector.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** 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));
			}
		}
	}
}
 
Example #10
Source File: ImportRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #11
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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);
}
 
Example #12
Source File: JavadocContentAccess2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #13
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 #14
Source File: CreatePackageDeclarationOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #15
Source File: AbstractSourceExporter.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
@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();
	}
}
 
Example #16
Source File: UglyMathCommentsExtractor.java    From compiler with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #17
Source File: CopyrightManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #18
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@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;
}
 
Example #19
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@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;
}
 
Example #20
Source File: JavadocContentAccess2.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example #21
Source File: JavadocContentAccess.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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);
}
 
Example #23
Source File: FlowAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void endVisit(PackageDeclaration node) {
	if (skipNode(node)) {
		return;
	}
	assignFlowInfo(node, node.getName());
}
 
Example #24
Source File: JavaFileParser.java    From buck with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #25
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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();
}
 
Example #26
Source File: CopyrightManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: ReferenceResolvingVisitor.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean visit(PackageDeclaration node)
{
    return super.visit(node);
}
 
Example #28
Source File: FileVisitor.java    From repositoryminer with Apache License 2.0 4 votes vote down vote up
@Override
public boolean visit(PackageDeclaration node) {
	packageName = node.getName().getFullyQualifiedName();
	return true;
}
 
Example #29
Source File: GenericVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void endVisit(PackageDeclaration node) {
	endVisitNode(node);
}
 
Example #30
Source File: GenericVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean visit(PackageDeclaration node) {
	return visitNode(node);
}