Example usage for org.eclipse.jdt.internal.core.util Util isJavaLikeFileName

List of usage examples for org.eclipse.jdt.internal.core.util Util isJavaLikeFileName

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core.util Util isJavaLikeFileName.

Prototype

public final static boolean isJavaLikeFileName(char[] fileName) 

Source Link

Document

Returns true if the given name ends with one of the known java like extension.

Usage

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

License:Open Source License

public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled())
        return true;
    //      if (!this.project.isAccessible()) return true; // nothing to do
    //      IResource folder = this.project.getParent().findMember(this.folderPath);

    File folder = new File(folderPath.toOSString());
    if (!folder.exists())
        return true; // nothing to do, source folder was removed

    /* ensure no concurrent write access to index */
    Index index = this.manager.getIndex(this.containerPath, true, /*reuse index file*/ true /*create if none*/);
    if (index == null)
        return true;
    ReadWriteMonitor monitor = index.monitor;
    if (monitor == null)
        return true; // index got deleted since acquired

    try {/*from ww w .  j a v a  2 s.  c  om*/
        monitor.enterRead(); // ask permission to read

        final IPath container = this.containerPath;
        final IndexManager indexManager = this.manager;
        final SourceElementParser parser = indexManager.getSourceElementParser(this.project,
                null/*requestor will be set by indexer*/);
        Path path = FileSystems.getDefault().getPath(folderPath.toOSString());
        if (this.exclusionPatterns == null && this.inclusionPatterns == null) {

            Files.walkFileTree(path, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    return null;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Util.isJavaLikeFileName(file.toFile().getName()))
                        indexManager.addSource(file, container, parser);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return null;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return null;
                }
            });

            //                folder.accept(
            //               new IResourceProxyVisitor() {
            //                  public boolean visit(IResourceProxy proxy) /* throws CoreException */{
            //                     if (proxy.getType() == IResource.FILE) {
            //
            //                        return false;
            //                     }
            //                     return true;
            //                  }
            //               },
            //               IResource.NONE
            //            );
        } else {
            Files.walkFileTree(path, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (AddFolderToIndex.this.exclusionPatterns != null
                            && AddFolderToIndex.this.inclusionPatterns == null) {
                        // if there are inclusion patterns then we must walk the children
                        if (Util.isExcluded(new org.eclipse.core.runtime.Path(dir.toFile().getPath()),
                                AddFolderToIndex.this.inclusionPatterns,
                                AddFolderToIndex.this.exclusionPatterns, true))
                            return FileVisitResult.SKIP_SUBTREE;
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Util.isJavaLikeFileName(file.getFileName().toString())) {
                        //                                IResource resource = proxy.requestResource();
                        if (!Util.isExcluded(new org.eclipse.core.runtime.Path(file.toFile().getPath()),
                                AddFolderToIndex.this.inclusionPatterns,
                                AddFolderToIndex.this.exclusionPatterns, false))
                            indexManager.addSource(file, container, parser);
                    }
                    return null;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return null;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return null;
                }
            });
            //                folder.accept(
            //               new IResourceProxyVisitor() {
            //                  public boolean visit(IResourceProxy proxy) /* throws CoreException */{
            //                     switch(proxy.getType()) {
            //                        case IResource.FILE :
            //
            //                           return false;
            //                        case IResource.FOLDER :
            //
            //                     }
            //                     return true;
            //                  }
            //               },
            //               IResource.NONE
            //            );
        }
    } catch (IOException e) {
        if (JobManager.VERBOSE) {
            Util.verbose(
                    "-> failed to add " + this.folderPath + " to index because of the following exception:", //$NON-NLS-1$//$NON-NLS-2$
                    System.err);
            e.printStackTrace();
        }
        return false;
    } finally {
        monitor.exitRead(); // free read lock
    }
    return true;
}

From source file:fr.obeo.dsl.fluent.files.JavaFormatter.java

License:Open Source License

public void format(File file) throws MalformedTreeException, org.eclipse.jface.text.BadLocationException {
    if (file.isDirectory()) {
        formatDirTree(file, codeFormatter);
    } else if (Util.isJavaLikeFileName(file.getPath())) {
        formatFile(file, codeFormatter);
    }/*from  ww  w.j  a v  a 2  s . c  om*/
}

From source file:fr.obeo.dsl.fluent.files.JavaFormatter.java

