Example usage for org.eclipse.jdt.core IJavaProject getAllPackageFragmentRoots

List of usage examples for org.eclipse.jdt.core IJavaProject getAllPackageFragmentRoots

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject getAllPackageFragmentRoots.

Prototype

IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException;

Source Link

Document

Returns all of the existing package fragment roots that exist on the classpath, in the order they are defined by the classpath.

Usage

From source file:org.limy.eclipse.qalab.propertypage.PackageSelector.java

License:Open Source License

/**
 * v?WFNgt@CI?B/*from  w w  w .  j  av  a  2  s.c om*/
 * @throws JavaModelException 
 */
private void setFromProject() throws JavaModelException {

    ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(new Shell(),
            new WorkbenchLabelProvider(), new WorkbenchContentProvider());

    dialog.setTitle("Package Selection");
    dialog.setMessage("Package I?B");
    ViewerFilter filter = new ViewerFilter() {
        @Override
        public boolean select(Viewer viewer, Object parentElement, Object element) {
            if (element instanceof ICompilationUnit) {
                return false;
            }
            return true;
        }
    };
    dialog.addFilter(filter);

    Collection<IPackageFragment> targetElements = new ArrayList<IPackageFragment>();
    for (IProject project : projects) {
        IJavaProject javaProject = JavaCore.create(project);
        for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
            if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                // jarpbP?[W?O
                IJavaElement[] children = root.getChildren();
                for (IJavaElement child : children) {
                    targetElements.add((IPackageFragment) child);
                }
            }
        }
    }

    dialog.setInput(new AdaptableList(targetElements));

    if (dialog.open() == Dialog.OK) {

        Object[] results = dialog.getResult();
        for (Object result : results) {
            IPackageFragment fragment = (IPackageFragment) result;
            control.add(fragment.getElementName());
            if (listener != null) {
                PropertyChangeEvent evt = new PropertyChangeEvent(control, "resultPath", null,
                        fragment.getPath());
                listener.propertyChange(evt);
            }
        }
    }
}

From source file:org.limy.eclipse.qalab.propertypage.SourceDirSelector.java

License:Open Source License

/**
 * pbP?[WfBNgI???s?B/*  w ww  .jav  a 2 s .c o  m*/
 * @throws JavaModelException 
 */
private void setPackageDir() throws JavaModelException {

    ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(new Shell(),
            new WorkbenchLabelProvider(), new WorkbenchContentProvider());

    dialog.setTitle(Messages.TITLE_SELECT_SOURCE_DIR);
    dialog.setMessage(Messages.MES_SELECT_SOURCE_DIR);
    ViewerFilter filter = new ViewerFilter() {
        @Override
        public boolean select(Viewer viewer, Object parentElement, Object element) {
            if (element instanceof IPackageFragmentRoot) {
                return true;
            }
            return false;
        }
    };
    dialog.addFilter(filter);

    Collection<IPackageFragmentRoot> targetElements = new ArrayList<IPackageFragmentRoot>();
    for (IProject project : projects) {
        IJavaProject javaProject = JavaCore.create(project);
        for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) {
            if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                // jarpbP?[W?O
                targetElements.add(root);
            }
        }
    }

    dialog.setInput(new AdaptableList(targetElements));

    if (dialog.open() == Dialog.OK) {

        Object[] results = dialog.getResult();
        for (Object result : results) {
            IPackageFragmentRoot fragment = (IPackageFragmentRoot) result;
            control.add(fragment.getElementName());
            if (listener != null) {
                PropertyChangeEvent evt = new PropertyChangeEvent(control, "resultPath", null,
                        fragment.getPath());
                listener.propertyChange(evt);
            }
        }
    }
}

From source file:org.neuro4j.studio.core.views.dialogs.FilteredItemsSelectionDialog.java

License:Apache License

