Example usage for org.eclipse.jdt.core JavaCore isJavaLikeFileName

List of usage examples for org.eclipse.jdt.core JavaCore isJavaLikeFileName

Introduction

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

Prototype

public static boolean isJavaLikeFileName(String fileName) 

Source Link

Document

Returns whether the given file name's extension is a Java-like extension.

Usage

From source file:ca.uvic.chisel.javasketch.ui.internal.views.java.RefreshEditorsJob.java

License:Open Source License

@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
    //get the top editor and refresh it. The others will be refreshed when they are opened.
    IEditorPart editor = null;/*from   w w  w  .  j  av a  2s .c  o m*/
    try {
        editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
    } catch (NullPointerException e) {

    }
    if (editor != null) {
        monitor.beginTask("Annotating Editors", 1);
        try {
            IEditorInput input = editor.getEditorInput();
            if (input instanceof IStorageEditorInput) {
                IPath path = ((IStorageEditorInput) input).getStorage().getFullPath();
                if (path != null && JavaCore.isJavaLikeFileName(path.lastSegment())) {
                    IResource r = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
                    if (r instanceof IFile) {
                        IJavaElement element = JavaCore.create((IFile) r);
                        if (element instanceof ITypeRoot) {
                            if (monitor.isCanceled()) {
                                return Status.OK_STATUS;
                            }
                            MarkTypeJob mtj = new MarkTypeJob((ITypeRoot) element);
                            mtj.schedule();
                        }
                    }
                }
            }
        } catch (CoreException e) {
        }
        monitor.worked(1);
    }
    monitor.done();
    return Status.OK_STATUS;
}

From source file:com.google.gdt.eclipse.core.java.ClasspathResourceUtilities.java

License:Open Source License

/**
 * Returns the given file or JAR entry if it is on the given package fragment.
 * The file can be a Java file, class file, or a non-Java resource.
 * <p>/*ww w. j a  v  a2s  .  c  o  m*/
 * This method returns null for .java files or .class files inside JARs.
 * 
 * @param fileName the file name
 * @param pckgFragment the package fragment to search
 * @return the file as an IResource or IJarEntryResource, or null
 * @throws JavaModelException
 */
public static IStorage resolveFileOnPackageFragment(String fileName, IPackageFragment pckgFragment)
        throws JavaModelException {

    boolean isJavaFile = JavaCore.isJavaLikeFileName(fileName);
    boolean isClassFile = ResourceUtils.endsWith(fileName, ".class");

    // Check the non-Java resources first
    Object[] nonJavaResources = pckgFragment.getNonJavaResources();
    for (Object nonJavaResource : nonJavaResources) {
        if (nonJavaResource instanceof IFile) {
            IFile file = (IFile) nonJavaResource;
            String resFileName = file.getName();

            if (ResourceUtils.areFilenamesEqual(resFileName, fileName)) {
                // Java source files that have been excluded from the build path
                // show up as non-Java resources, but we'll ignore them since
                // they're not available on the classpath.
                if (!JavaCore.isJavaLikeFileName(resFileName)) {
                    return file;
                } else {
                    return null;
                }
            }
        }

        // JAR resources are not IResource's, so we need to handle them
        // differently
        if (nonJavaResource instanceof IJarEntryResource) {
            IJarEntryResource jarEntry = (IJarEntryResource) nonJavaResource;
            if (jarEntry.isFile() && ResourceUtils.areFilenamesEqual(jarEntry.getName(), fileName)) {
                return jarEntry;
            }
        }
    }

    // If we're looking for a .java or .class file, we can use the regular
    // Java Model methods.

    if (isJavaFile) {
        ICompilationUnit cu = pckgFragment.getCompilationUnit(fileName);
        if (cu.exists()) {
            return (IFile) cu.getCorrespondingResource();
        }
    }

    if (isClassFile) {
        IClassFile cf = pckgFragment.getClassFile(fileName);
        if (cf.exists()) {
            return (IFile) cf.getCorrespondingResource();
        }
    }

    return null;
}

