Example usage for org.eclipse.jdt.core IPackageFragmentRoot K_SOURCE

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot K_SOURCE

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot K_SOURCE.

Prototype

int K_SOURCE

To view the source code for org.eclipse.jdt.core IPackageFragmentRoot K_SOURCE.

Click Source Link

Document

Kind constant for a source path root.

Usage

From source file:org.eclipse.gmf.tests.JDTUtil.java

License:Open Source License

private void collectProblems(IJavaElement jElement, IMemberProcessor[] processors) {
    try {// w  w  w . j a va 2  s  .c o m
        switch (jElement.getElementType()) {
        case IJavaElement.JAVA_PROJECT: {
            IJavaProject jProject = (IJavaProject) jElement;
            IPackageFragmentRoot[] roots = jProject.getPackageFragmentRoots();
            for (int i = 0; i < roots.length; i++) {
                if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                    collectProblems(roots[i], processors);
                }
            }
        }
            break;
        case IJavaElement.PACKAGE_FRAGMENT_ROOT: {
            IPackageFragmentRoot root = (IPackageFragmentRoot) jElement;
            IJavaElement[] children = root.getChildren();
            for (int i = 0; i < children.length; i++) {
                collectProblems(children[i], processors);
            }
        }
            break;
        case IJavaElement.PACKAGE_FRAGMENT: {
            IPackageFragment pf = (IPackageFragment) jElement;
            ICompilationUnit[] compilationUnits = pf.getCompilationUnits();
            for (int i = 0; i < compilationUnits.length; i++) {
                collectProblems(compilationUnits[i], processors);
            }
        }
            break;
        case IJavaElement.COMPILATION_UNIT: {
            ICompilationUnit compilationUnit = (ICompilationUnit) jElement;
            IType[] types = compilationUnit.getTypes();
            for (int i = 0; i < types.length; i++) {
                collectProblems(types[i], processors);
            }
        }
            break;
        case IJavaElement.TYPE: {
            IMember member = (IMember) jElement;
            collectProblems(member, processors, false);
        }
            break;
        }
    } catch (JavaModelException e) {
        myAggregator.add(e.getStatus());
    }
}

From source file:org.eclipse.gmt.mod.infra.common.core.internal.utils.FileUtils.java

License:Open Source License

/**
 * Whether the given workspace file is in its project's output location
 * (e.g. "bin" directory)/*from www .  j  a  va  2s . c  o  m*/
 */