protected static List<String> getSourceDirectories(IProject project) {
    if (project == null)
        return null;

    List<String> ret = projectSources.get(project);

    if (ret != null) {
        return ret;
    } else {//from  w w  w . j  a v a  2s  . co  m
        ret = new ArrayList<String>();
    }

    IJavaProject javaProject = JavaCore.create(project);
    try {
        IPackageFragmentRoot[] packageFragmentRoot = javaProject.getAllPackageFragmentRoots();
        for (int i = 0; i < packageFragmentRoot.length; i++) {
            if (packageFragmentRoot[i].getKind() == IPackageFragmentRoot.K_SOURCE
                    && !packageFragmentRoot[i].isArchive())
                ret.add(packageFragmentRoot[i].getPath().toPortableString() + "/");
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
        return Collections.EMPTY_LIST;
    }
    projectSources.put(project, ret);
    return ret;
}

From source file:org.sculptor.dsl.ui.resource.MavenClasspathUriResolver.java

License:Apache License

/**
 * Before forwarding to//from  w  w w. j  ava 2 s.  com
 * {@link JdtClasspathUriResolver#findResourceInWorkspace(IJavaProject, URI)}
 * this methods uses {@link #isMavenResourceDirectory(IPackageFragment)} to
 * check if the given classpath URI references a resource in an excluded
 * Maven resource directory.
 */
@Override
protected URI findResourceInWorkspace(IJavaProject javaProject, URI classpathUri) throws CoreException {
    if (javaProject.exists()) {
        String packagePath = classpathUri.trimSegments(1).path();
        String fileName = classpathUri.lastSegment();
        IPath filePath = new Path(fileName);
        String packageName = isEmpty(packagePath) ? "" : packagePath.substring(1).replace('/', '.');
        for (IPackageFragmentRoot packageFragmentRoot : javaProject.getAllPackageFragmentRoots()) {
            IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment(packageName);
            if (isMavenResourceDirectory(packageFragment)) {
                IResource packageFragmentResource = packageFragment.getResource();
                if (packageFragmentResource instanceof IContainer) {
                    IFile file = ((IContainer) packageFragmentResource).getFile(filePath);
                    if (file.exists()) {
                        return createPlatformResourceURI(file);
                    }
                }
            }
        }
    }
    return super.findResourceInWorkspace(javaProject, classpathUri);
}

From source file:org.seasar.doma.extension.domax.util.JavaProjectUtil.java

License:Apache License

public static List<IResource> getSourceFolders(IJavaProject javaProject) {
    List<IResource> results = new ArrayList<IResource>();
    try {/*from  ww w. j a  v a 2  s . c  o m*/
        IPackageFragmentRoot[] roots = javaProject.getAllPackageFragmentRoots();
        for (IPackageFragmentRoot root : roots) {
            if (root.getJavaProject() == javaProject && root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                results.add(root.getCorrespondingResource());
            }
        }
    } catch (JavaModelException e) {
        Logger.error(e);
    }
    return results;
}

From source file:org.seasar.kijimuna.core.search.JavaPackageSearcher.java

License:Apache License

public void searchPackagesAndTypes(String prefix, IPackageRequestor requestor) {
    int lastDot = prefix.lastIndexOf('.');
    String packageName;//w ww .  ja va 2 s . com
    String trimedPrefix = "";
    if (lastDot > 0) {
        packageName = prefix.substring(0, lastDot);
        trimedPrefix = prefix.substring(lastDot + 1);
    } else if (lastDot == -1) {
        packageName = prefix;
    } else {
        return;
    }
    IJavaProject javaProject = JavaCore.create(project);
    try {
        IPackageFragmentRoot[] roots = javaProject.getAllPackageFragmentRoots();

        // search packages and types
        for (int i = 0; i < roots.length; i++) {
            IJavaElement[] elements = roots[i].getChildren();
            for (int k = 0; k < elements.length; k++) {
                if (elements[k] instanceof IPackageFragment) {
                    IPackageFragment pack = (IPackageFragment) elements[k];
                    String currentName = pack.getElementName();
                    if (StringUtils.existValue(currentName)
                            && currentName.toLowerCase().startsWith(prefix.toLowerCase())) {
                        requestor.acceptPackage(pack, roots[i].isArchive());
                    } else if (currentName.equals(packageName)) {
                        if (roots[i].isArchive()) {
                            handleClassFiles(pack, requestor, trimedPrefix);
                        } else {
                            handleCompilationUnits(pack, requestor, trimedPrefix);
                        }
                    }
                }
            }
        }

        // search inner type
        if (lastDot > 0) {
            int lastDollar = prefix.lastIndexOf('$');
            String typeName;
            if (lastDollar > lastDot) {
                typeName = prefix.substring(0, lastDollar);
            } else {
                typeName = packageName;
            }
            IType type = javaProject.findType(typeName);
            if (type != null && Flags.isPublic(type.getFlags())) {
                IJavaElement[] children = type.getChildren();
                for (int i = 0; i < children.length; i++) {
                    if (children[i] instanceof IType) {
                        IType innerType = (IType) children[i];
                        int flag = innerType.getFlags();
                        if (Flags.isPublic(flag)) {
                            requestor.acceptType(innerType);
                        }
                    }
                }
            }
        }

        // direct search types
        if (lastDot == -1 && prefix.length() > 0) {
            IPackageFragmentRoot[] pkgs = javaProject.getAllPackageFragmentRoots();
            char[][] typeNames = { prefix.toCharArray() };

            final ArrayList res = new ArrayList();
            TypeNameRequestor typeNameRequestor = new TypeNameRequestor() {

                public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                        char[][] enclosingTypeNames, String path) {

                    if (enclosingTypeNames.length == 0 && Flags.isPublic(modifiers)) {
                        StringBuffer fqcn = new StringBuffer();
                        if (packageName.length > 0) {
                            fqcn.append(packageName).append(".");
                        }
                        fqcn.append(simpleTypeName);
                        res.add(fqcn.toString());
                    }
                }
            };
            // TODO:3.2??????,deprecated??
            new SearchEngine().searchAllTypeNames(null, prefix.toCharArray(), SearchPattern.R_PREFIX_MATCH,
                    IJavaSearchConstants.CLASS, SearchEngine.createJavaSearchScope(pkgs), typeNameRequestor,
                    IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);

            for (Iterator iterator = res.iterator(); iterator.hasNext();) {
                String fqcn = (String) iterator.next();
                IType type = javaProject.findType(fqcn);
                requestor.acceptType(type);
            }
        }
    } catch (JavaModelException e) {
        KijimunaCore.reportException(e);
    }
}