From source file:com.laex.j2objc.preferences.PackagePrefixPropertyPage.java

License:Open Source License

/**
 * Load packages.// w  w w .  jav  a  2 s  .  co  m
 *
 * @throws CoreException the core exception
 */
private void loadPackages() throws CoreException {
    pkgList = new HashSet<String>();
    ProjectUtil.getJavaProject(getElement()).getResource().accept(new IResourceVisitor() {
        @Override
        public boolean visit(IResource resource) throws CoreException {
            if (JavaCore.isJavaLikeFileName(resource.getName())) {
                ICompilationUnit compU = JavaCore.createCompilationUnitFrom((IFile) resource);

                // Wrap with exception, in case the project does not have
                // any pacakgaes declared
                try {
                    pkgList.add(compU.getPackageDeclarations()[0].getElementName());
                } catch (ArrayIndexOutOfBoundsException aiobx) {
                    LogUtil.logException(aiobx);
                }

            }
            return true;
        }
    });
}

From source file:com.laex.j2objc.ToObjectiveCAction.java

License:Open Source License

/**
 * Calculate work./*from w  ww  . j  a  va2s  .c  o m*/
 */
private void calculateWork() {
    IJavaElement elm = (IJavaElement) strucSelc.getFirstElement();

    totalWork = 0;

    try {
        elm.getResource().accept(new IResourceVisitor() {
            @Override
            public boolean visit(IResource resource) throws CoreException {

                if (!(resource.getType() == IResource.FILE)) {
                    return true;
                }

                if (JavaCore.isJavaLikeFileName(resource.getName())) {
                    System.err.println(resource.getName());
                    totalWork++;
                    return true;
                }

                return true;
            }
        });
    } catch (CoreException e) {
        LogUtil.logException(e);
    }
}

From source file:com.laex.j2objc.ToObjectiveCDelegate.java

License:Open Source License

@Override
public boolean visit(final IResource resource) throws CoreException {
    // cancel the job
    if (monitor.isCanceled()) {
        onCancelled();// www .  ja  v a  2  s.co m
        resource.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
        monitor.done();
        return false;
    }

    if (!(resource.getType() == IResource.FILE)) {
        return true;
    }

    if (!JavaCore.isJavaLikeFileName(resource.getName())) {
        return true;
    }

    String sourcePath = resource.getLocation().makeAbsolute().toOSString();
    // As per the discussion with Tom Ball, the output of compilation is
    // stored in the project's root source folder
    // See
    // https://groups.google.com/forum/?fromgroups=#!topic/j2objc-discuss/lJGzN-pxmkQ
    String outputPath = resource.getProject().getFolder("src").getLocation().makeAbsolute().toOSString();

    try {
        String cmd = buildCommand(this.display, prefs, resource.getProject(), resource, sourcePath, outputPath);

        monitor.subTask(resource.getName());

        Process p = Runtime.getRuntime().exec(cmd);

        Scanner scanInput = new Scanner(p.getInputStream());
        Scanner scanErr = new Scanner(p.getErrorStream());

        MessageConsoleStream mct = MessageUtil.findConsole(MessageUtil.J2OBJC_CONSOLE).newMessageStream();

        mct.write(cmd);
        mct.write(MessageUtil.NEW_LINE_CONSTANT);

        while (scanInput.hasNext()) {
            MessageUtil.resetConsoleColor(display, mct);
            mct.write(scanInput.nextLine());
            mct.write(MessageUtil.NEW_LINE_CONSTANT);
        }

        while (scanErr.hasNext()) {
            MessageUtil.setConsoleColor(display, mct, SWT.COLOR_RED);
            mct.write(scanErr.nextLine());
            mct.write(MessageUtil.NEW_LINE_CONSTANT);
        }

        mct.write(MessageUtil.NEW_LINE_CONSTANT);

    } catch (IOException e) {
        LogUtil.logException(e);
    }

    monitor.worked(1);

    return true;
}

