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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.eclipse.e4.xwt.ui.utils.ClassLoaderHelper.java

License:Open Source License

public static byte[] getClassContent(IJavaProject javaProject, String className) {
    if (javaProject == null || !javaProject.exists())
        return null;
    String resourceName = className.replace('.', '/') + ".class";
    try {//from w  ww  . j  a  v  a 2  s.  c o  m
        IPath outPath = javaProject.getProject().getLocation().removeLastSegments(1)
                .append(javaProject.getOutputLocation());
        outPath = outPath.addTrailingSeparator();
        {
            URL url = toURL(outPath.append(resourceName));
            if (url != null) {
                InputStream inputStream = url.openStream();
                byte[] content = new byte[inputStream.available()];
                inputStream.read(content);
                return content;
            }
            for (IProject project : javaProject.getProject().getReferencedProjects()) {
                if (!project.isOpen()) {
                    continue;
                }
                IJavaProject javaReferencedProject = JavaCore.create(project);
                if (javaReferencedProject.exists()) {
                    byte[] content = getClassContent(javaReferencedProject, className);
                    if (content != null) {
                        return content;
                    }
                }
            }
        }
        IType type = javaProject.findType(className);
        if (type != null && type.exists()) {
            if (type.isBinary()) {
                return type.getClassFile().getBytes();
            } else {
                IJavaProject typeProject = type.getJavaProject();
                if (!javaProject.equals(typeProject)) {
                    return getClassContent(typeProject, className);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.eclipse.e4.xwt.ui.utils.DisplayUtil.java

License:Open Source License

public static void open(IFile file) {
    if (file != null) {
        IJavaProject javaProject = JavaCore.create(file.getProject());
        if (!javaProject.exists()) {
            return;
        }//from  w w  w . ja v a2s  . co  m
        URI uri = file.getLocationURI();
        try {
            XWT.setLoadingContext(ProjectContext.getContext(javaProject));
            Object widget = XWT.load(uri.toURL());
            if (!(widget instanceof Control)) {
                throw new XWTException("Root element must be a control.");
            }
            Shell shell = ((Control) widget).getShell();
            shell.pack();
            shell.open();
            while (!shell.isDisposed())
                if (!shell.getDisplay().readAndDispatch())
                    shell.getDisplay().sleep();
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            }
            throw new RuntimeException(e);
        }
    }
}

From source file:org.eclipse.e4.xwt.ui.views.ProjectContentProvider.java

License:Open Source License

public ProjectContentProvider(IFile file) {
    URI uri = file.getLocationURI();

    IJavaProject javaProject = JavaCore.create(file.getProject());
    if (javaProject.exists()) {
        loadingContext = ProjectContext.getContext(javaProject);
    }//from w  w  w.j a v  a 2 s. c o  m
    try {
        contentURL = uri.toURL();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.edt.ide.core.utils.EclipseUtilities.java

License:Open Source License

/**
 * Adds the outputFolder as a Java source folder if the project is a Java project.
 * /* www .j  a  v  a  2s .  c o  m*/
 * @param project       The project containing the folder (used when outputFolder is a relative path)
 * @param outputFolder  The path of the folder. It may be project-relative, or workspace-relative. If workspace-relative
 *                      it should start with 'F/' for a folder or 'P/' for a project.
 * @param forceClasspathRefresh A classpath needs to be refreshed if an entry already exists for the output folder, but the folder has yet to be
 *                         created.  This can occur when a project is exported without a generation directory.
 * @throws CoreException
 */
public static void addToJavaBuildPathIfNecessary(IProject project, String outputFolder,
        boolean forceClasspathRefresh) throws CoreException {
    if (project.hasNature(JavaCore.NATURE_ID)) {
        IJavaProject javaProject = JavaCore.create(project);
        if (javaProject.exists()) {
            IClasspathEntry[] entries = javaProject.getRawClasspath();
            IPath outputFolderPath = new Path(convertFromInternalPath(outputFolder));
            boolean needToAdd = true;

            IPath fullPath = outputFolderPath.isAbsolute() ? outputFolderPath
                    : outputFolderPath.segmentCount() == 0 ? project.getFullPath()
                            : project.getFolder(outputFolderPath).getFullPath();

            for (int i = 0; i < entries.length; i++) {
                if (entries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    IPath nextPath = entries[i].getPath();
                    // JDT throws an error if you have a source folder within a source folder. We could add exclusions to support this, but
                    // for now we just won't add the folder.
                    if (nextPath.isPrefixOf(fullPath) || fullPath.isPrefixOf(nextPath)) {
                        needToAdd = false;
                        break;
                    }
                }
            }

            if (needToAdd) {
                IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];
                System.arraycopy(entries, 0, newEntries, 0, entries.length);
                newEntries[newEntries.length - 1] = JavaCore.newSourceEntry(fullPath);
                javaProject.setRawClasspath(newEntries, null);
            }

            if (!needToAdd && forceClasspathRefresh) {
                javaProject.setRawClasspath(javaProject.readRawClasspath(), javaProject.readOutputLocation(),
                        null);
            }
        }
    }
}

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

License:Open Source License

public static void getJavaSourceFolders(IProject sourceProject, List<IResource> resources)
        throws CoreException, JavaModelException {

    //for the source project get all of it's Java source folders
    //and include java folders in this project classpath
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IJavaProject javaProject = JavaCore.create(sourceProject);
    if (PlatformUI.isWorkbenchRunning() && javaProject.exists() && javaProject.isOpen()
            || !PlatformUI.isWorkbenchRunning() && javaProject.exists()) {
        IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
        if (entries != null && entries.length > 0) {
            for (int idx = entries.length - 1; idx >= 0; idx--) {
                if (entries[idx].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    IResource element = root.findMember(entries[idx].getPath());

                    if (element != null && element.exists()) {
                        resources.add(element);
                    }/*from   ww w  .j a  v  a  2 s  .  c  o m*/
                }
            }
        }
    }
}

From source file:org.eclipse.emf.ecore.xcore.ui.container.XcoreJavaProjectsState.java

License:Open Source License

@Override
protected String doInitHandle(URI uri) {
    String result = getJavaProjectsHelper().initHandle(uri);
    if (result == null && uri.isPlatformResource() && uri.segmentCount() > 1) {
        IProject project = getWorkspaceRoot().getProject(uri.segment(1));
        IJavaProject javaProject = JavaCore.create(project);
        result = javaProject.exists() ? javaProject.getHandleIdentifier() : project.getName();
    }// www . j av  a  2  s  .  c om
    return result;
}

From source file:org.eclipse.emf.editor.provider.ClasspathUriResolver.java

License:Open Source License

private URI findResourceInWorkspace(IJavaProject javaProject, URI classpathUri)
        throws JavaModelException, CoreException {
    Path fullPath = new Path(classpathUri.path());
    String projectRelativePath = fullPath.toString();
    if (javaProject.exists()) {
        IPackageFragmentRoot[] allPackageFragmentRoots = javaProject.getAllPackageFragmentRoots();
        for (IPackageFragmentRoot packageFragmentRoot : allPackageFragmentRoots) {
            IResource correspondingResource = packageFragmentRoot.getCorrespondingResource();
            if (correspondingResource != null) {
                if (correspondingResource instanceof IFile) {
                    // jar file
                    JarPackageFragmentRoot jarPackageFragmentRoot = (JarPackageFragmentRoot) JavaCore
                            .createJarPackageFragmentRootFrom((IFile) correspondingResource);
                    if (jarPackageFragmentRoot != null) {
                        ZipFile zipFile = jarPackageFragmentRoot.getJar();
                        if (zipFile != null) {
                            ZipEntry zipEntry = zipFile.getEntry(projectRelativePath.substring(1));
                            if (zipEntry != null) {
                                return URI.createURI("jar:" + "platform:/resource"
                                        + correspondingResource.getFullPath() + "!" + projectRelativePath,
                                        true);
                            }/*from  w  ww . j  av  a 2 s  . c  om*/
                        }
                    }
                } else {
                    // plain file
                    IFolder rootFolder = (IFolder) correspondingResource;
                    IResource modelFile = rootFolder.findMember(projectRelativePath);
                    if (modelFile != null && modelFile.exists() && modelFile instanceof IFile) {
                        URI platformResourceUri = URI
                                .createPlatformResourceURI(modelFile.getFullPath().toString(), true);
                        return platformResourceUri;
                    }
                }
            }
        }
    }
    return classpathUri;
}

From source file:org.eclipse.emf.mwe.internal.ui.debug.sourcelookup.SourceLookupUtil.java

License:Open Source License

/**
 * Translates the given runtime classpath entries into associated source containers.
 *//*from  www  . j a va2  s.c  o m*/
public static ISourceContainer[] translate(final IRuntimeClasspathEntry[] entries) {
    List<ISourceContainer> containers = new ArrayList<ISourceContainer>(entries.length);
    for (IRuntimeClasspathEntry entry : entries) {
        ISourceContainer container = null;
        switch (entry.getType()) {
        case IRuntimeClasspathEntry.ARCHIVE:
            IPackageFragmentRoot root = getPackageFragmentRoot(entry);
            if (root == null) {
                String path = entry.getLocation();
                File file = new File(path);
                if (file.isDirectory()) {
                    IResource resource = entry.getResource();
                    if (resource instanceof IContainer) {
                        container = new FolderSourceContainer((IContainer) resource, false);
                    } else {
                        container = new DirectorySourceContainer(file, false);
                    }
                } else {
                    container = new ExternalArchiveSourceContainer(path, true);
                }
            } else {
                container = new PackageFragmentRootContainer(root);
            }
            break;
        case IRuntimeClasspathEntry.PROJECT:
            IResource resource = entry.getResource();
            if ((resource != null) && (resource.getType() == IResource.PROJECT)) {
                IJavaProject javaProject = JavaCore.create((IProject) resource);
                if (javaProject.exists()) {
                    container = new SourceFolderSourceContainer(javaProject);
                } else if (resource.exists()) {
                    container = new ProjectSourceContainer((IProject) resource, false);
                }
            }
            break;
        default:
            // no other classpath types are valid in a resolved path
            break;
        }
        if ((container != null) && !containers.contains(container)) {
            containers.add(container);
        }
    }
    return containers.toArray(new ISourceContainer[containers.size()]);
}

From source file:org.eclipse.emf.mwe.internal.ui.debug.sourcelookup.SourceLookupUtil.java

License:Open Source License

private static IPackageFragmentRoot getPackageFragmentRoot(final IRuntimeClasspathEntry entry) {
    IResource resource = entry.getResource();

    if (resource != null) {
        // our own project jars...
        IProject project = resource.getProject();
        IJavaProject jp = JavaCore.create(project);
        if (project.isOpen() && jp.exists()) {
            IPackageFragmentRoot root = jp.getPackageFragmentRoot(resource);
            return root;
        }//from  w  w w  .  j a va 2s .  c o  m
    }

    if (model == null) {
        model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
    }

    // ... or external jars, that are registered in one of the open projects at runtime
    IPath reqPath = (resource == null ? new Path(entry.getLocation()) : entry.getPath());
    try {
        for (IJavaProject jp : model.getJavaProjects()) {
            if (jp.getProject().isOpen()) {
                for (IPackageFragmentRoot root : jp.getPackageFragmentRoots()) {
                    if (root.isExternal() && root.getPath().equals(reqPath)) {
                        return root;
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        Activator.logError(e); // should not occur
    }
    return null;
}

From source file:org.eclipse.examples.slideshow.jdt.JavaSourceStreamHandlerService.java

License:Open Source License

@Override
public URLConnection openConnection(URL u) throws IOException {
    return new URLConnection(u) {
        private Map<String, List<String>> headers;

        @Override/* w  w w  . j av a  2 s.com*/
        public void connect() throws IOException {
            headers = new HashMap<String, List<String>>();
            // TODO Consider adding additional MIME types.
            headers.put("content-type", Collections.singletonList("text/x-java-source"));
        }

        @Override
        public Map<String, List<String>> getHeaderFields() {
            return headers;
        }

        @Override
        public Object getContent(Class[] classes) throws IOException {
            for (int index = 0; index < classes.length; index++) {
                if (classes[index] == String.class)
                    return getContent();
            }
            throw new UnknownServiceException();
        }

        // TODO This isn't in the right place. At least I don't think it is.
        // TODO Returning error messages intended for the end user in the exception is convenient, but is it correct?
        // TODO Probably better to return a Document containing formatting
        @Override
        public InputStream getInputStream() throws IOException {
            return new StringBufferInputStream(getSource());
        }

        private String getSource() throws IOException {
            String projectName = getURL().getHost();
            if (projectName.length() == 0)
                throw new IOException("Project name must be provided!");

            IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
            if (!project.exists())
                throw new IOException(String.format("Project \"%1$s\"not found!", projectName));

            IJavaProject javaProject = JavaCore.create(project);
            if (!javaProject.exists())
                throw new IOException(String.format("Project \"%1$s\" is not a Java Project!", projectName));

            IType type = null;
            // The path will include a preceding slash; we strip it.
            if (getURL().getPath().length() <= 1)
                throw new IOException("Type name must be provided!");
            String typeName = getURL().getPath().substring(1);
            try {
                type = javaProject.findType(typeName);
            } catch (JavaModelException e) {
                // We've covered off most of the potential problems spots, this shouldn't happen.
                throw new IOException(e.getMessage());
            }
            if (type == null || !type.exists())
                throw new IOException(String.format("Type \"%1$s\" not found!", typeName));

            if (getURL().getRef() == null)
                try {
                    return type.getSource();
                } catch (JavaModelException e) {
                    throw new IOException(e.getMessage());
                }

            // separate the method name from the parameters.
            Matcher matcher = Pattern.compile("([^\\(]*)\\((.*)\\)").matcher(getURL().getRef());

            if (!matcher.matches()) {
                throw new IOException(String.format(
                        "Method format, \"%1$s\", incorrect, method([parameter [, parameter*]]) expected!",
                        getURL().getRef()));
            }

            String methodName = matcher.group(1);

            // Splitting returns an array containing a single empty string if the receiver is empty. See Bug 272381.
            String allParameters = matcher.group(2);
            String[] parameters = "".equals(allParameters.trim()) ? new String[0] : allParameters.split(",");

            // TODO permit user to enter user-sensible parameters, e.g. "String[]" instead of "[QString;"
            IMethod method = type.getMethod(methodName, parameters);
            if (!method.exists())
                throw new IOException(String.format("Method \"%1$s\" not found!", methodName));
            try {
                return getSourceCodeFor(method);
            } catch (JavaModelException e) {
                throw new IOException(e.getMessage());
            } catch (MalformedTreeException e) {
                throw new IOException(e.getMessage());
            } catch (BadLocationException e) {
                throw new IOException(e.getMessage());
            }
        }

        private String getSourceCodeFor(IMethod method) throws JavaModelException, BadLocationException {
            String source = method.getSource();
            TextEdit format = ToolFactory.createCodeFormatter(null).format(
                    CodeFormatter.K_UNKNOWN + CodeFormatter.F_INCLUDE_COMMENTS, source, 0, source.length(), 0,
                    null);
            Document document = new Document();
            document.set(source);
            format.apply(document);
            return document.get();
        }
    };
}