Java Code Examples for org.eclipse.jdt.core.IPackageFragment#getChildren()

The following examples show how to use org.eclipse.jdt.core.IPackageFragment#getChildren() . 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: PackageFragmentRootWalker.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected T traverse(IPackageFragment pack, boolean stopOnFirstResult, TraversalState state) throws JavaModelException {
	T result = null;
	state.push(pack);
	IJavaElement[] children = pack.getChildren();
	for (IJavaElement iJavaElement : children) {
		if (iJavaElement instanceof IPackageFragment) {
			result = traverse((IPackageFragment) iJavaElement, stopOnFirstResult, state);
			if (stopOnFirstResult && result!=null)
				return result;
		}
	}
	Object[] resources = pack.getNonJavaResources();
	for (Object object : resources) {
		if (object instanceof IJarEntryResource) {
			result = traverse((IJarEntryResource) object, stopOnFirstResult, state);
			if (stopOnFirstResult && result!=null)
				return result;
		}
	}
	state.pop();
	return result;
}
 
Example 2
Source File: RefactoringModifications.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
protected IResource[] collectResourcesOfInterest(IPackageFragment source) throws CoreException {
	IJavaElement[] children = source.getChildren();
	int childOfInterest = IJavaElement.COMPILATION_UNIT;
	if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
		childOfInterest = IJavaElement.CLASS_FILE;
	}
	ArrayList<IResource> result = new ArrayList<>(children.length);
	for (int i = 0; i < children.length; i++) {
		IJavaElement child = children[i];
		if (child.getElementType() == childOfInterest && child.getResource() != null) {
			result.add(child.getResource());
		}
	}
	// Gather non-java resources
	Object[] nonJavaResources = source.getNonJavaResources();
	for (int i= 0; i < nonJavaResources.length; i++) {
		Object element= nonJavaResources[i];
		if (element instanceof IResource) {
			result.add((IResource) element);
		}
	}
	return result.toArray(new IResource[result.size()]);
}
 
Example 3
Source File: SaveUtils.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
public static HashSet<String> getPackageElements(String projectName, String modelName,
		Iterable<String> descriptions) {
	HashSet<String> packageElements = new HashSet<String>();

	for (String description : descriptions) {
		packageElements.add(description + ".java");
	}

	try {
		IPackageFragment[] packages = PackageUtils.findPackageFragments(projectName, modelName);

		for (IPackageFragment pack : packages) {
			String packageName = pack.getElementName();

			for (IJavaElement elem : pack.getChildren()) {
				String fileName = elem.getElementName();
				String fullName = packageName + "." + fileName;

				packageElements.add(fullName);
			}
		}
	} catch (JavaModelException | NotFoundException ex) {
	}

	return packageElements;
}
 
Example 4
Source File: RefactoringModifications.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected IResource[] collectResourcesOfInterest(IPackageFragment source) throws CoreException {
	IJavaElement[] children = source.getChildren();
	int childOfInterest = IJavaElement.COMPILATION_UNIT;
	if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
		childOfInterest = IJavaElement.CLASS_FILE;
	}
	ArrayList<IResource> result = new ArrayList<IResource>(children.length);
	for (int i = 0; i < children.length; i++) {
		IJavaElement child = children[i];
		if (child.getElementType() == childOfInterest && child.getResource() != null) {
			result.add(child.getResource());
		}
	}
	// Gather non-java resources
	Object[] nonJavaResources = source.getNonJavaResources();
	for (int i= 0; i < nonJavaResources.length; i++) {
		Object element= nonJavaResources[i];
		if (element instanceof IResource) {
			result.add((IResource) element);
		}
	}
	return result.toArray(new IResource[result.size()]);
}
 
Example 5
Source File: JavaWorkingSetPageContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean hasChildren(Object element) {

	if (element instanceof IProject && !((IProject)element).isAccessible())
		return false;

	if (element instanceof IPackageFragment) {
		IPackageFragment pkg= (IPackageFragment)element;
		try {
			if (pkg.getKind() == IPackageFragmentRoot.K_BINARY) {
				// Don't show IJarEntryResource
				return pkg.getChildren().length > 0;
			}
		} catch (JavaModelException ex) {
			// use super behavior
		}
	}
	return super.hasChildren(element);
}
 
Example 6
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void addContainedTypes(IPackageFragment pack, List<IType> typesCollector) throws JavaModelException {
	IJavaElement[] children= pack.getChildren();
	for (int c= 0; c < children.length; c++) {
		IJavaElement child= children[c];
		if (child instanceof ICompilationUnit) {
			typesCollector.addAll(Arrays.asList(((ICompilationUnit) child).getTypes()));
		} else if (child instanceof IOrdinaryClassFile) {
			typesCollector.add(((IOrdinaryClassFile) child).getType());
		}
	}
}
 