public static boolean isInOutputLocation(final IFile file) {
    try {
        IJavaProject javaProject = JavaCore.create(file.getProject());
        if (javaProject != null) {
            if (javaProject.getOutputLocation().isPrefixOf(file.getFullPath())) {
                return true;
            }
            IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
            for (IClasspathEntry classpathEntry : rawClasspath) {
                if (classpathEntry.getContentKind() == IPackageFragmentRoot.K_SOURCE) {
                    IPath outputLocation = classpathEntry.getOutputLocation();
                    if (outputLocation != null && outputLocation.isPrefixOf(file.getFullPath())) {
                        return true;
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        log.error(e.toString()); //FP
    }
    return false;
}

From source file:org.eclipse.jdt.internal.core.CompilationUnit.java

License:Open Source License

protected IStatus validateCompilationUnit(IResource resource) {
    IPackageFragmentRoot root = getPackageFragmentRoot();
    // root never null as validation is not done for working copies
    try {/*  w w w.j av  a  2 s . c  o  m*/
        if (root.getKind() != IPackageFragmentRoot.K_SOURCE)
            return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, root);
    } catch (JavaModelException e) {
        return e.getJavaModelStatus();
    }
    if (resource != null) {
        char[][] inclusionPatterns = ((PackageFragmentRoot) root).fullInclusionPatternChars();
        char[][] exclusionPatterns = ((PackageFragmentRoot) root).fullExclusionPatternChars();
        if (Util.isExcluded(resource, inclusionPatterns, exclusionPatterns))
            return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this);
        if (!resource.isAccessible())
            return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this);
    }
    IJavaProject project = getJavaProject();
    return JavaConventions.validateCompilationUnitName(getElementName(),
            project.getOption(JavaCore.COMPILER_SOURCE, true),
            project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
}

From source file:org.eclipse.jdt.internal.core.JavaModelManager.java

License:Open Source License

private Map secondaryTypesSearching(IJavaProject project, boolean waitForIndexes, IProgressMonitor monitor,
        final PerProjectInfo projectInfo) throws JavaModelException {
    if (VERBOSE || BasicSearchEngine.VERBOSE) {
        StringBuffer buffer = new StringBuffer("JavaModelManager.secondaryTypesSearch("); //$NON-NLS-1$
        buffer.append(project.getElementName());
        buffer.append(',');
        buffer.append(waitForIndexes);//from   www  .j av a2s.  c  om
        buffer.append(')');
        Util.verbose(buffer.toString());
    }

    final Hashtable secondaryTypes = new Hashtable(3);
    IRestrictedAccessTypeRequestor nameRequestor = new IRestrictedAccessTypeRequestor() {
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                char[][] enclosingTypeNames, String path, AccessRestriction access) {
            String key = packageName == null ? "" : new String(packageName); //$NON-NLS-1$
            HashMap types = (HashMap) secondaryTypes.get(key);
            if (types == null)
                types = new HashMap(3);
            types.put(new String(simpleTypeName), path);
            secondaryTypes.put(key, types);
        }
    };

    // Build scope using prereq projects but only source folders
    IPackageFragmentRoot[] allRoots = project.getAllPackageFragmentRoots();
    int length = allRoots.length, size = 0;
    IPackageFragmentRoot[] allSourceFolders = new IPackageFragmentRoot[length];
    for (int i = 0; i < length; i++) {
        if (allRoots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
            allSourceFolders[size++] = allRoots[i];
        }
    }
    if (size < length) {
        System.arraycopy(allSourceFolders, 0, allSourceFolders = new IPackageFragmentRoot[size], 0, size);
    }

    // Search all secondary types on scope
    new BasicSearchEngine().searchAllSecondaryTypeNames(allSourceFolders, nameRequestor, waitForIndexes,
            monitor);

    // Build types from paths
    Iterator packages = secondaryTypes.values().iterator();
    while (packages.hasNext()) {
        HashMap types = (HashMap) packages.next();
        Iterator names = types.entrySet().iterator();
        while (names.hasNext()) {
            Map.Entry entry = (Map.Entry) names.next();
            String typeName = (String) entry.getKey();
            String path = (String) entry.getValue();
            if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(path)) {
                IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path));
                ICompilationUnit unit = JavaModelManager.createCompilationUnitFrom(file, null);
                IType type = unit.getType(typeName);
                types.put(typeName, type); // replace stored path with type itself
            } else {
                names.remove();
            }
        }
    }

    // Store result in per project info cache if still null or there's still an indexing cache (may have been set by another thread...)
    if (projectInfo.secondaryTypes == null || projectInfo.secondaryTypes.get(INDEXED_SECONDARY_TYPES) != null) {
        projectInfo.secondaryTypes = secondaryTypes;
        if (VERBOSE || BasicSearchEngine.VERBOSE) {
            System.out.print(Thread.currentThread() + "   -> secondary paths stored in cache: "); //$NON-NLS-1$
            System.out.println();
            Iterator entries = secondaryTypes.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                String qualifiedName = (String) entry.getKey();
                Util.verbose("      - " + qualifiedName + '-' + entry.getValue()); //$NON-NLS-1$
            }
        }
    }
    return projectInfo.secondaryTypes;
}

From source file:org.eclipse.jdt.internal.core.PackageFragment.java

License:Open Source License