License:Open Source License

/**
 * Recursively format the Java source code that is contained in the
 * directory rooted at dir.//from   www .  j av  a2s . c  o m
 * 
 * @throws org.eclipse.jface.text.BadLocationException
 * @throws MalformedTreeException
 */
private void formatDirTree(File dir, CodeFormatter codeFormatter)
        throws MalformedTreeException, org.eclipse.jface.text.BadLocationException {

    File[] files = dir.listFiles();
    if (files == null)
        return;

    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        if (file.isDirectory()) {
            formatDirTree(file, codeFormatter);
        } else if (Util.isJavaLikeFileName(file.getPath())) {
            formatFile(file, codeFormatter);
        }
    }
}

From source file:org.codehaus.groovy.eclipse.debug.ui.BreakpointUpdater.java

License:Apache License

/**
 * Finds the groovy compilation unit associated with this marker's resource.
 * Tries to get a working copy first, or otherwise creates a new compilation unit
 * @param marker/*  w  ww  .  ja va  2s . c  o  m*/
 * @return {@link GroovyCompilationUnit} associated with this marker's resource or
 * null if none exists.
 */
private GroovyCompilationUnit getCompilationUnit(IMarker marker) {
    IResource resource = marker.getResource();
    if (!Util.isJavaLikeFileName(resource.getName())) {
        return null;
    }
    ICompilationUnit unit = JavaPlugin.getDefault().getCompilationUnitDocumentProvider()
            .getWorkingCopy(resource);
    if (unit == null && resource.getType() == IResource.FILE) {
        // nope...must create from new
        unit = JavaCore.createCompilationUnitFrom((IFile) resource);
    }
    if (unit != null && unit instanceof GroovyCompilationUnit) {
        return (GroovyCompilationUnit) unit;
    } else {
        return null;
    }
}

From source file:org.codehaus.groovy.eclipse.ui.GroovyResourcePropertyTester.java

License:Apache License

public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
    boolean returnValue = false;

    if (hasMain.equals(property) || isScript.equals(property)) {
        if (receiver instanceof IAdaptable) {
            try {
                ICompilationUnit unit = (ICompilationUnit) ((IAdaptable) receiver)
                        .getAdapter(ICompilationUnit.class);
                if (unit == null) {
                    IFile file = (IFile) ((IAdaptable) receiver).getAdapter(IFile.class);
                    if (file != null && Util.isJavaLikeFileName(file.getName())) {
                        unit = JavaCore.createCompilationUnitFrom(file);
                    }//from w w w .jav a 2  s . c  o m
                }
                if (unit != null) {
                    if (hasMain.equals(property) || isScript.equals(property)) {
                        List<IType> results = GroovyProjectFacade.findAllRunnableTypes(unit);
                        returnValue = results.size() > 0;
                    }
                }
            } catch (IllegalArgumentException e) {
                // can ignore
                // passed in non-JavaLike file name
            } catch (JavaModelException e) {
                // can ignore situations when trying to find types that are not on the classpath
                if (e.getStatus() != null
                        && e.getStatus().getCode() != IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH) {
                    GroovyCore.logException("Exception when testing for main methods " + receiver, e);
                }
            }

        }
    }
    return returnValue;
}

From source file:org.codehaus.jdt.groovy.integration.DefaultLanguageSupport.java

License:Open Source License

public boolean isSourceFile(String fileName, boolean isInterestingProject) {
    return Util.isJavaLikeFileName(fileName);
}

From source file:org.codehaus.jdt.groovy.integration.internal.GroovyLanguageSupport.java

License:Open Source License

public boolean isSourceFile(String fileName, boolean isInterestingProject) {
    if (isInterestingProject) {
        return Util.isJavaLikeFileName(fileName);
    } else {// w  ww  .j  a  va2 s  .c o m
        return ContentTypeUtils.isJavaLikeButNotGroovyLikeExtension(fileName);
    }
}

From source file:org.eclipse.ajdt.internal.core.ajde.CoreOutputLocationManager.java

License:Open Source License

public File getOutputLocationForClass(File compilationUnit) {
    // remember that this file has been asked for
    // presumably it is being recompiled
    if (Util.isJavaLikeFileName(compilationUnit.getName()) && !isComputingXmlFile()) {
        compiledSourceFiles.add(compilationUnit);
    }//  w ww.j av a2 s .  co m

    return getOutputLocationForResource(compilationUnit);
}