From source file:org.seasar.kijimuna.core.util.ProjectUtils.java

License:Apache License

public static IStorage findDiconStorage(IProject proj, String fullPath) {
    IPath path = getQualifiedDiconPath(fullPath);
    String pack = path.removeLastSegments(1).toString();
    pack = pack.replace('/', '.');
    if (pack.startsWith(".")) {
        pack = pack.substring(1);//  www  .j  a v a 2 s. c om
    }
    if (pack.endsWith(".")) {
        pack = pack.substring(0, pack.length() - 1);
    }
    String name = path.lastSegment();
    try {
        IJavaProject project = ProjectUtils.getJavaProject(proj);

        IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
        for (int i = 0; i < roots.length; i++) {
            if (pack.length() == 0) {
                Object[] os = roots[i].getNonJavaResources();
                for (int j = 0; j < os.length; j++) {
                    if (os[j] instanceof IStorage) {
                        IStorage storage = (IStorage) os[j];
                        if (name.equals(storage.getName())) {
                            return storage;
                        }
                    }
                }
            }
            IPackageFragment frag = roots[i].getPackageFragment(pack);
            if (frag.exists()) {
                if (frag.isDefaultPackage()) {
                    IPath testPath = roots[i].getPath().append(name);
                    // remove project name segment from path.
                    testPath = testPath.removeFirstSegments(1);
                    IFile dicon = proj.getFile(testPath);
                    if (dicon.exists()) {
                        return dicon;
                    }
                } else {
                    Object[] resources = frag.getNonJavaResources();
                    for (int k = 0; k < resources.length; k++) {
                        if (resources[k] instanceof IStorage) {
                            IStorage dicon = (IStorage) resources[k];
                            if (name.equals(dicon.getName())) {
                                return dicon;
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        // -> getAllPackageFragmentRoots()
        // when non java project
        IFile dicon = proj.getFile(getQualifiedDiconPath(fullPath));
        if (dicon.exists()) {
            return dicon;
        }
    }
    return null;
}

From source file:org.springframework.ide.eclipse.beans.ui.editor.util.BeansJavaCompletionUtils.java

License:Open Source License

private static IPackageFragment getPackageFragment(IJavaProject project, String prefix)
        throws JavaModelException {
    int dot = prefix.lastIndexOf('.');
    if (dot > -1) {
        String packageName = prefix.substring(0, dot);
        for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
            IPackageFragment p = root.getPackageFragment(packageName);
            if (p != null && p.exists()) {
                return p;
            }// www  . j av  a 2  s  . co  m
        }
        IPackageFragment[] packages = project.getPackageFragments();
        for (IPackageFragment p : packages) {
            if (p.getElementName().equals(packageName))
                return p;
        }
    } else {
        for (IPackageFragmentRoot p : project.getAllPackageFragmentRoots()) {
            if (p.getKind() == IPackageFragmentRoot.K_SOURCE) {
                return p.getPackageFragment("");
            }
        }
    }
    return project.getPackageFragments()[0];
}

From source file:org.springframework.ide.eclipse.quickfix.proposals.CreateNewClassQuickFixProposal.java

License:Open Source License

public CreateNewClassQuickFixProposal(int offset, int length, String text, boolean missingEndQuote,
        IJavaProject javaProject, Set<String> properties, int numConstructorArgs, boolean allowUserChanges) {
    super(offset, length, missingEndQuote);
    this.properties = properties;
    this.numConstructorArgs = numConstructorArgs;
    this.javaProject = javaProject;
    this.allowUserChanges = allowUserChanges;

    int classNameOffset = text.lastIndexOf("$");
    int packageEnd;

    if (classNameOffset >= 0) {
        String enclosingClassName = text.substring(0, classNameOffset);
        enclosingType = JdtUtils.getJavaType(javaProject.getProject(), enclosingClassName);

        packageEnd = enclosingClassName.lastIndexOf(".");
    } else {//  w  w w .  ja  va  2s. co  m
        classNameOffset = text.lastIndexOf(".");
        packageEnd = classNameOffset;
    }

    if (classNameOffset < 0) {
        className = text;
    } else {
        className = text.substring(classNameOffset + 1);
    }

    if (packageEnd >= 0) {
        packageName = text.substring(0, packageEnd);
    } else {
        packageName = "";
    }

    String packageFragmentName = null;
    if (enclosingType != null) {
        packageFragmentName = enclosingType.getPackageFragment().getElementName();
    }

    IPackageFragmentRoot[] allPackageFragmentRoots;
    try {
        allPackageFragmentRoots = javaProject.getAllPackageFragmentRoots();
        if (allPackageFragmentRoots != null && allPackageFragmentRoots.length > 0) {
            for (IPackageFragmentRoot packageFragmentRoot : allPackageFragmentRoots) {
                if (!(packageFragmentRoot instanceof JarPackageFragmentRoot)) {
                    if (packageFragmentName != null) {
                        if (packageFragmentRoot.getPackageFragment(packageFragmentName) == null) {
                            continue;
                        }
                    }
                    sourceRoot = packageFragmentRoot;
                    break;
                }
            }
        }
    } catch (JavaModelException e) {
    }

}

From source file:org.springframework.ide.eclipse.wizard.ui.BeanWizardPage.java

License:Open Source License

private void createAttribute(String attributeName, Hyperlink link, Text text) {
    link.setText(getDisplayText(attributeName) + ":"); //$NON-NLS-1$
    link.setUnderlined(true);/*w  ww  . jav a  2  s .co m*/
    link.setLayoutData(new GridData());

    link.addHyperlinkListener(new HyperlinkAdapter() {
        @Override
        public void linkActivated(HyperlinkEvent e) {
            IProject project = BeanWizardPage.this.wizard.getBeanFile().getProject();
            String className = classText.getText();

            try {
                if (project.hasNature(JavaCore.NATURE_ID)) {
                    IJavaProject javaProject = JavaCore.create(project);
                    IJavaElement result = null;
                    if (className.length() > 0) {
                        result = javaProject.findType(className);
                    }

                    if (result != null) {
                        JavaUI.openInEditor(result);
                        return;
                    }

                    NewClassWizardPage page = new NewClassWizardPage();

                    int index = className.lastIndexOf(".");
                    if (index > 0) {
                        String packageName = className.substring(0, index);
                        className = className.substring(index + 1);

                        IPackageFragment[] packageFragments = javaProject.getPackageFragments();
                        for (IPackageFragment packageFragment : packageFragments) {
                            if (packageFragment.getElementName().equals(packageName)) {
                                page.setPackageFragment(packageFragment, true);

                                IPackageFragmentRoot[] packageFragmentRoots = javaProject
                                        .getAllPackageFragmentRoots();
                                for (IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) {
                                    if (packageFragmentRoot.getPath().isPrefixOf(packageFragment.getPath())) {
                                        page.setPackageFragmentRoot(packageFragmentRoot, true);
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                    }

                    page.setTypeName(className, false);

                    NewClassCreationWizard wizard = new NewClassCreationWizard(page, true);
                    IWorkbench workbench = PlatformUI.getWorkbench();
                    wizard.init(workbench, null);

                    Shell shell = workbench.getActiveWorkbenchWindow().getShell();
                    WizardDialog dialog = new WizardDialog(shell, wizard);
                    dialog.create();
                    dialog.getShell().setText("New Class");

                    dialog.setBlockOnOpen(true);
                    if (dialog.open() == Window.OK) {
                        validateAttribute(BeansSchemaConstants.ATTR_CLASS, className);
                    }

                }
            } catch (CoreException ex) {

            }

        }
    });

    createAttrbute(attributeName, text);
}