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

The following examples show how to use org.eclipse.jdt.core.IPackageFragmentRoot#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: TypeCheckingEvolution.java    From JDeodorant with MIT License 6 votes vote down vote up
private List<TypeCheckElimination> generateTypeCheckEliminationsWithinJavaProject(IJavaProject javaProject, TypeCheckElimination elimination) {
	List<TypeCheckElimination> typeCheckEliminations = new ArrayList<TypeCheckElimination>();
	try {
		IPackageFragmentRoot[] iPackageFragmentRoots = javaProject.getPackageFragmentRoots();
		for(IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
			IJavaElement[] children = iPackageFragmentRoot.getChildren();
			for(IJavaElement child : children) {
				if(child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
					IPackageFragment iPackageFragment = (IPackageFragment)child;
					ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
					for(ICompilationUnit iCompilationUnit : iCompilationUnits) {
						ASTParser parser = ASTParser.newParser(ASTReader.JLS);
				        parser.setKind(ASTParser.K_COMPILATION_UNIT);
				        parser.setSource(iCompilationUnit);
				        parser.setResolveBindings(true); // we need bindings later on
				        CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
						typeCheckEliminations.addAll(generateTypeCheckEliminationsWithinCompilationUnit(compilationUnit, elimination));
					}
				}
			}
		}
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	return typeCheckEliminations;
}
 
Example 2
Source File: ExternalizeStringsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<NonNLSElement> analyze(IPackageFragmentRoot sourceFolder, IProgressMonitor pm) throws CoreException {
	try{
		IJavaElement[] children= sourceFolder.getChildren();
		pm.beginTask("", children.length); //$NON-NLS-1$
		pm.setTaskName(JavaElementLabels.getElementLabel(sourceFolder, JavaElementLabels.ALL_DEFAULT));
		List<NonNLSElement> result= new ArrayList<NonNLSElement>();
		for (int i= 0; i < children.length; i++) {
			IJavaElement iJavaElement= children[i];
			if (iJavaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT){
				IPackageFragment pack= (IPackageFragment)iJavaElement;
				if (! pack.isReadOnly())
					result.addAll(analyze(pack, new SubProgressMonitor(pm, 1)));
				else
					pm.worked(1);
			} else
				pm.worked(1);
		}
		return result;
	} finally{
		pm.done();
	}
}
 
Example 3
Source File: JavaBrowsingContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException {
	if (!project.getProject().isOpen())
		return NO_CHILDREN;

	IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
	List<IJavaElement> list= new ArrayList<IJavaElement>(roots.length);
	// filter out package fragments that correspond to projects and
	// replace them with the package fragments directly
	for (int i= 0; i < roots.length; i++) {
		IPackageFragmentRoot root= roots[i];
		if (!root.isExternal()) {
			IJavaElement[] children= root.getChildren();
			for (int k= 0; k < children.length; k++)
				list.add(children[k]);
		}
		else if (hasChildren(root)) {
			list.add(root);
		}
	}
	return concatenate(list.toArray(), project.getNonJavaResources());
}
 
Example 4
Source File: ClientBundleResourceSelectionDialog.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private boolean showPackageFragmentRoot(IPackageFragmentRoot srcRoot)
    throws JavaModelException {
  // Only show roots defined in source
  if (!(srcRoot.getKind() == IPackageFragmentRoot.K_SOURCE)) {
    return false;
  }

  // Only show roots with visible packages underneath
  for (IJavaElement child : srcRoot.getChildren()) {
    if (child instanceof IPackageFragment) {
      if (showPackage((IPackageFragment) child)) {
        // At least one package underneath this root should be visible
        return true;
      }
    }
  }
  return false;
}
 
Example 5
Source File: PackagesViewHierarchicalContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IPackageFragment[] findNextLevelChildrenByElementName(IPackageFragmentRoot parent, IPackageFragment fragment) {
	List<IPackageFragment> list= new ArrayList<IPackageFragment>();
	try {

		IJavaElement[] children= parent.getChildren();
		String fragmentname= fragment.getElementName();
		for (int i= 0; i < children.length; i++) {
			IJavaElement element= children[i];
			if (element instanceof IPackageFragment) {
				IPackageFragment frag= (IPackageFragment) element;

				String name= element.getElementName();
				if (name.length() > fragmentname.length() && name.charAt(fragmentname.length()) == '.' && frag.exists() && !IPackageFragment.DEFAULT_PACKAGE_NAME.equals(fragmentname) && name.startsWith(fragmentname) && !name.equals(fragmentname)) {
					String tail= name.substring(fragmentname.length() + 1);
					if (!IPackageFragment.DEFAULT_PACKAGE_NAME.equals(tail) && tail.indexOf('.') == -1) {
						list.add(frag);
					}
				}
			}
		}

	} catch (JavaModelException e) {
		JavaPlugin.log(e);
	}
	return list.toArray(new IPackageFragment[list.size()]);
}
 
Example 6
Source File: JavaElementUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param pack a package fragment
 * @return an array containing the given package and all subpackages
 * @throws JavaModelException if getting the all sibling packages fails
 */
public static IPackageFragment[] getPackageAndSubpackages(IPackageFragment pack) throws JavaModelException {
	if (pack.isDefaultPackage()) {
		return new IPackageFragment[] { pack };
	}

	IPackageFragmentRoot root= (IPackageFragmentRoot) pack.getParent();
	IJavaElement[] allPackages= root.getChildren();
	ArrayList<IPackageFragment> subpackages= new ArrayList<>();
	subpackages.add(pack);
	String prefix= pack.getElementName() + '.';
	for (int i= 0; i < allPackages.length; i++) {
		IPackageFragment currentPackage= (IPackageFragment) allPackages[i];
		if (currentPackage.getElementName().startsWith(prefix)) {
			subpackages.add(currentPackage);
		}
	}
	return subpackages.toArray(new IPackageFragment[subpackages.size()]);
}
 
Example 7
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns all the package fragments found in the specified
 * package fragment roots.
 * @param roots IPackageFragmentRoot[]
 * @return IPackageFragment[]
 */
public IPackageFragment[] getPackageFragmentsInRoots(IPackageFragmentRoot[] roots) {

	ArrayList frags = new ArrayList();
	for (int i = 0; i < roots.length; i++) {
		IPackageFragmentRoot root = roots[i];
		try {
			IJavaElement[] rootFragments = root.getChildren();
			for (int j = 0; j < rootFragments.length; j++) {
				frags.add(rootFragments[j]);
			}
		} catch (JavaModelException e) {
			// do nothing
		}
	}
	IPackageFragment[] fragments = new IPackageFragment[frags.size()];
	frags.toArray(fragments);
	return fragments;
}
 
Example 8
Source File: PackageFragmentRootWalker.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public T traverse(IPackageFragmentRoot root, boolean stopOnFirstResult) throws JavaModelException {
	T result = null;
	if (root.exists() && existsPhysically(root)) {
		Object[] resources = root.getNonJavaResources();
		TraversalState state = new TraversalState(root);
		for (Object object : resources) {
			if (object instanceof IJarEntryResource) {
				result = traverse((IJarEntryResource) object, stopOnFirstResult, state);
				if (stopOnFirstResult && result != null)
					return result;
			}
		}

		IJavaElement[] children = root.getChildren();
		for (IJavaElement javaElement : children) {
			if (javaElement instanceof IPackageFragment) {
				result = traverse((IPackageFragment) javaElement, stopOnFirstResult, state);
				if (stopOnFirstResult && result != null)
					return result;
			}
		}
	}
	return result;
}
 
Example 9
Source File: CleanUpAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void collectCompilationUnits(IPackageFragmentRoot root, Collection<IJavaElement> result) throws JavaModelException {
	if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
		IJavaElement[] children= root.getChildren();
		for (int i= 0; i < children.length; i++) {
			collectCompilationUnits((IPackageFragment)children[i], result);
		}
	}
}
 