From source file:org.eclipse.che.jdt.dom.JavaConventions.java

License:Open Source License

/**
 * Validate the given compilation unit name for the given source and compliance levels.
 * <p>/*  ww  w . java2  s.  c  o m*/
 * A compilation unit name must obey the following rules:
 * <ul>
 * <li> it must not be null
 * <li> it must be suffixed by a dot ('.') followed by one of the
 *       {@link org.eclipse.jdt.core.JavaCore#getJavaLikeExtensions() Java-like extensions}
 * <li> its prefix must be a valid identifier
 * <li> it must not contain any characters or substrings that are not valid
 *         on the file system on which workspace root is located.
 * </ul>
 * </p>
 * @param name the name of a compilation unit
 * @param sourceLevel the source level
 * @param complianceLevel the compliance level
 * @return a status object with code <code>IStatus.OK</code> if
 *      the given name is valid as a compilation unit name, otherwise a status
 *      object indicating what is wrong with the name
 * @since 3.3
 */
public static IStatus validateCompilationUnitName(String name, String sourceLevel, String complianceLevel) {
    if (name == null) {
        return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.convention_unit_nullName, null);
    }
    if (!Util.isJavaLikeFileName(name)) {
        return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.convention_unit_notJavaName, null);
    }
    String identifier;
    int index;
    index = name.lastIndexOf('.');
    if (index == -1) {
        return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.convention_unit_notJavaName, null);
    }
    identifier = name.substring(0, index);
    // JSR-175 metadata strongly recommends "package-info.java" as the
    // file in which to store package annotations and
    // the package-level spec (replaces package.html)
    if (!identifier.equals(PACKAGE_INFO)) {
        IStatus status = validateIdentifier(identifier, sourceLevel, complianceLevel);
        if (!status.isOK()) {
            return status;
        }
    }
    //        IStatus status = ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE);
    //        if (!status.isOK()) {
    //            return status;
    //        }
    return JavaModelStatus.VERIFIED_OK;
}

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

License:Open Source License

/**
 * Copies/moves a package fragment with the name <code>newName</code>
 * to the destination package.<br>
 *
 * @exception JavaModelException if the operation is unable to
 * complete//from w  w w  . j  a v a  2s .c o  m
 */
