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:com.codenvy.ide.ext.java.server.internal.core.PackageFragment.java

License:Open Source License

/**
 * @see Openable//w w  w  .  ja va2s  . c o  m
 */
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements,
        File underlyingResource) throws JavaModelException {
    // add compilation units/class files from resources
    HashSet vChildren = new HashSet();
    int kind = getKind();
    PackageFragmentRoot root = getPackageFragmentRoot();
    char[][] inclusionPatterns = root.fullInclusionPatternChars();
    char[][] exclusionPatterns = root.fullExclusionPatternChars();
    File[] members = underlyingResource.listFiles();

    {
        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++) {
                File child = members[i];
                if (child.isFile() && !Util.isExcluded(new Path(child.getAbsolutePath()), inclusionPatterns,
                        exclusionPatterns, false)) {
                    IJavaElement childElement;
                    if (kind == IPackageFragmentRoot.K_SOURCE
                            && Util.isValidCompilationUnitName(child.getName(), sourceLevel, complianceLevel)) {
                        childElement = new CompilationUnit(this, manager, child.getName(),
                                DefaultWorkingCopyOwner.PRIMARY);
                        vChildren.add(childElement);
                    } else if (kind == IPackageFragmentRoot.K_BINARY
                            && Util.isValidClassFileName(child.getName(), sourceLevel, complianceLevel)) {
                        childElement = getClassFile(child.getName());
                        vChildren.add(childElement);
                    }
                }
            }
        }
    }
    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:com.codenvy.ide.ext.java.server.internal.core.PackageFragment.java

License:Open Source License

protected boolean internalIsValidPackageName() {
    // if package fragment refers to folder in another IProject, then
    // resource().getProject() is different than getJavaProject().getProject()
    // use the other java project's options to verify the name
    IJavaProject javaProject = getJavaProject(); //JavaCore.create(resource().getProject());
    String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
    String complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
    for (int i = 0, length = this.names.length; i < length; i++) {
        if (!Util.isValidFolderNameForPackage(this.names[i], sourceLevel, complianceLevel))
            return false;
    }/* w ww . j  av  a  2  s .c o m*/
    return true;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.PackageFragmentRootInfo.java

License:Open Source License

/**
 * Starting at this folder, create non-java resources for this package fragment root
 * and add them to the non-java resources collection.
 *
 * @exception org.eclipse.jdt.core.JavaModelException  The resource associated with this package fragment does not exist
 *//*from  www  . j  a v  a2 s . c  om*/
static Object[] computeFolderNonJavaResources(IPackageFragmentRoot root, IContainer folder,
        char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException {
    IResource[] nonJavaResources = new IResource[5];
    int nonJavaResourcesCounter = 0;
    try {
        IResource[] members = folder.members();
        int length = members.length;
        if (length > 0) {
            // if package fragment root refers to folder in another IProject, then
            // folder.getProject() is different than root.getJavaProject().getProject()
            // use the other java project's options to verify the name
            IJavaProject otherJavaProject = JavaCore.create(folder.getProject());
            String sourceLevel = otherJavaProject.getOption(JavaCore.COMPILER_SOURCE, true);
            String complianceLevel = otherJavaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
            JavaProject javaProject = (JavaProject) root.getJavaProject();
            IClasspathEntry[] classpath = javaProject.getResolvedClasspath();
            nextResource: for (int i = 0; i < length; i++) {
                IResource member = members[i];
                switch (member.getType()) {
                case IResource.FILE:
                    String fileName = member.getName();

                    // ignore .java files that are not excluded
                    if (Util.isValidCompilationUnitName(fileName, sourceLevel, complianceLevel)
                            && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns))
                        continue nextResource;
                    // ignore .class files
                    if (Util.isValidClassFileName(fileName, sourceLevel, complianceLevel))
                        continue nextResource;
                    // ignore .zip or .jar file on classpath
                    if (isClasspathEntry(member.getFullPath(), classpath))
                        continue nextResource;
                    break;

                case IResource.FOLDER:
                    // ignore valid packages or excluded folders that correspond to a nested pkg fragment root
                    if (Util.isValidFolderNameForPackage(member.getName(), sourceLevel, complianceLevel)
                            && (!Util.isExcluded(member, inclusionPatterns, exclusionPatterns)
                                    || isClasspathEntry(member.getFullPath(), classpath)))
                        continue nextResource;
                    break;
                }
                if (nonJavaResources.length == nonJavaResourcesCounter) {
                    // resize
                    System.arraycopy(nonJavaResources, 0,
                            (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0,
                            nonJavaResourcesCounter);
                }
                nonJavaResources[nonJavaResourcesCounter++] = member;
            }
        }
        //      if (ExternalFoldersManager.isInternalPathForExternalFolder(folder.getFullPath())) {
        //         IJarEntryResource[] jarEntryResources = new IJarEntryResource[nonJavaResourcesCounter];
        //         for (int i = 0; i < nonJavaResourcesCounter; i++) {
        //            jarEntryResources[i] = new NonJavaResource(root, nonJavaResources[i]);
        //         }
        //         return jarEntryResources;
        //      } else if (nonJavaResources.length != nonJavaResourcesCounter) {
        //         System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
        //      }
        return nonJavaResources;
    } catch (CoreException e) {
        throw new JavaModelException(e);
    }
}

From source file:com.codenvy.ide.ext.java.server.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;
            }/*from  w w  w .ja  v a2  s . co m*/
        }
    }
    return false;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.TypeNameMatchRequestorWrapper.java

