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

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

Introduction

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

Prototype

String getOption(String optionName, boolean inheritJavaCoreOptions);

Source Link

Document

Helper method for returning one option value only.

Usage

From source file:org.eclipse.buildship.core.workspace.internal.JavaSourceSettingsUpdater.java

License:Open Source License

private static boolean updateJavaProjectOptionIfNeeded(IJavaProject project, String optionKey,
        String newValue) {//from  ww w  .  j a v a  2  s  .c o m
    String currentValue = project.getOption(optionKey, true);
    if (currentValue == null || !currentValue.equals(newValue)) {
        project.setOption(optionKey, newValue);
        return true;
    } else {
        return false;
    }
}

From source file:org.eclipse.che.jdt.internal.core.SourceMapper.java

License:Open Source License

private synchronized void computeAllRootPaths(IType type) {
    if (this.areRootPathsComputed) {
        return;//from www  . java 2s .  c  om
    }
    IPackageFragmentRoot root = (IPackageFragmentRoot) type.getPackageFragment().getParent();
    IPath pkgFragmentRootPath = root.getPath();
    final HashSet tempRoots = new HashSet();
    long time = 0;
    if (VERBOSE) {
        System.out.println("compute all root paths for " + root.getElementName()); //$NON-NLS-1$
        time = System.currentTimeMillis();
    }
    final HashSet firstLevelPackageNames = new HashSet();
    boolean containsADefaultPackage = false;
    boolean containsJavaSource = !pkgFragmentRootPath.equals(this.sourcePath); // used to optimize zip file reading only if source path and root path are equals, otherwise
    // assume that attachment contains Java source

    String sourceLevel = null;
    String complianceLevel = null;
    if (root.isArchive()) {
        //         org.eclipse.jdt.internal.core.JavaModelManager manager = org.eclipse.jdt.internal.core.JavaModelManager.getJavaModelManager();
        ZipFile zip = null;
        try {
            zip = manager.getZipFile(pkgFragmentRootPath);
            for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String entryName = entry.getName();
                if (!entry.isDirectory()) {
                    if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entryName)) {
                        int index = entryName.indexOf('/');
                        if (index != -1) {
                            String firstLevelPackageName = entryName.substring(0, index);
                            if (!firstLevelPackageNames.contains(firstLevelPackageName)) {
                                if (sourceLevel == null) {
                                    IJavaProject project = root.getJavaProject();
                                    sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
                                    complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
                                }
                                IStatus status = Status.OK_STATUS;// JavaConventions
                                //                                 .validatePackageName(firstLevelPackageName, sourceLevel, complianceLevel);
                                if (status.isOK() || status.getSeverity() == IStatus.WARNING) {
                                    firstLevelPackageNames.add(firstLevelPackageName);
                                }
                            }
                        } else {
                            containsADefaultPackage = true;
                        }
                    } else if (!containsJavaSource
                            && org.eclipse.che.jdt.internal.core.util.Util.isJavaLikeFileName(entryName)) {
                        containsJavaSource = true;
                    }
                }
            }
        } catch (CoreException e) {
            // ignore
        } finally {
            manager.closeZipFile(zip); // handle null case
        }
    } /*else {
      Object target = JavaModel.getTarget(root.getPath(), true);
      if (target instanceof IResource) {
      IResource resource = (IResource) target;
      if (resource instanceof IContainer) {
         try {
            IResource[] members = ((IContainer) resource).members();
            for (int i = 0, max = members.length; i < max; i++) {
               IResource member = members[i];
               String resourceName = member.getName();
               if (member.getType() == IResource.FOLDER) {
                  if (sourceLevel == null) {
                     IJavaProject project = root.getJavaProject();
                     sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
                     complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
                  }
                  IStatus status = JavaConventions.validatePackageName(resourceName, sourceLevel, complianceLevel);
                  if (status.isOK() || status.getSeverity() == IStatus.WARNING) {
                     firstLevelPackageNames.add(resourceName);
                  }
               } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resourceName)) {
                  containsADefaultPackage = true;
               } else if (!containsJavaSource && Util.isJavaLikeFileName(resourceName)) {
                  containsJavaSource = true;
               }
            }
         } catch (CoreException e) {
            // ignore
         }
      }
      }
      }*/

    if (containsJavaSource) { // no need to read source attachment if it contains no Java source (see https://bugs.eclipse
        // .org/bugs/show_bug.cgi?id=190840 )
        //         Object target = JavaModel.getTarget(this.sourcePath, true);
        //         if (target instanceof IContainer) {
        //            IContainer folder = (IContainer)target;
        //            computeRootPath(folder, firstLevelPackageNames, containsADefaultPackage, tempRoots, folder.getFullPath().segmentCount()
        // /*if external folder, this is the linked folder path*/);
        //         } else {
        //            JavaModelManager
        //                  manager = JavaModelManager.getJavaModelManager();
        ZipFile zip = null;
        try {
            zip = manager.getZipFile(this.sourcePath);
            for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String entryName;
                if (!entry.isDirectory() && Util.isJavaLikeFileName(entryName = entry.getName())) {
                    IPath path = new Path(entryName);
                    int segmentCount = path.segmentCount();
                    if (segmentCount > 1) {
                        for (int i = 0, max = path.segmentCount() - 1; i < max; i++) {
                            if (firstLevelPackageNames.contains(path.segment(i))) {
                                tempRoots.add(path.uptoSegment(i));
                                // don't break here as this path could contain other first level package names (see https://bugs
                                // .eclipse.org/bugs/show_bug.cgi?id=74014)
                            }
                            if (i == max - 1 && containsADefaultPackage) {
                                tempRoots.add(path.uptoSegment(max));
                            }
                        }
                    } else if (containsADefaultPackage) {
                        tempRoots.add(new Path("")); //$NON-NLS-1$
                    }
                }
            }
        } catch (CoreException e) {
            // ignore
        } finally {
            manager.closeZipFile(zip); // handle null case
        }
        //         }
    }
    int size = tempRoots.size();
    if (this.rootPaths != null) {
        for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext();) {
            tempRoots.add(new Path((String) iterator.next()));
        }
        this.rootPaths.clear();
    } else {
        this.rootPaths = new ArrayList(size);
    }
    size = tempRoots.size();
    if (size > 0) {
        ArrayList sortedRoots = new ArrayList(tempRoots);
        if (size > 1) {
            Collections.sort(sortedRoots, new Comparator() {
                public int compare(Object o1, Object o2) {
                    IPath path1 = (IPath) o1;
                    IPath path2 = (IPath) o2;
                    return path1.segmentCount() - path2.segmentCount();
                }
            });
        }
        for (Iterator iter = sortedRoots.iterator(); iter.hasNext();) {
            IPath path = (IPath) iter.next();
            this.rootPaths.add(path.toString());
        }
    }
    this.areRootPathsComputed = true;
    if (VERBOSE) {
        System.out.println("Spent " + (System.currentTimeMillis() - time) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
        System.out.println("Found " + size + " root paths"); //$NON-NLS-1$ //$NON-NLS-2$
        int i = 0;
        for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext();) {
            System.out.println("root[" + i + "]=" + ((String) iterator.next()));//$NON-NLS-1$ //$NON-NLS-2$
            i++;
        }
    }
}