From source file:com.redhat.ceylon.eclipse.code.explorer.JavaElementImageProvider.java

License:Open Source License

private ImageDescriptor computeDescriptor(Object element, int flags) {
    if (element instanceof IJavaElement) {
        return getJavaImageDescriptor((IJavaElement) element, flags);
    } else if (element instanceof IFile) {
        IFile file = (IFile) element;//from w w  w  .  jav a 2s .  c o m
        if (JavaCore.isJavaLikeFileName(file.getName())) {
            return getCUResourceImageDescriptor(file, flags); // image for a CU not on the build path
        }
        return getWorkbenchImageDescriptor(file, flags);
    } else if (element instanceof IAdaptable) {
        return getWorkbenchImageDescriptor((IAdaptable) element, flags);
    }
    return null;
}

From source file:com.redhat.ceylon.eclipse.core.model.JDTModule.java

License:Open Source License

public void removedOriginalUnit(String relativePathToSource) {
    if (isProjectModule()) {
        return;//  w  w  w  .j  ava  2s.  c o m
    }
    originalUnitsToRemove.add(relativePathToSource);

    try {
        if (isCeylonBinaryArchive() || JavaCore.isJavaLikeFileName(relativePathToSource)) {
            List<String> unitPathsToSearch = new ArrayList<>();
            unitPathsToSearch.add(relativePathToSource);
            unitPathsToSearch.addAll(toBinaryUnitRelativePaths(relativePathToSource));
            for (String relativePathOfUnitToRemove : unitPathsToSearch) {
                Package p = getPackageFromRelativePath(relativePathOfUnitToRemove);
                if (p != null) {
                    Set<Unit> units = new HashSet<>();
                    try {
                        for (Declaration d : p.getMembers()) {
                            Unit u = d.getUnit();
                            if (u.getRelativePath().equals(relativePathOfUnitToRemove)) {
                                units.add(u);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    for (Unit u : units) {
                        try {
                            for (Declaration d : u.getDeclarations()) {
                                d.getMembers();
                                // Just to fully load the declaration before 
                                // the corresponding class is removed (so that 
                                // the real removing from the model loader
                                // will not require reading the bindings.
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.redhat.ceylon.eclipse.core.model.JDTModule.java

License:Open Source License

public void refresh() {
    if (originalUnitsToAdd.size() + originalUnitsToRemove.size() == 0) {
        // Nothing to refresh
        return;/*  w w w  .  j  a v a2s. c o m*/
    }

    try {
        PhasedUnitMap<? extends PhasedUnit, ?> phasedUnitMap = null;
        if (isCeylonBinaryArchive()) {
            JavaModelManager.getJavaModelManager().resetClasspathListCache();
            JavaModelManager.getJavaModelManager().getJavaModel().refreshExternalArchives(
                    getPackageFragmentRoots().toArray(new IPackageFragmentRoot[0]), null);
            phasedUnitMap = binaryModulePhasedUnits;
        }
        if (isSourceArchive()) {
            phasedUnitMap = sourceModulePhasedUnits.get();
        }
        if (phasedUnitMap != null) {
            synchronized (phasedUnitMap) {
                for (String relativePathToRemove : originalUnitsToRemove) {
                    if (isCeylonBinaryArchive() || JavaCore.isJavaLikeFileName(relativePathToRemove)) {
                        List<String> unitPathsToSearch = new ArrayList<>();
                        unitPathsToSearch.add(relativePathToRemove);
                        unitPathsToSearch.addAll(toBinaryUnitRelativePaths(relativePathToRemove));
                        for (String relativePathOfUnitToRemove : unitPathsToSearch) {
                            Package p = getPackageFromRelativePath(relativePathOfUnitToRemove);
                            if (p != null) {
                                Set<Unit> units = new HashSet<>();
                                for (Declaration d : p.getMembers()) {
                                    Unit u = d.getUnit();
                                    if (u.getRelativePath().equals(relativePathOfUnitToRemove)) {
                                        units.add(u);
                                    }
                                }
                                for (Unit u : units) {
                                    try {
                                        p.removeUnit(u);
                                        // In the future, when we are sure that we cannot add several unit objects with the 
                                        // same relative path, we can add a break.
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else {
                                System.out.println("WARNING : The package of the following binary unit ("
                                        + relativePathOfUnitToRemove + ") " + "cannot be found in module "
                                        + getNameAsString() + artifact != null
                                                ? " (artifact=" + artifact.getAbsolutePath() + ")"
                                                : "");
                            }
                        }
                    }
                    phasedUnitMap.removePhasedUnitForRelativePath(relativePathToRemove);
                }

                if (isSourceArchive()) {
                    ClosableVirtualFile sourceArchive = null;
                    try {
                        sourceArchive = moduleManager.getContext().getVfs()
                                .getFromZipFile(new File(sourceArchivePath));
                        for (String relativePathToAdd : originalUnitsToAdd) {
                            VirtualFile archiveEntry = null;
                            archiveEntry = searchInSourceArchive(relativePathToAdd, sourceArchive);

                            if (archiveEntry != null) {
                                Package pkg = getPackageFromRelativePath(relativePathToAdd);
                                ((ExternalModulePhasedUnits) phasedUnitMap).parseFile(archiveEntry,
                                        sourceArchive, pkg);
                            }
                        }
                    } catch (Exception e) {
                        StringBuilder error = new StringBuilder("Unable to read source artifact from ");
                        error.append(sourceArchive);
                        error.append("\ndue to connection error: ").append(e.getMessage());
                        throw e;
                    } finally {
                        if (sourceArchive != null) {
                            sourceArchive.close();
                        }
                    }
                }

                classesToSources = CarUtils.retrieveMappingFile(returnCarFile());
                javaImplFilesToCeylonDeclFiles = CarUtils
                        .searchCeylonFilesForJavaImplementations(classesToSources, new File(sourceArchivePath));

                originalUnitsToRemove.clear();
                originalUnitsToAdd.clear();
            }
        }
        if (isCeylonBinaryArchive() || isJavaBinaryArchive()) {
            jarPackages.clear();
            loadPackageList(new ArtifactResult() {
                @Override
                public VisibilityType visibilityType() {
                    return null;
                }

                @Override
                public String version() {
                    return null;
                }

                @Override
                public ArtifactResultType type() {
                    return null;
                }

                @Override
                public String name() {
                    return null;
                }

                @Override
                public ImportType importType() {
                    return null;
                }

                @Override
                public List<ArtifactResult> dependencies() throws RepositoryException {
                    return null;
                }

                @Override
                public File artifact() throws RepositoryException {
                    return artifact;
                }

                @Override
                public String repositoryDisplayString() {
                    return "";
                }

                @Override
                public PathFilter filter() {
                    return null;
                }

                @Override
                public Repository repository() {
                    return null;
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.ovgu.cide.export.physical.ahead.validator.JakColorCheckerJob.java

License:Open Source License

protected void processSource(ColoredSourceFile source) throws JavaModelException, CoreException {
    if (!JavaCore.isJavaLikeFileName(source.getResource().getName()))
        return;//from   ww w .ja  v  a 2 s . c  o m

    try {
        CompilationUnit ast = JDTParserWrapper.parseJavaFile(source.getResource());

        JakColorChecker colorChecker = new JakColorChecker(
                new RefactoringColorManager(source.getColorManager(), ast, source.getResource()));
        LocalVariableHelper.cacheCompilationUnit(ast);
        ast.accept(colorChecker);

        ast.accept(new LocalVariableTmp());

        markColorWarnings(source, colorChecker.getUnsupportedColorings());
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw e;

    } catch (JavaModelException e) {
        e.printStackTrace();
        throw e;

    } catch (CoreException e) {
        e.printStackTrace();
        throw e;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:net.officefloor.eclipse.classpath.ClasspathUtil.java

License:Open Source License

/**
 * Opens the class path resource.//  w ww  .j a v a2s.  com
 * 
 * @param resourcePath
 *            Path to the resource on the class path.
 * @param editor
 *            {@link AbstractOfficeFloorEditor} opening the resource.
 */
public static void openClasspathResource(String resourcePath, AbstractOfficeFloorEditor<?, ?> editor) {

    // Extensions
    final String CLASS_EXTENSION = ".class";
    final String SOURCE_EXTENSION = ".java";

    try {
        // Obtain the package and resource name
        int index = resourcePath.lastIndexOf('/');
        String packageName = (index < 0 ? "" : resourcePath.substring(0, index)).replace('/', '.');
        String resourceName = (index < 0 ? resourcePath : resourcePath.substring(index + 1)); // +1
        // to
        // skip
        // separator

        // Obtain the java project
        IJavaProject project = JavaCore.create(ProjectConfigurationContext.getProject(editor.getEditorInput()));

        // Iterate over the fragment roots searching for the file
        for (IPackageFragmentRoot root : project.getAllPackageFragmentRoots()) {

            // Attempt to obtain the package
            IPackageFragment packageFragment = root.getPackageFragment(packageName);
            if (!packageFragment.exists()) {
                continue; // must have package
            }

            // Handle if a java or class file
            if (JavaCore.isJavaLikeFileName(resourceName) || resourceName.endsWith(CLASS_EXTENSION)) {

                // Handle based on kind of fragment root
                int rootKind = root.getKind();
                switch (rootKind) {
                case IPackageFragmentRoot.K_BINARY:
                    // Binary, so ensure extension is class
                    if (resourceName.endsWith(SOURCE_EXTENSION)) {
                        resourceName = resourceName.replace(SOURCE_EXTENSION, CLASS_EXTENSION);
                    }

                    // Attempt to obtain and open the class file
                    IClassFile classFile = packageFragment.getClassFile(resourceName);
                    if (classFile != null) {
                        openEditor(editor, classFile);
                        return; // opened
                    }
                    break;

                case IPackageFragmentRoot.K_SOURCE:
                    // Source, so ensure extension is java
                    if (resourceName.endsWith(CLASS_EXTENSION)) {
                        resourceName = resourceName.replace(CLASS_EXTENSION, SOURCE_EXTENSION);
                    }

                    // Attempt to obtain the compilation unit (source file)
                    ICompilationUnit sourceFile = packageFragment.getCompilationUnit(resourceName);
                    if (sourceFile != null) {
                        openEditor(editor, sourceFile);
                        return; // opened
                    }
                    break;

                default:
                    throw new IllegalStateException("Unknown package fragment root kind: " + rootKind);
                }

            } else {
                // Not java file, so open as resource
                for (Object nonJavaResource : packageFragment.getNonJavaResources()) {
                    // Should only be opening files
                    if (nonJavaResource instanceof IFile) {
                        IFile file = (IFile) nonJavaResource;

                        // Determine if the file looking for
                        if (resourceName.equals(file.getName())) {
                            // Found file to open, so open
                            openEditor(editor, file);
                            return;
                        }
                    } else {
                        // Unknown resource type
                        throw new IllegalStateException(
                                "Unkown resource type: " + nonJavaResource.getClass().getName());
                    }
                }
            }
        }

        // Unable to open as could not find
        MessageDialog.openWarning(editor.getEditorSite().getShell(), "Open", "Could not find: " + resourcePath);

    } catch (Throwable ex) {
        // Failed to open file
        MessageDialog.openInformation(editor.getEditorSite().getShell(), "Open",
                "Failed to open '" + resourcePath + "': " + ex.getMessage());
    }
}