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

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

Introduction

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

Prototype

IProject getProject();

Source Link

Document

Returns the IProject on which this IJavaProject was created.

Usage

From source file:apet.utils.ClasspathUtils.java

License:Open Source License

/**
 * Returns the Eclipse Project class loader using project build path
 * @param javaProject Eclipse Java Project
 * @return A class loader using project build path
 * @throws Exception If the project is no valid
 *///from w w  w  . j ava  2  s . c  om
public static ClassLoader getProjectClassLoader(IJavaProject javaProject) throws Exception {
    IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
    String wsPath = javaProject.getProject().getLocation().toPortableString();
    String firstEntryLocation = javaProject.getPath().toPortableString();
    int idx = wsPath.indexOf(firstEntryLocation);

    URL[] urls = null;
    int i = 0;

    //System.out.println("ClassLoader " + wsPath);
    //System.out.println("ClassLoader " + firstEntryLocation);

    String output = javaProject.getOutputLocation().toPortableString();
    urls = new URL[entries.length + 1];

    if (idx != -1) {
        wsPath = wsPath.substring(0, idx);
    } else {
        output = output.substring(firstEntryLocation.length());
    }
    urls[i++] = new File(wsPath + output).toURL();

    //System.out.println("ClassLoader " + output);

    String fullPath = null;

    for (IClasspathEntry entry : entries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            IResource project = ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath());
            String projectPath = JavaCore.create(project.getProject()).getOutputLocation().toPortableString();
            fullPath = wsPath + projectPath;
        } else {
            Object resource = JavaModel.getTarget(entry.getPath(), true);

            if (resource instanceof IResource) {
                IResource iFile = (IResource) resource;
                fullPath = iFile.getLocation().toPortableString();
            } else if (resource instanceof File) {
                File file = (File) resource;
                fullPath = file.getAbsolutePath();
            }
        }

        urls[i++] = new File(fullPath).toURL();
        //System.out.println(fullPath);
    }

    URLClassLoader classLoader = new URLClassLoader(urls, String.class.getClassLoader());

    /*for (int j = 0; j < urls.length; j ++) {
       System.out.println(urls[j]);
    }*/

    return classLoader;
}

From source file:apet.utils.ClasspathUtils.java

License:Open Source License

/**
 * Returns a String with all libraries defined in build path
 * @param javaProject Eclipse Java Project
 * @return a String with all libraries defined in build path
 * @throws Exception If the project is no valid
 *//*  ww w  . jav a2  s  .  c o m*/
public static String getStringClasspath(IJavaProject javaProject) throws Exception {

    IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
    String wsPath = javaProject.getProject().getLocation().toPortableString();
    String firstEntryLocation = javaProject.getPath().toPortableString();
    int idx = wsPath.indexOf(firstEntryLocation);

    String[] urls = new String[entries.length + 1];
    String fullPath = null;
    int i = 0;
    String output = javaProject.getOutputLocation().toPortableString();

    if (idx != -1) {
        wsPath = wsPath.substring(0, idx);
    } else {
        output = output.substring(firstEntryLocation.length());
    }
    urls[i++] = wsPath + output;

    for (IClasspathEntry entry : entries) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
            IResource project = ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath());
            String projectPath = JavaCore.create(project.getProject()).getOutputLocation().toPortableString();
            fullPath = wsPath + projectPath;
        } else {
            Object resource = JavaModel.getTarget(entry.getPath(), true);

            if (resource instanceof IResource) {
                IResource iFile = (IResource) resource;
                fullPath = iFile.getLocation().toPortableString();
            } else if (resource instanceof File) {
                File file = (File) resource;
                fullPath = file.getAbsolutePath();
            }
        }

        urls[i++] = fullPath;
    }

    StringBuffer buffer = new StringBuffer();
    for (String url : urls) {
        buffer.append(url);
        buffer.append(":");
    }

    return buffer.toString().substring(0, buffer.length() - 1);

}

From source file:ar.com.tadp.xml.rinzo.jdt.JDTUtils.java

License:Open Source License

public static boolean isJavaProject(IJavaProject project) {
    try {/*from  ww  w .j a v a 2  s.c  o  m*/
        return project != null && project.getProject().getNature(JAVA_NATURE_ID) != null;
    } catch (CoreException e) {
        return false;
    }
}