/**
 * @see Openable//from w w w . j  av a2s .  co  m
 */
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements,
        IResource underlyingResource) throws JavaModelException {
    // add compilation units/class files from resources
    HashSet vChildren = new HashSet();
    int kind = getKind();
    try {
        PackageFragmentRoot root = getPackageFragmentRoot();
        char[][] inclusionPatterns = root.fullInclusionPatternChars();
        char[][] exclusionPatterns = root.fullExclusionPatternChars();
        IResource[] members = ((IContainer) underlyingResource).members();
        int length = members.length;
        if (length > 0) {
            IJavaProject project = getJavaProject();
            String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
            String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
            for (int i = 0; i < length; i++) {
                IResource child = members[i];
                if (child.getType() != IResource.FOLDER
                        && !Util.isExcluded(child, inclusionPatterns, exclusionPatterns)) {
                    IJavaElement childElement;
                    if (kind == IPackageFragmentRoot.K_SOURCE
                            && Util.isValidCompilationUnitName(child.getName(), sourceLevel, complianceLevel)) {
                        // GROOVY start
                        /* old {
                        childElement = new CompilationUnit(this, child.getName(), DefaultWorkingCopyOwner.PRIMARY);
                        } new */
                        childElement = LanguageSupportFactory.newCompilationUnit(this, child.getName(),
                                DefaultWorkingCopyOwner.PRIMARY);
                        // GROOVY end

                        vChildren.add(childElement);
                    } else if (kind == IPackageFragmentRoot.K_BINARY
                            && Util.isValidClassFileName(child.getName(), sourceLevel, complianceLevel)) {
                        childElement = getClassFile(child.getName());
                        vChildren.add(childElement);
                    }
                }
            }
        }
    } catch (CoreException e) {
        throw new JavaModelException(e);
    }

    if (kind == IPackageFragmentRoot.K_SOURCE) {
        // add primary compilation units
        ICompilationUnit[] primaryCompilationUnits = getCompilationUnits(DefaultWorkingCopyOwner.PRIMARY);
        for (int i = 0, length = primaryCompilationUnits.length; i < length; i++) {
            ICompilationUnit primary = primaryCompilationUnits[i];
            vChildren.add(primary);
        }
    }

    IJavaElement[] children = new IJavaElement[vChildren.size()];
    vChildren.toArray(children);
    info.setChildren(children);
    return true;
}

From source file:org.eclipse.jdt.internal.core.PackageFragment.java

License:Open Source License

protected IStatus validateExistence(IResource underlyingResource) {
    // check that the name of the package is valid (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=108456)
    if (!isValidPackageName())
        return newDoesNotExistStatus();

    // check whether this pkg can be opened
    if (underlyingResource != null && !resourceExists(underlyingResource))
        return newDoesNotExistStatus();

    // check that it is not excluded (https://bugs.eclipse.org/bugs/show_bug.cgi?id=138577)
    int kind;//from  w w w .j  av a 2  s. c om
    try {
        kind = getKind();
    } catch (JavaModelException e) {
        return e.getStatus();
    }
    if (kind == IPackageFragmentRoot.K_SOURCE && Util.isExcluded(this))
        return newDoesNotExistStatus();

    return JavaModelStatus.VERIFIED_OK;
}

From source file:org.eclipse.jem.workbench.utility.JemProjectUtilities.java

License:Open Source License

/**
 * Get all source package fragment roots.
 * //from  ww w.  j  a  v  a 2s  . c om
 * @param javaProj
 * @return source package fragment roots
 * @throws JavaModelException
 * 
 * @since 1.0.0
 */
public static List getSourcePackageFragmentRoots(IJavaProject javaProj) throws JavaModelException {
    List result = new ArrayList();
    IPackageFragmentRoot[] roots = javaProj.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        IPackageFragmentRoot root = roots[i];
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE)
            result.add(root);
    }
    return result;
}

From source file:org.eclipse.jet.taglib.java.JavaActionsUtil.java

License:Open Source License

/**
 * Find the a container corresponding the the given package in the specified project.
 * Traverse all project source package roots, looking for an existing instance of a package fragment corresponding to packageName.
 * If not found, return the first non-existant fragment found.
 * If the project has no source package roots, then null is returned.
 * @param jProject the Java project to search
 * @param packageName the Java package for which a container is sought.
 * @return the container corresponding to the package, or null.
 * @throws JavaModelException if the package roots or root kinds cannot be determined.
 *///from  w w  w  .  j ava 2s  . com