License:Open Source License

private IType createTypeFromJar(String resourcePath, int separatorIndex) throws JavaModelException {
    // path to a class file inside a jar
    // Optimization: cache package fragment root handle and package handles
    if (this.lastPkgFragmentRootPath == null || this.lastPkgFragmentRootPath.length() > resourcePath.length()
            || !resourcePath.startsWith(this.lastPkgFragmentRootPath)) {
        String jarPath = resourcePath.substring(0, separatorIndex);
        IPackageFragmentRoot root = ((AbstractJavaSearchScope) this.scope).packageFragmentRoot(resourcePath,
                separatorIndex, jarPath);
        if (root == null)
            return null;
        this.lastPkgFragmentRootPath = jarPath;
        this.lastPkgFragmentRoot = root;
        this.packageHandles = new HashtableOfArrayToObject(5);
    }/*from  w ww .  j  a v a2s. c o m*/
    // create handle
    String classFilePath = resourcePath.substring(separatorIndex + 1);
    String[] simpleNames = new Path(classFilePath).segments();
    String[] pkgName;
    int length = simpleNames.length - 1;
    if (length > 0) {
        pkgName = new String[length];
        System.arraycopy(simpleNames, 0, pkgName, 0, length);
    } else {
        pkgName = CharOperation.NO_STRINGS;
    }
    IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName);
    if (pkgFragment == null) {
        pkgFragment = ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName);
        // filter org.apache.commons.lang.enum package for projects above 1.5 
        // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317264
        if (length == 5 && pkgName[4].equals("enum")) { //$NON-NLS-1$
            IJavaProject proj = (IJavaProject) pkgFragment.getAncestor(IJavaElement.JAVA_PROJECT);
            if (!proj.equals(this.lastProject)) {
                String complianceStr = proj.getOption(CompilerOptions.OPTION_Source, true);
                this.complianceValue = CompilerOptions.versionToJdkLevel(complianceStr);
                this.lastProject = proj;
            }
            if (this.complianceValue >= ClassFileConstants.JDK1_5)
                return null;
        }
        this.packageHandles.put(pkgName, pkgFragment);
    }
    return pkgFragment.getClassFile(simpleNames[length]).getType();
}

From source file:com.codenvy.ide.ext.java.server.internal.core.SearchableEnvironmentRequestor.java

License:Open Source License