From source file:org.eclipse.che.jdt.util.JavaModelUtil.java

License:Open Source License

private static String getSourceCompliance(IJavaProject project) {
    return project != null ? project.getOption(JavaCore.COMPILER_SOURCE, true)
            : JavaCore.getOption(JavaCore.COMPILER_SOURCE);
}

From source file:org.eclipse.edt.ide.ui.internal.CodeFormatterUtil.java

License:Open Source License

/**
 * Returns the possibly <code>project</code>-specific core preference
 * defined under <code>key</code>.
 * /*from w w w. ja v a  2 s. c om*/
 * @param project the project to get the preference from, or
 *        <code>null</code> to get the global preference
 * @param key the key of the preference
 * @return the value of the preference
 * @since 3.1
 */
private static String getCoreOption(IJavaProject project, String key) {
    if (project == null)
        return JavaCore.getOption(key);
    return project.getOption(key, true);
}

From source file:org.eclipse.flux.jdt.services.CompletionProposalReplacementProvider.java

License:Open Source License

private final boolean shouldProposeGenerics(IJavaProject project) {
    String sourceVersion;/*from w  ww  .j  a va2s  .  c  om*/
    if (project != null)
        sourceVersion = project.getOption(JavaCore.COMPILER_SOURCE, true);
    else
        sourceVersion = JavaCore.getOption(JavaCore.COMPILER_SOURCE);

    return !isVersionLessThan(sourceVersion, JavaCore.VERSION_1_5);
}

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 {/*from w  w w  .j a  v a  2s  .c  om*/
        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.CompilationUnitProblemFinder.java

License:Open Source License

/**
 * Add additional source types//  w  ww.  j av  a2s  .c  o  m
 */
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding,
        AccessRestriction accessRestriction) {
    // ensure to jump back to toplevel type for first one (could be a member)
    while (sourceTypes[0].getEnclosingType() != null) {
        sourceTypes[0] = sourceTypes[0].getEnclosingType();
    }

    CompilationResult result = new CompilationResult(sourceTypes[0].getFileName(), 1, 1,
            this.options.maxProblemsPerUnit);

    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305259, build the compilation unit in its own sand box.
    final long savedComplianceLevel = this.options.complianceLevel;
    final long savedSourceLevel = this.options.sourceLevel;

    try {
        IJavaProject project = ((SourceTypeElementInfo) sourceTypes[0]).getHandle().getJavaProject();
        this.options.complianceLevel = CompilerOptions
                .versionToJdkLevel(project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
        this.options.sourceLevel = CompilerOptions
                .versionToJdkLevel(project.getOption(JavaCore.COMPILER_SOURCE, true));

        // need to hold onto this
        CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit(sourceTypes, //sourceTypes[0] is always toplevel here
                SourceTypeConverter.FIELD_AND_METHOD // need field and methods
                        | SourceTypeConverter.MEMBER_TYPE // need member types
                        | SourceTypeConverter.FIELD_INITIALIZATION, // need field initialization
                this.lookupEnvironment.problemReporter, result);

        if (unit != null) {
            this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
            this.lookupEnvironment.completeTypeBindings(unit);
        }
    } finally {
        this.options.complianceLevel = savedComplianceLevel;
        this.options.sourceLevel = savedSourceLevel;
    }
}

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

License:Open Source License

/**
 * Returns the package fragment root represented by the resource, or
 * the package fragment the given resource is located in, or <code>null</code>
 * if the given resource is not on the classpath of the given project.
 *//*from   w ww  .j  a  va  2  s .  c  o  m*/
public static IJavaElement determineIfOnClasspath(IResource resource, IJavaProject project) {
    IPath resourcePath = resource.getFullPath();
    boolean isExternal = ExternalFoldersManager.isInternalPathForExternalFolder(resourcePath);
    if (isExternal)
        resourcePath = resource.getLocation();

    try {
        JavaProjectElementInfo projectInfo = (JavaProjectElementInfo) getJavaModelManager().getInfo(project);
        ProjectCache projectCache = projectInfo == null ? null : projectInfo.projectCache;
        HashtableOfArrayToObject allPkgFragmentsCache = projectCache == null ? null
                : projectCache.allPkgFragmentsCache;
        boolean isJavaLike = org.eclipse.jdt.internal.core.util.Util
                .isJavaLikeFileName(resourcePath.lastSegment());
        IClasspathEntry[] entries = isJavaLike ? project.getRawClasspath() // JAVA file can only live inside SRC folder (on the raw path)
                : ((JavaProject) project).getResolvedClasspath();

        int length = entries.length;
        if (length > 0) {
            String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
            String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
            for (int i = 0; i < length; i++) {
                IClasspathEntry entry = entries[i];
                if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT)
                    continue;
                IPath rootPath = entry.getPath();
                if (rootPath.equals(resourcePath)) {
                    if (isJavaLike)
                        return null;
                    return project.getPackageFragmentRoot(resource);
                } else if (rootPath.isPrefixOf(resourcePath)) {
                    // allow creation of package fragment if it contains a .java file that is included
                    if (!Util.isExcluded(resource, ((ClasspathEntry) entry).fullInclusionPatternChars(),
                            ((ClasspathEntry) entry).fullExclusionPatternChars())) {
                        // given we have a resource child of the root, it cannot be a JAR pkg root
                        PackageFragmentRoot root = isExternal
                                ? new ExternalPackageFragmentRoot(rootPath, (JavaProject) project)
                                : (PackageFragmentRoot) ((JavaProject) project)
                                        .getFolderPackageFragmentRoot(rootPath);
                        if (root == null)
                            return null;
                        IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());

                        if (resource.getType() == IResource.FILE) {
                            // if the resource is a file, then remove the last segment which
                            // is the file name in the package
                            pkgPath = pkgPath.removeLastSegments(1);
                        }
                        String[] pkgName = pkgPath.segments();

                        // if package name is in the cache, then it has already been validated
                        // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=133141)
                        if (allPkgFragmentsCache != null && allPkgFragmentsCache.containsKey(pkgName))
                            return root.getPackageFragment(pkgName);

                        if (pkgName.length != 0 && JavaConventions
                                .validatePackageName(Util.packageName(pkgPath, sourceLevel, complianceLevel),
                                        sourceLevel, complianceLevel)
                                .getSeverity() == IStatus.ERROR) {
                            return null;
                        }
                        return root.getPackageFragment(pkgName);
                    }
                }
            }
        }
    } catch (JavaModelException npe) {
        return null;
    }
    return null;
}

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

License:Open Source License

/**
 * @see Openable//from   w w w. ja va 2s.c om
 */
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.search.matching.MatchLocator.java

License:Open Source License

private boolean filterEnum(SearchMatch match) {

    // filter org.apache.commons.lang.enum package for projects above 1.5 
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=317264   
    IJavaElement element = (IJavaElement) match.getElement();
    PackageFragment pkg = (PackageFragment) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
    if (pkg != null) {
        // enum was found in org.apache.commons.lang.enum at index 5
        if (pkg.names.length == 5 && pkg.names[4].equals("enum")) { //$NON-NLS-1$
            if (this.options == null) {
                IJavaProject proj = (IJavaProject) pkg.getAncestor(IJavaElement.JAVA_PROJECT);
                String complianceStr = proj.getOption(CompilerOptions.OPTION_Source, true);
                if (CompilerOptions.versionToJdkLevel(complianceStr) >= ClassFileConstants.JDK1_5)
                    return true;
            } else if (this.options.sourceLevel >= ClassFileConstants.JDK1_5) {
                return true;
            }//  w  ww.  jav a 2 s.  c o  m
        }
    }
    return false;
}