From source file:at.bestsolution.efxclipse.tooling.fxgraph.ui.internal.FXMLProviderAdapter.java

License:Open Source License

@Override
public List<URL> getPreviewClasspath() {
    return editor.getDocument().readOnly(new IUnitOfWork<List<URL>, XtextResource>() {

        @Override//from   w ww  .  j  a  va  2s.co m
        public List<URL> exec(XtextResource resource) throws Exception {
            List<URL> extraPaths = new ArrayList<URL>();
            EList<EObject> contents = resource.getContents();
            if (!contents.isEmpty()) {
                URI uri = resource.getURI();
                IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(uri.segment(1));
                IJavaProject jp = JavaCore.create(p);
                EObject rootObject = contents.get(0);
                if (rootObject instanceof Model) {
                    ComponentDefinition def = ((Model) rootObject).getComponentDef();

                    for (String path : def.getPreviewClasspathEntries()) {
                        try {
                            URI cpUri = URI.createURI(path);
                            if (cpUri.isPlatformResource()) {
                                if (cpUri.lastSegment().equals("*")) {
                                    cpUri = cpUri.trimSegments(1);
                                    Path cpPath = new Path(cpUri.toPlatformString(true));
                                    IWorkspaceRoot root = jp.getProject().getWorkspace().getRoot();
                                    IFolder f = root.getFolder(cpPath);
                                    if (f.exists()) {
                                        for (IResource r : f.members()) {
                                            IFile jarFile = (IFile) r;
                                            if (r instanceof IFile) {
                                                if ("jar".equals(jarFile.getFileExtension())) {
                                                    extraPaths.add(
                                                            jarFile.getLocation().toFile().toURI().toURL());
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    Path cpPath = new Path(cpUri.toPlatformString(true));
                                    IWorkspaceRoot root = jp.getProject().getWorkspace().getRoot();
                                    IFile jarFile = root.getFile(cpPath);
                                    if (jarFile.exists()) {
                                        try {
                                            extraPaths.add(jarFile.getLocation().toFile().toURI().toURL());
                                        } catch (MalformedURLException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            } else if (cpUri.isFile()) {
                                if (cpUri.toFileString().endsWith("*")) {
                                    File ioFile = new File(cpUri.toFileString()).getParentFile();
                                    if (ioFile.exists()) {
                                        try {
                                            for (File jarFile : ioFile.listFiles()) {
                                                if (jarFile.getName().endsWith(".jar")) {
                                                    extraPaths.add(jarFile.toURI().toURL());
                                                }
                                            }
                                        } catch (MalformedURLException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                                    }
                                } else {
                                    File ioFile = new File(cpUri.toFileString());
                                    if (ioFile.exists()) {
                                        try {
                                            extraPaths.add(ioFile.toURI().toURL());
                                        } catch (MalformedURLException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                    }
                }
            }

            return extraPaths;
        }

    });
}

From source file:at.bestsolution.efxclipse.tooling.jdt.ui.internal.wizard.NewJavaFXProjectWizardPageTwo.java

License:Open Source License

/**
 * Evaluates the new build path and output folder according to the settings on the first page.
 * The resulting build path is set by calling {@link #init(IJavaProject, IPath, IClasspathEntry[], boolean)}.
 * Clients can override this method.// w  w  w.j  av a  2  s . co m
 *
 * @param javaProject the new project which is already created when this method is called.
 * @param monitor the progress monitor
 * @throws CoreException thrown when initializing the build path failed
 */
protected void initializeBuildPath(IJavaProject javaProject, IProgressMonitor monitor) throws CoreException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }
    monitor.beginTask(NewWizardMessages.NewJavaProjectWizardPageTwo_monitor_init_build_path, 2);

    try {
        IClasspathEntry[] entries = null;
        IPath outputLocation = null;
        IProject project = javaProject.getProject();

        if (fKeepContent) {
            if (!project.getFile(FILENAME_CLASSPATH).exists()) {
                final ClassPathDetector detector = new ClassPathDetector(fCurrProject,
                        new SubProgressMonitor(monitor, 2));
                entries = detector.getClasspath();
                outputLocation = detector.getOutputLocation();
                if (entries.length == 0)
                    entries = null;
            } else {
                monitor.worked(2);
            }
        } else {
            List<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            IWorkspaceRoot root = project.getWorkspace().getRoot();

            IClasspathEntry[] sourceClasspathEntries = fFirstPage.getSourceClasspathEntries();
            for (int i = 0; i < sourceClasspathEntries.length; i++) {
                IPath path = sourceClasspathEntries[i].getPath();
                if (path.segmentCount() > 1) {
                    IFolder folder = root.getFolder(path);
                    CoreUtility.createFolder(folder, true, true, new SubProgressMonitor(monitor, 1));
                }
                cpEntries.add(sourceClasspathEntries[i]);
            }

            cpEntries.addAll(Arrays.asList(fFirstPage.getDefaultClasspathEntries()));

            entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);

            outputLocation = fFirstPage.getOutputLocation();
            if (outputLocation.segmentCount() > 1) {
                IFolder folder = root.getFolder(outputLocation);
                CoreUtility.createDerivedFolder(folder, true, true, new SubProgressMonitor(monitor, 1));
            }
        }
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }

        init(javaProject, outputLocation, entries, false);

        IProjectDescription projectDescription = project.getDescription();
        String[] ids = projectDescription.getNatureIds();
        String[] newIds = new String[ids.length + 1];
        System.arraycopy(ids, 0, newIds, 0, ids.length);
        newIds[ids.length] = "org.eclipse.xtext.ui.shared.xtextNature";
        projectDescription.setNatureIds(newIds);
        project.setDescription(projectDescription, null);
    } finally {
        monitor.done();
    }
}

From source file:at.bestsolution.efxclipse.tooling.ui.preview.LivePreviewSynchronizer.java

License:Open Source License

private List<URL> calculateProjectClasspath(IJavaProject jp) {
    HashSet<IPath> outputPath = new HashSet<IPath>();
    HashSet<IPath> libraries = new HashSet<IPath>();
    resolveDataProject(jp, outputPath, libraries);

    IWorkspaceRoot root = jp.getProject().getWorkspace().getRoot();

    List<URL> rv = new ArrayList<URL>();
    for (IPath out : outputPath) {
        IFolder f = root.getFolder(out);
        if (f.exists()) {
            try {
                rv.add(f.getLocation().toFile().toURI().toURL());
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();/*from  ww w. java 2  s .c  o m*/
            }
        }
    }

    for (IPath lib : libraries) {
        IFile f = root.getFile(lib);
        if (f.exists()) {
            try {
                rv.add(f.getLocation().toFile().toURI().toURL());
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    return rv;
}

From source file:at.bestsolution.efxclipse.tooling.ui.util.RelativeFileLocator.java

License:Open Source License

public static File locateFile(URI uri, String filePath) {
    IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(uri.segment(1));
    IJavaProject jp = JavaCore.create(p);

    // Absolute to project
    if (filePath.startsWith("/")) {
        filePath = filePath.substring(1); // Remove the leading /
        IFile f = p.getFile(filePath);/*from w  w w  .ja v  a2  s.  c o  m*/
        if (f.exists()) {
            return f.getLocation().toFile().getAbsoluteFile();
        } else if (jp != null) {
            try {
                for (IPackageFragmentRoot r : jp.getPackageFragmentRoots()) {
                    if (r.isArchive()) {
                        //TODO We should allow to load styles from the referenced jars
                    } else if (r.getResource() instanceof IFolder) {
                        IFolder folder = (IFolder) r.getResource();
                        if (folder.exists()) {
                            f = folder.getFile(filePath);
                            if (f.exists()) {
                                return f.getLocation().toFile().getAbsoluteFile();
                            }
                        }
                    }
                }
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {
        URI fileUri = null;

        try {
            fileUri = URI.createURI(filePath);
        } catch (Exception e) {
            // TODO: handle exception
        }

        if (fileUri != null && fileUri.isPlatformResource()) {
            Path path = new Path(fileUri.toPlatformString(true));
            IWorkspaceRoot root = jp.getProject().getWorkspace().getRoot();
            IFile file = root.getFile(path);
            if (file.exists()) {
                return file.getLocation().toFile().getAbsoluteFile();
            }
        } else {
            IPath path = null;
            for (int i = 2; i < uri.segmentCount() - 1; i++) {
                if (path == null) {
                    path = new Path(uri.segment(i));
                } else {
                    path = path.append(uri.segment(i));
                }
            }

            if (path != null) {
                IFile f = p.getFile(path.append(filePath));
                if (f.exists()) {
                    return f.getLocation().toFile().getAbsoluteFile();
                }
            }
        }
    }

    return null;
}

From source file:at.bestsolution.efxclipse.tooling.ui.wizards.AbstractHtmlElementPage.java

License:Open Source License

private IPackageFragmentRoot choosePackageRoot() {
    IJavaElement initElement = clazz.getFragmentRoot();
    Class<?>[] acceptedClasses = new Class<?>[] { IPackageFragmentRoot.class, IJavaProject.class };
    TypedElementSelectionValidator validator = new TypedElementSelectionValidator(acceptedClasses, false) {
        public boolean isSelectedValid(Object element) {
            try {
                if (element instanceof IJavaProject) {
                    IJavaProject jproject = (IJavaProject) element;
                    IPath path = jproject.getProject().getFullPath();
                    return (jproject.findPackageFragmentRoot(path) != null);
                } else if (element instanceof IPackageFragmentRoot) {
                    return (((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE);
                }/*from   w  w  w.  j  a va2  s  .  c  o  m*/
                return true;
            } catch (JavaModelException e) {
                JavaPlugin.log(e.getStatus()); // just log, no UI in validation
            }
            return false;
        }
    };

    acceptedClasses = new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class };
    ViewerFilter filter = new TypedViewerFilter(acceptedClasses) {
        public boolean select(Viewer viewer, Object parent, Object element) {
            if (element instanceof IPackageFragmentRoot) {
                try {
                    return (((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE);
                } catch (JavaModelException e) {
                    JavaPlugin.log(e.getStatus()); // just log, no UI in validation
                    return false;
                }
            }
            return super.select(viewer, parent, element);
        }
    };

    StandardJavaElementContentProvider provider = new StandardJavaElementContentProvider();
    ILabelProvider labelProvider = new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
    dialog.setValidator(validator);
    dialog.setComparator(new JavaElementComparator());
    dialog.setTitle(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_title);
    dialog.setMessage(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_description);
    dialog.addFilter(filter);
    dialog.setInput(JavaCore.create(fWorkspaceRoot));
    dialog.setInitialSelection(initElement);
    dialog.setHelpAvailable(false);

    if (dialog.open() == Window.OK) {
        Object element = dialog.getFirstResult();
        if (element instanceof IJavaProject) {
            IJavaProject jproject = (IJavaProject) element;
            return jproject.getPackageFragmentRoot(jproject.getProject());
        } else if (element instanceof IPackageFragmentRoot) {
            return (IPackageFragmentRoot) element;
        }
        return null;
    }
    return null;
}

From source file:at.bestsolution.fxide.jdt.corext.javadoc.JavaDocLocations.java

License:Open Source License

public static URL getProjectJavadocLocation(IJavaProject project) {
    if (!project.getProject().isAccessible()) {
        return null;
    }/* w ww .  jav a  2  s  .  co  m*/
    try {
        String prop = project.getProject().getPersistentProperty(PROJECT_JAVADOC);
        if (prop == null) {
            return null;
        }
        return parseURL(prop);
    } catch (CoreException e) {
        //TODO
        e.printStackTrace();
    }
    return null;
}

From source file:at.bestsolution.javafx.ide.jdt.internal.jdt.CPListElement.java

License:Open Source License

public static boolean isProjectSourceFolder(CPListElement[] existing, IJavaProject project) {
    IPath projPath = project.getProject().getFullPath();
    for (int i = 0; i < existing.length; i++) {
        IClasspathEntry curr = existing[i].getClasspathEntry();
        if (curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            if (projPath.equals(curr.getPath())) {
                return true;
            }//  w  ww.  ja  v a  2 s.c o  m
        }
    }
    return false;
}