Example 10
Source File: CheckProjectHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks that the Java file for the given class name exists in the project.
 *
 * @param project
 *          the project, must not be {@code null}
 * @param className
 *          the class name, must not be {@code null}
 * @return whether the corresponding java file exists in the project
 */
public boolean isJavaFilePresent(final IProject project, final String className) {
  int packageSplitIndex = className.lastIndexOf('.');
  if (packageSplitIndex == -1) {
    throw new IllegalArgumentException(String.format("%s is a simple class name or not a class name at all.", className));
  }
  int fileNameEndIndex = className.indexOf('$');
  if (fileNameEndIndex == -1) {
    fileNameEndIndex = className.length();
  }
  String packageName = className.substring(0, packageSplitIndex);
  String fileName = className.substring(packageSplitIndex + 1, fileNameEndIndex) + ".java";
  try {
    if (project.hasNature(JavaCore.NATURE_ID)) {
      for (IPackageFragmentRoot root : JavaCore.create(project).getAllPackageFragmentRoots()) {
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
          for (IJavaElement element : root.getChildren()) {
            if (element instanceof IPackageFragment && packageName.equals(element.getElementName())
                && ((IPackageFragment) element).getCompilationUnit(fileName).exists()) {
              return true;
            }
          }
        }
      }
    }
  } catch (CoreException e) {
    LOGGER.error(String.format("Failed to read project %s.", project.getName()), e);
  }
  return false;
}
 