private void processPackageFragmentResource(PackageFragment source, PackageFragmentRoot root, String newName)
        throws JavaModelException {
    try {
        String[] newFragName = (newName == null) ? source.names : Util.getTrimmedSimpleNames(newName);
        PackageFragment newFrag = root.getPackageFragment(newFragName);
        IResource[] resources = collectResourcesOfInterest(source);

        // if isMove() can we move the folder itself ? (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=22458)
        boolean shouldMoveFolder = isMove() && !newFrag.resource().exists(); // if new pkg fragment exists, it is an override
        IFolder srcFolder = (IFolder) source.resource();
        IPath destPath = newFrag.getPath();
        if (shouldMoveFolder) {
            // check if destination is not included in source
            if (srcFolder.getFullPath().isPrefixOf(destPath)) {
                shouldMoveFolder = false;
            } else {
                // check if there are no sub-packages
                IResource[] members = srcFolder.members();
                for (int i = 0; i < members.length; i++) {
                    if (members[i] instanceof IFolder) {
                        shouldMoveFolder = false;
                        break;
                    }
                }
            }
        }
        boolean containsReadOnlySubPackageFragments = createNeededPackageFragments(
                (IContainer) source.parent.resource(), root, newFragName, shouldMoveFolder);
        boolean sourceIsReadOnly = Util.isReadOnly(srcFolder);

        // Process resources
        if (shouldMoveFolder) {
            // move underlying resource
            // TODO Revisit once bug 43044 is fixed
            if (sourceIsReadOnly) {
                Util.setReadOnly(srcFolder, false);
            }
            srcFolder.move(destPath, this.force, true /* keep history */, getSubProgressMonitor(1));
            if (sourceIsReadOnly) {
                Util.setReadOnly(srcFolder, true);
            }
            setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
        } else {
            // process the leaf resources
            if (resources.length > 0) {
                if (isRename()) {
                    if (!destPath.equals(source.getPath())) {
                        moveResources(resources, destPath);
                    }
                } else if (isMove()) {
                    // we need to delete this resource if this operation wants to override existing resources
                    for (int i = 0, max = resources.length; i < max; i++) {
                        IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot()
                                .findMember(destPath.append(resources[i].getName()));
                        if (destinationResource != null) {
                            if (this.force) {
                                deleteResource(destinationResource, IResource.KEEP_HISTORY);
                            } else {
                                throw new JavaModelException(
                                        new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION,
                                                Messages.bind(Messages.status_nameCollision,
                                                        destinationResource.getFullPath().toString())));
                            }
                        }
                    }
                    moveResources(resources, destPath);
                } else {
                    // we need to delete this resource if this operation wants to override existing resources
                    for (int i = 0, max = resources.length; i < max; i++) {
                        IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot()
                                .findMember(destPath.append(resources[i].getName()));
                        if (destinationResource != null) {
                            if (this.force) {
                                // we need to delete this resource if this operation wants to override existing resources
                                deleteResource(destinationResource, IResource.KEEP_HISTORY);
                            } else {
                                throw new JavaModelException(
                                        new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION,
                                                Messages.bind(Messages.status_nameCollision,
                                                        destinationResource.getFullPath().toString())));
                            }
                        }
                    }
                    copyResources(resources, destPath);
                }
            }
        }

        // Update package statement in compilation unit if needed
        if (!Util.equalArraysOrNull(newFragName, source.names)) { // if package has been renamed, update the compilation units
            char[][] inclusionPatterns = root.fullInclusionPatternChars();
            char[][] exclusionPatterns = root.fullExclusionPatternChars();
            for (int i = 0; i < resources.length; i++) {
                String resourceName = resources[i].getName();
                if (Util.isJavaLikeFileName(resourceName)) {
                    // we only consider potential compilation units
                    ICompilationUnit cu = newFrag.getCompilationUnit(resourceName);
                    if (Util.isExcluded(cu.getPath(), inclusionPatterns, exclusionPatterns,
                            false/*not a folder*/))
                        continue;
                    this.parser.setSource(cu);
                    CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
                    AST ast = astCU.getAST();
                    ASTRewrite rewrite = ASTRewrite.create(ast);
                    updatePackageStatement(astCU, newFragName, rewrite, cu);
                    TextEdit edits = rewrite.rewriteAST();
                    applyTextEdit(cu, edits);
                    cu.save(null, false);
                }
            }
        }

        // Discard empty old package (if still empty after the rename)
        boolean isEmpty = true;
        if (isMove()) {
            // delete remaining files in this package (.class file in the case where Proj=src=bin)
            // in case of a copy
            updateReadOnlyPackageFragmentsForMove((IContainer) source.parent.resource(), root, newFragName,
                    sourceIsReadOnly);
            if (srcFolder.exists()) {
                IResource[] remaining = srcFolder.members();
                for (int i = 0, length = remaining.length; i < length; i++) {
                    IResource file = remaining[i];
                    if (file instanceof IFile) {
                        if (Util.isReadOnly(file)) {
                            Util.setReadOnly(file, false);
                        }
                        deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY);
                    } else {
                        isEmpty = false;
                    }
                }
            }
            if (isEmpty) {
                IResource rootResource;
                // check if source is included in destination
                if (destPath.isPrefixOf(srcFolder.getFullPath())) {
                    rootResource = newFrag.resource();
                } else {
                    rootResource = source.parent.resource();
                }

                // delete recursively empty folders
                deleteEmptyPackageFragment(source, false, rootResource);
            }
        } else if (containsReadOnlySubPackageFragments) {
            // in case of a copy
            updateReadOnlyPackageFragmentsForCopy((IContainer) source.parent.resource(), root, newFragName);
        }
        // workaround for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=24505
        if (isEmpty && isMove() && !(Util.isExcluded(source) || Util.isExcluded(newFrag))) {
            IJavaProject sourceProject = source.getJavaProject();
            getDeltaFor(sourceProject).movedFrom(source, newFrag);
            IJavaProject destProject = newFrag.getJavaProject();
            getDeltaFor(destProject).movedTo(newFrag, source);
        }
    } catch (JavaModelException e) {
        throw e;
    } catch (CoreException ce) {
        throw new JavaModelException(ce);
    }
}