Example 7
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addContainedTypes(IPackageFragment pack, List<IType> typesCollector) throws JavaModelException {
	IJavaElement[] children= pack.getChildren();
	for (int c= 0; c < children.length; c++) {
		IJavaElement child= children[c];
		if (child instanceof ICompilationUnit) {
			typesCollector.addAll(Arrays.asList(((ICompilationUnit) child).getTypes()));
		} else if (child instanceof IClassFile) {
			typesCollector.add(((IClassFile) child).getType());
		}
	}
}
 
Example 8
Source File: JavadocMemberContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean hasChildren(Object element) {
	try {
		if (element instanceof IPackageFragment) {
			IPackageFragment iPackageFragment= (IPackageFragment) element;
			return (iPackageFragment.getChildren().length > 0);
		}
	} catch (JavaModelException e) {
	}
	return false;
}
 
Example 9
Source File: JarManifestWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a selection dialog that lists all packages under the given package
 * fragment root.
 * The caller is responsible for opening the dialog with <code>Window.open</code>,
 * and subsequently extracting the selected packages (of type
 * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
 *
 * @param packageFragments the package fragments
 * @return a new selection dialog
 */
protected SelectionDialog createPackageDialog(Set<IJavaElement> packageFragments) {
	List<IPackageFragment> packages= new ArrayList<IPackageFragment>(packageFragments.size());
	for (Iterator<IJavaElement> iter= packageFragments.iterator(); iter.hasNext();) {
		IPackageFragment fragment= (IPackageFragment)iter.next();
		boolean containsJavaElements= false;
		int kind;
		try {
			kind= fragment.getKind();
			containsJavaElements= fragment.getChildren().length > 0;
		} catch (JavaModelException ex) {
			ExceptionHandler.handle(ex, getContainer().getShell(), JarPackagerMessages.JarManifestWizardPage_error_jarPackageWizardError_title, Messages.format(JarPackagerMessages.JarManifestWizardPage_error_jarPackageWizardError_message, JavaElementLabels.getElementLabel(fragment, JavaElementLabels.ALL_DEFAULT)));
			continue;
		}
		if (kind != IPackageFragmentRoot.K_BINARY && containsJavaElements)
			packages.add(fragment);
	}
	StandardJavaElementContentProvider cp= new StandardJavaElementContentProvider() {
		@Override
		public boolean hasChildren(Object element) {
			// prevent the + from being shown in front of packages
			return !(element instanceof IPackageFragment) && super.hasChildren(element);
		}
	};
	final DecoratingLabelProvider provider= new DecoratingLabelProvider(new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT), new ProblemsLabelDecorator(null));
	ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getContainer().getShell(), provider, cp);
	dialog.setDoubleClickSelects(false);
	dialog.setComparator(new JavaElementComparator());
	dialog.setInput(JavaCore.create(JavaPlugin.getWorkspace().getRoot()));
	dialog.addFilter(new EmptyInnerPackageFilter());
	dialog.addFilter(new LibraryFilter());
	dialog.addFilter(new SealPackagesFilter(packages));
	dialog.setValidator(new ISelectionStatusValidator() {
		public IStatus validate(Object[] selection) {
			StatusInfo res= new StatusInfo();
			for (int i= 0; i < selection.length; i++) {
				if (!(selection[i] instanceof IPackageFragment)) {
					res.setError(JarPackagerMessages.JarManifestWizardPage_error_mustContainPackages);
					return res;
				}
			}
			res.setOK();
			return res;
		}
	});
	return dialog;
}
 
Example 10
Source File: DeleteResourceElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Deletes the direct children of <code>frag</code> corresponding to its kind
 * (K_SOURCE or K_BINARY), and deletes the corresponding folder if it is then
 * empty.
 */