Example 11
Source File: BuilderUtils.java    From JReFrameworker with MIT License 5 votes vote down vote up
/**
 * Returns a collection of K_SOURCE Compilation units in the project's package fragments
 * Reference: https://www.eclipse.org/forums/index.php/t/68072/
 * @param javaproject
 * @return
 */
public static final ICompilationUnit[] getSourceCompilationUnits(IJavaProject jProject) {
	ArrayList<ICompilationUnit> sourceCompilationUnits = new ArrayList<ICompilationUnit>();
	try {
		IPackageFragmentRoot[] roots = jProject.getPackageFragmentRoots();
		for (int i = 0; i < roots.length; i++) {
			IPackageFragmentRoot root = roots[i];
			if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
				IJavaElement[] javaElements = root.getChildren();
				for (int j = 0; j < javaElements.length; j++) {
					IJavaElement javaElement = javaElements[j];
					if (javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
						IPackageFragment pf = (IPackageFragment) javaElement;
						ICompilationUnit[] compilationUnits = pf.getCompilationUnits();
						for (int k = 0; k < compilationUnits.length; k++) {
							ICompilationUnit unit = compilationUnits[k];
							if (unit.isStructureKnown()) {
								sourceCompilationUnits.add(unit);
							}
						}
					}
				}
			}
		}
	} catch (CoreException e) {
		e.printStackTrace();
	}
	ICompilationUnit[] sourceCompilationUnitsArray = new ICompilationUnit[sourceCompilationUnits.size()];
	sourceCompilationUnits.toArray(sourceCompilationUnitsArray);
	return sourceCompilationUnitsArray;
}
 
Example 12
Source File: SystemObject.java    From JDeodorant with MIT License 5 votes vote down vote up
public Set<ClassObject> getClassObjects(IPackageFragmentRoot packageFragmentRoot) {
  	Set<ClassObject> classObjectSet = new LinkedHashSet<ClassObject>();
  	try {
  		IJavaElement[] children = packageFragmentRoot.getChildren();
  		for(IJavaElement child : children) {
  			if(child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
  				IPackageFragment packageFragment = (IPackageFragment)child;
  				classObjectSet.addAll(getClassObjects(packageFragment));
  			}
  		}
  	} catch(JavaModelException e) {
	e.printStackTrace();
}
  	return classObjectSet;
  }
 
Example 13
Source File: OrganizeImportsCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void collectCompilationUnits(IPackageFragmentRoot root, Collection<IJavaElement> result, String prefix) throws JavaModelException {
	if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
		IJavaElement[] children = root.getChildren();
		for (int i = 0; i < children.length; i++) {
			IPackageFragment pack = (IPackageFragment) children[i];
			if (StringUtils.isBlank(prefix) || pack.getElementName().indexOf(prefix) >= 0) {
				collectCompilationUnits(pack, result);
			}
		}
	}
}
 