/**
 * Constructs a SearchableEnvironmentRequestor that wraps the
 * given SearchRequestor.  The requestor will not accept types in
 * the <code>unitToSkip</code>.
 *///from   w  w  w.  j a  v a 2  s . c  om
public SearchableEnvironmentRequestor(ISearchRequestor requestor, ICompilationUnit unitToSkip,
        IJavaProject project, NameLookup nameLookup) {
    this.requestor = requestor;
    this.unitToSkip = unitToSkip;
    this.project = project;
    this.nameLookup = nameLookup;
    this.checkAccessRestrictions = !JavaCore.IGNORE
            .equals(project.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
            || !JavaCore.IGNORE.equals(project.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true));
}

From source file:com.codenvy.ide.ext.java.server.internal.core.SourceMapper.java

License:Open Source License

private synchronized void computeAllRootPaths(IType type) {
    if (this.areRootPathsComputed) {
        return;/*from   ww  w .j a v a2 s .co m*/
    }
    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 && com.codenvy.ide.ext.java.server.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:com.codenvy.ide.ext.java.server.JavadocFinder.java

License:Open Source License

/**
 * Returns the assignment operator string with the project's formatting applied to it.
 *
 * @param javaProject the Java project whose formatting options will be used.
 * @return the formatted assignment operator string.
 * @since 3.4/* w ww  .  java2 s . c o  m*/
 */
public static String getFormattedAssignmentOperator(IJavaProject javaProject) {
    StringBuffer buffer = new StringBuffer();
    if (JavaCore.INSERT.equals(javaProject
            .getOption(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, true)))
        buffer.append(' ');
    buffer.append('=');
    if (JavaCore.INSERT.equals(javaProject
            .getOption(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR, true)))
        buffer.append(' ');
    return buffer.toString();
}

From source file:com.google.gdt.eclipse.designer.uibinder.model.util.NameSupport.java

License:Open Source License

/**
 * @return the error message if given name is not valid, or <code>null</code> if this name can be
 *         used.//from   w ww. java 2 s  .  c  o  m
 */
private String validateName(String name) throws Exception {
    // check that identifier is valid
    {
        IJavaProject javaProject = m_object.getContext().getJavaProject();
        String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
        String complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
        IStatus status = JavaConventions.validateFieldName(name, sourceLevel, complianceLevel);
        if (status.matches(IStatus.ERROR)) {
            return status.getMessage();
        }
    }
    // check that name is unique
    {
        Set<String> existingNames = getExistingNames();
        if (existingNames.contains(name)) {
            return "Field '" + name + "' already exists.";
        }
    }
    // OK
    return null;
}

From source file:com.javadude.antxr.eclipse.ui.editor.AntxrConfiguration.java

License:Open Source License

/** {@inheritDoc} */
public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
    List<String> prefixes = new ArrayList<String>();
    int tabWidth = 0;
    boolean useSpaces;

    IJavaProject project = getProject();
    String tabSize;// w w w .java  2 s . c  o  m
    if (project != null) {
        tabSize = project.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, true);
        useSpaces = JavaCore.SPACE
                .equals(project.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, true));
    } else {
        tabSize = JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
        useSpaces = JavaCore.SPACE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR));
    }
    try {
        tabWidth = Integer.parseInt(tabSize);
    } catch (NumberFormatException e) {
        tabWidth = 4;
    }

    // prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces
    for (int i = 0; i <= tabWidth; i++) {
        StringBuffer prefix = new StringBuffer();

        if (useSpaces) {
            for (int j = 0; j + i < tabWidth; j++) {
                prefix.append(' ');
            }

            if (i != 0) {
                prefix.append('\t');
            }
        } else {
            for (int j = 0; j < i; j++) {
                prefix.append(' ');
            }

            if (i != tabWidth) {
                prefix.append('\t');
            }
        }

        prefixes.add(prefix.toString());
    }

    prefixes.add(""); //$NON-NLS-1$

    return prefixes.toArray(new String[prefixes.size()]);
}