private void deletePackageFragment(IPackageFragment frag)
	throws JavaModelException {
	IResource res = ((JavaElement) frag).resource();
	if (res != null) {
		// collect the children to remove
		IJavaElement[] childrenOfInterest = frag.getChildren();
		if (childrenOfInterest.length > 0) {
			IResource[] resources = new IResource[childrenOfInterest.length];
			// remove the children
			for (int i = 0; i < childrenOfInterest.length; i++) {
				resources[i] = ((JavaElement) childrenOfInterest[i]).resource();
			}
			deleteResources(resources, this.force);
		}

		// Discard non-java resources
		Object[] nonJavaResources = frag.getNonJavaResources();
		int actualResourceCount = 0;
		for (int i = 0, max = nonJavaResources.length; i < max; i++){
			if (nonJavaResources[i] instanceof IResource) actualResourceCount++;
		}
		IResource[] actualNonJavaResources = new IResource[actualResourceCount];
		for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){
			if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i];
		}
		deleteResources(actualNonJavaResources, this.force);

		// delete remaining files in this package (.class file in the case where Proj=src=bin)
		IResource[] remainingFiles;
		try {
			remainingFiles = ((IContainer) res).members();
		} catch (CoreException ce) {
			throw new JavaModelException(ce);
		}
		boolean isEmpty = true;
		for (int i = 0, length = remainingFiles.length; i < length; i++) {
			IResource file = remainingFiles[i];
			if (file instanceof IFile && org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(file.getName())) {
				deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY);
			} else {
				isEmpty = false;
			}
		}
		if (isEmpty && !frag.isDefaultPackage()/*don't delete default package's folder: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38450*/) {
			// delete recursively empty folders
			IResource fragResource =  ((JavaElement) frag).resource();
			if (fragResource != null) {
				deleteEmptyPackageFragment(frag, false, fragResource.getParent());
			}
		}
	}
}
 
Example 11
Source File: JavaUtils.java    From developer-studio with Apache License 2.0 4 votes vote down vote up
public static boolean isClassImplement(IProject project, String interfaceTocheck) throws JavaModelException{
		IJavaProject jp = JavaCore.create(project);
		try {
			IPackageFragment[] packageFragments = jp.getPackageFragments();
			for (IPackageFragment fragment : packageFragments) {
				IJavaElement[] children = fragment.getChildren();
				for (IJavaElement element : children) {
						ICompilationUnit[] compilationUnits = fragment.getCompilationUnits();
						for (ICompilationUnit unit : compilationUnits) {
							String a = unit.getElementName();
							IType[] types = unit.getTypes();
							for (IType type : types) {
								String[] superInterfaceNames = type.getSuperInterfaceNames();
								if(superInterfaceNames != null){
									for (String interfaceName : superInterfaceNames) {
										if(interfaceName.equals(interfaceTocheck)){
											return true;
										}
									}
								}
							}
						}
				}
			}
		} catch (JavaModelException e) {
			e.printStackTrace();
		}
		
//		IType findType = getJavaITypeForClass(jp, fullyQualifiedClassName);
//		if (findType!=null && findType.getSuperclassName()!=null){
//			String[][] resolveType = findType.resolveType(findType.getSuperclassName());
//			if (resolveType!=null){
//				String fullyQualifiedSuperClassName=(resolveType[0][0]).toString()+"."+(resolveType[0][1]).toString();
//				boolean result = isClassImplement(project, fullyQualifiedSuperClassName,classNameToCheck);
//				if (result){
//					return true;
//				}
//			}
//		}
	
	return false;
		
	}
 
Example 12
Source File: JavaProjectModulesManager.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This method passes through all the java packages and calls the filter callback passed
 * on each package found.
 *
 * If true is returned on the callback, the children of each package (classes) will also be visited,
 * otherwise, they'll be skipped.
 */
private void filterJavaPackages(IFilter filter) {
    IClasspathEntry[] rawClasspath;
    try {
        rawClasspath = this.javaProject.getRawClasspath();
        FastStringBuffer buffer = new FastStringBuffer();
        for (IClasspathEntry entry : rawClasspath) {
            int entryKind = entry.getEntryKind();
            IClasspathEntry resolvedClasspathEntry = JavaCore.getResolvedClasspathEntry(entry);
            if (entryKind != IClasspathEntry.CPE_CONTAINER) {
                //ignore if it's in the system classpath...
                IPackageFragmentRoot[] roots = javaProject.findPackageFragmentRoots(resolvedClasspathEntry);

                //get the package roots
                for (IPackageFragmentRoot root : roots) {
                    IJavaElement[] children = root.getChildren();

                    //get the actual packages
                    for (IJavaElement child : children) {
                        IPackageFragment childPackage = (IPackageFragment) child;
                        String elementName = childPackage.getElementName();

                        //and if the java package is 'accepted'
                        if (filter.accept(elementName, root, childPackage)) {
                            buffer.clear();
                            buffer.append(elementName);
                            int packageNameLen = buffer.length();
                            if (packageNameLen > 0) {
                                buffer.append('.');
                                packageNameLen++;
                            }

                            //traverse its classes
                            for (IJavaElement class_ : childPackage.getChildren()) {
                                buffer.append(FullRepIterable.getFirstPart(class_.getElementName()));
                                filter.accept(buffer.toString(), root, class_);
                                buffer.setCount(packageNameLen); //leave only the package part for the next append
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}