Example 14
Source File: RenameModifications.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IPackageFragment[] getSubpackages(IPackageFragment pack) throws CoreException {
	IPackageFragmentRoot root= (IPackageFragmentRoot) pack.getParent();
	IJavaElement[] allPackages= root.getChildren();
	if (pack.isDefaultPackage())
		return new IPackageFragment[0];
	ArrayList<IPackageFragment> result= new ArrayList<IPackageFragment>();
	String prefix= pack.getElementName() + '.';
	for (int i= 0; i < allPackages.length; i++) {
		IPackageFragment currentPackage= (IPackageFragment) allPackages[i];
		if (currentPackage.getElementName().startsWith(prefix))
			result.add(currentPackage);
	}
	return result.toArray(new IPackageFragment[result.size()]);
}
 
Example 15
Source File: ASTReader.java    From JDeodorant with MIT License 5 votes vote down vote up
public ASTReader(IJavaProject iJavaProject, IProgressMonitor monitor) throws CompilationErrorDetectedException {
	List<IMarker> markers = buildProject(iJavaProject, monitor);
	if(!markers.isEmpty()) {
		throw new CompilationErrorDetectedException(markers);
	}
	if(monitor != null)
		monitor.beginTask("Parsing selected Java Project", getNumberOfCompilationUnits(iJavaProject));
	systemObject = new SystemObject();
	examinedProject = iJavaProject;
	try {
		IPackageFragmentRoot[] iPackageFragmentRoots = iJavaProject.getPackageFragmentRoots();
		for(IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
			IJavaElement[] children = iPackageFragmentRoot.getChildren();
			for(IJavaElement child : children) {
				if(child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
					IPackageFragment iPackageFragment = (IPackageFragment)child;
					ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
					for(ICompilationUnit iCompilationUnit : iCompilationUnits) {
						if(monitor != null && monitor.isCanceled())
			    			throw new OperationCanceledException();
						systemObject.addClasses(parseAST(iCompilationUnit));
						if(monitor != null)
							monitor.worked(1);
					}
				}
			}
		}
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	if(monitor != null)
		monitor.done();
}
 
Example 16
Source File: PackageBrowseAdapter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
static void getValidPackages(IPackageFragmentRoot root, List<IPackageFragment> result, HashMap<String, Object> entered, String elementNameMatch) throws JavaModelException {
	IJavaElement[] children= null;
	try {
		children= root.getChildren();
	} catch (JavaModelException e){
		return;
	}
	for (int i= 0; i < children.length; i++){
           if (children[i] instanceof IPackageFragment) {
               IPackageFragment packageFragment = (IPackageFragment)children[i];
               String packageName = packageFragment.getElementName();

               if ((entered != null) && (entered.containsKey(packageName)) == true) {
                   continue;
               }

		    if (canAddPackage(packageFragment)) {
		        if ((elementNameMatch == null) || (elementNameMatch.equals(packageName))) {
		            result.add(packageFragment);
		            if (entered != null) {
		                entered.put(packageName, null);
		            }
		        }
		    }
           }
	}
}
 
Example 17
Source File: PackageSelectionStringButtonAdapter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void changeControlPressed(DialogField field) {
	IPackageFragmentRoot root= fPackageSelectionField.getSelectedFragmentRoot();

	IJavaElement[] packages= null;
	try {
		if (root != null && root.exists()) {
			packages= root.getChildren();
		}
	} catch (JavaModelException e) {
		// no need to react
	}

	if (packages == null) {
		packages= new IJavaElement[0];
	}

	ElementListSelectionDialog dialog= new ElementListSelectionDialog(field.getLabelControl(null).getShell(),
		new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
	dialog.setIgnoreCase(true);

	dialog.setTitle(fTitle);
	dialog.setMessage(fMessage);
	dialog.setEmptyListMessage(fEmtpyListMessage);
	dialog.setElements(packages);

	// TODO initial selection
	//    List selection = new ArrayList();
	//    selection.add(fPackageSelectionField.fPackageSelection.getPackageFragment());
	//    dialog.setInitialElementSelections(selection);

	if (dialog.open() == Window.OK) {
		IPackageFragment fragment= (IPackageFragment)dialog.getFirstResult();
		fPackageSelectionField.setSelected(fragment);
	}
}
 
Example 18
Source File: JavaWorkingSetPageContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Object[] getPackageFragmentRootContent(IPackageFragmentRoot root) throws JavaModelException {
	if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
		// Don't show IJarEntryResource
		return root.getChildren();
	}

	return super.getPackageFragmentRootContent(root);
}
 
Example 19
Source File: JavadocProjectContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Object[] getPackageFragments(IPackageFragmentRoot root) throws JavaModelException {
	ArrayList<IJavaElement> packageFragments= new ArrayList<IJavaElement>();

	IJavaElement[] children= root.getChildren();
	for (int i= 0; i < children.length; i++) {
		if (((IPackageFragment) children[i]).containsJavaResources())
			packageFragments.add(children[i]);
	}
	return packageFragments.toArray();
}
 
Example 20
Source File: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the necessary source code for the refactoring.
 *
 * @param monitor
 *            the progress monitor to use
 * @return
 *            the resulting status
 */
private RefactoringStatus createNecessarySourceCode(final IProgressMonitor monitor) {
	final RefactoringStatus status= new RefactoringStatus();
	try {
		monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 240);
		final IPackageFragmentRoot root= getPackageFragmentRoot();
		if (root != null && fSourceFolder != null && fJavaProject != null) {
			try {
				final SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 40, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
				final IJavaElement[] elements= root.getChildren();
				final List<IPackageFragment> list= new ArrayList<IPackageFragment>(elements.length);
				try {
					subMonitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, elements.length);
					for (int index= 0; index < elements.length; index++) {
						final IJavaElement element= elements[index];
						if (!fProcessedFragments.contains(element) && !element.getElementName().equals(META_INF_FRAGMENT))
							list.add((IPackageFragment) element);
						subMonitor.worked(1);
					}
				} finally {
					subMonitor.done();
				}
				if (!list.isEmpty()) {
					fProcessedFragments.addAll(list);
					final URI uri= fSourceFolder.getRawLocationURI();
					if (uri != null) {
						final IPackageFragmentRoot sourceFolder= fJavaProject.getPackageFragmentRoot(fSourceFolder);
						IWorkspaceRunnable runnable= null;
						if (canUseSourceAttachment()) {
							runnable= new SourceCreationOperation(uri, list) {

								private IPackageFragment fFragment= null;

								@Override
								protected final void createCompilationUnit(final IFileStore store, final String name, final String content, final IProgressMonitor pm) throws CoreException {
									fFragment.createCompilationUnit(name, content, true, pm);
								}

								@Override
								protected final void createPackageFragment(final IFileStore store, final String name, final IProgressMonitor pm) throws CoreException {
									fFragment= sourceFolder.createPackageFragment(name, true, pm);
								}
							};
						} else {
							runnable= new StubCreationOperation(uri, list, true) {

								private IPackageFragment fFragment= null;

								@Override
								protected final void createCompilationUnit(final IFileStore store, final String name, final String content, final IProgressMonitor pm) throws CoreException {
									fFragment.createCompilationUnit(name, content, true, pm);
								}

								@Override
								protected final void createPackageFragment(final IFileStore store, final String name, final IProgressMonitor pm) throws CoreException {
									fFragment= sourceFolder.createPackageFragment(name, true, pm);
								}
							};
						}
						try {
							runnable.run(new SubProgressMonitor(monitor, 150, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
						} finally {
							fSourceFolder.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 50, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
						}
					}
				}
			} catch (CoreException exception) {
				status.addFatalError(exception.getLocalizedMessage());
			}
		}
	} finally {
		monitor.done();
	}
	return status;
}