private static IContainer findOrCreateJavaPackage(IJavaProject jProject, String packageName)
        throws JavaModelException {
    IPackageFragment firstNonExistantFragment = null;
    // Traverse package roots, looking for an existing instance of the package fragment corresponding to packageName.
    // Otherwise, return the first non-existant fragment
    final IPackageFragmentRoot[] roots = jProject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
            IPackageFragment fragment = roots[i].getPackageFragment(packageName);
            if (fragment.exists()) {
                return (IContainer) fragment.getResource();
            } else if (firstNonExistantFragment == null) {
                firstNonExistantFragment = fragment;
            }
        }
    }
    return firstNonExistantFragment != null ? (IContainer) firstNonExistantFragment.getResource() : null;
}

From source file:org.eclipse.jpt.common.core.internal.utility.PackageFragmentRootTools.java

License:Open Source License

private static boolean isSourceFolder_(IPackageFragmentRoot pfr) throws JavaModelException {
    return pfr.exists() && (pfr.getKind() == IPackageFragmentRoot.K_SOURCE);
}

From source file:org.eclipse.jpt.jaxb.ui.internal.wizards.classesgen.ClassesGeneratorWizardPage.java

License:Open Source License

/** 
 * Override to allow selection of source folder in current project only
 * @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#chooseContainer()
 * Only 1 line in this code is different from the parent
 *///w ww.j a v  a2 s .c  o m
@Override
protected IPackageFragmentRoot chooseContainer() {
    Class<?>[] acceptedClasses = new Class[] { IPackageFragmentRoot.class, IJavaProject.class };
    TypedElementSelectionValidator validator = new TypedElementSelectionValidator(acceptedClasses, false) {
        @Override
        public boolean isSelectedValid(Object element) {
            try {
                if (element instanceof IJavaProject) {
                    IJavaProject jproject = (IJavaProject) element;
                    IPath path = jproject.getProject().getFullPath();
                    return (jproject.findPackageFragmentRoot(path) != null);
                } else if (element instanceof IPackageFragmentRoot) {
                    return (((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE);
                }
                return true;
            } catch (JavaModelException e) {
                JptJaxbUiPlugin.instance().logError(e); // just log, no UI in validation
            }
            return false;
        }
    };

    acceptedClasses = new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class };
    ViewerFilter filter = new TypedViewerFilter(acceptedClasses) {
        @Override
        public boolean select(Viewer viewer, Object parent, Object element) {
            if (element instanceof IPackageFragmentRoot) {
                try {
                    return (((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE);
                } catch (JavaModelException e) {
                    JptJaxbUiPlugin.instance().logError(e); // just log, no UI in validation
                    return false;
                }
            }
            return super.select(viewer, parent, element);
        }
    };

    StandardJavaElementContentProvider provider = new StandardJavaElementContentProvider();
    ILabelProvider labelProvider = new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
    dialog.setValidator(validator);
    dialog.setComparator(new JavaElementComparator());
    dialog.setTitle(JptJaxbUiMessages.CLASSES_GENERATOR_WIZARD_PAGE_SOURCE_FOLDER_SELECTION_DIALOG_TITLE);
    dialog.setMessage(JptJaxbUiMessages.CLASSES_GENERATOR_WIZARD_PAGE_CHOOSE_SOURCE_FOLDER_DIALOG_DESC);
    dialog.addFilter(filter);
    //set the java project as the input instead of the workspace like the NewContainerWizardPage was doing
    //******************************************************//
    dialog.setInput(this.getJavaProject()); //
    //******************************************************//
    dialog.setInitialSelection(getPackageFragmentRoot());
    dialog.setHelpAvailable(false);

    if (dialog.open() == Window.OK) {
        Object element = dialog.getFirstResult();
        if (element instanceof IJavaProject) {
            IJavaProject jproject = (IJavaProject) element;
            return jproject.getPackageFragmentRoot(jproject.getProject());
        } else if (element instanceof IPackageFragmentRoot) {
            return (IPackageFragmentRoot) element;
        }
        return null;
    }
    return null;
}