Example usage for org.eclipse.jdt.core IPackageFragmentRoot getPath

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getPath

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot getPath.

Prototype

IPath getPath();

Source Link

Document

Returns the path to the innermost resource enclosing this element.

Usage

From source file:org.maven.ide.eclipse.actions.DownloadSourcesAction.java

License:Apache License

public void run(IAction action) {
    IPackageFragmentRoot root = (IPackageFragmentRoot) this.selection.getFirstElement();

    IJavaElement parent = root.getParent();
    if (parent instanceof IJavaProject) {
        IJavaProject project = (IJavaProject) parent;
        try {/*from ww  w  .  j a va  2  s .  com*/
            IClasspathEntry classpathEntry = root.getRawClasspathEntry();
            IClasspathContainer classpathContainer = JavaCore.getClasspathContainer(classpathEntry.getPath(),
                    project);
            IClasspathEntry[] classpathEntries = classpathContainer.getClasspathEntries();
            for (int i = 0; i < classpathEntries.length; i++) {
                IClasspathEntry entry = classpathEntries[i];
                if (entry.getPath().equals(root.getPath())) {
                    String actionDefinitionId = action.getActionDefinitionId();
                    String id = action.getId();
                    System.err.println("### DownloadSourcesAction.run()");

                }
            }
        } catch (JavaModelException ex) {
            //
        }
    }
}

From source file:org.nuxeo.ide.sdk.deploy.Deployment.java

License:Open Source License

protected void copyCompilationUnit(Set<String> commands, IPackageFragmentRoot root, ICompilationUnit unit)
        throws JavaModelException, CoreException {
    IJavaProject java = (IJavaProject) root.getParent();
    String type = unitOutput(unit);
    IFolder nxdataFolder = nxdataFolder(java).getFolder(type);
    IProject project = java.getProject();
    IPath outputLocation = java.getOutputLocation();
    IPath path = unit.getPath().removeFirstSegments(root.getPath().segmentCount()).removeLastSegments(1);
    path = path.append(//from  w  w w . ja  v  a2s  .  co m
            org.eclipse.jdt.internal.core.util.Util.getNameWithoutJavaLikeExtension(unit.getElementName())
                    + ".class"); //$NON-NLS-1$
    IContainer container = (IContainer) project.getWorkspace().getRoot().findMember(outputLocation);
    IResource dotClassMember = container.findMember(path);
    if (dotClassMember == null) {
        SDKPlugin.log(IStatus.ERROR,
                "Cannot find binary class " + path + " in project " + java.getElementName());
        return;
    }

    IFile outputFile = nxdataFolder.getFile(path);
    mkdirs((IFolder) outputFile.getParent(), new NullProgressMonitor());
    dotClassMember.copy(outputFile.getFullPath(), IResource.HIDDEN | IResource.DERIVED,
            new NullProgressMonitor());
    commands.add(type + ":" + nxdataFolder.getLocation().toOSString());
}

From source file:org.nuxeo.ide.sdk.java.ProjectDeployer.java

License:Open Source License

protected void moveSeamCompilationUnit(IPackageFragmentRoot root, ICompilationUnit unit,
        IProgressMonitor monitor) throws JavaModelException, CoreException {
    if (!isSeam(unit)) {
        return;/*from w w w .ja  va2 s .  c  o  m*/
    }
    IPath outputLocation = root.getRawClasspathEntry().getOutputLocation();
    if (outputLocation == null) {
        outputLocation = project.getOutputLocation();
    }
    IPath path = unit.getPath().removeFirstSegments(root.getPath().segmentCount()).removeLastSegments(1);
    path = path.append(
            org.eclipse.jdt.internal.core.util.Util.getNameWithoutJavaLikeExtension(unit.getElementName())
                    + ".class");
    IResource mainMember = mainFolder.findMember(path);
    if (mainMember == null) {
        throw new Error("Cannot find binary class " + path + " in project " + project.getElementName());
    }
    IResource seamMember = seamFolder.findMember(path);
    if (seamMember != null) {
        seamMember.delete(true, monitor);
    }
    seamMember = seamFolder.getFile(path);
    mkdirs((IFolder) seamMember.getParent(), monitor);
    mainMember.move(seamMember.getFullPath(), IResource.FORCE | IResource.HIDDEN | IResource.DERIVED, monitor);
}

From source file:org.nuxeo.ide.sdk.server.ui.ExportProjectJar.java

License:Open Source License

protected Object[] collectElementsToExport(IProject project) throws JavaModelException {
    IJavaProject jp = JavaCore.create(project);
    ArrayList<Object> result = new ArrayList<Object>();
    // IFolder folder = project.getFolder("src/main/java");
    // if (folder.exists()) {
    // result.add(jp.getPackageFragmentRoot(folder));
    // }/*  w  w w . ja va 2  s.  c o m*/
    // folder = project.getFolder("src/main/resources");
    // if (folder.exists()) {
    // result.add(jp.getPackageFragmentRoot(folder));
    // }
    // return result;
    IFolder testSrc = project.getFolder("src/test");
    IPath test = testSrc.exists() ? testSrc.getFullPath() : null;
    IPackageFragmentRoot[] roots = jp.getPackageFragmentRoots();
    for (IPackageFragmentRoot root : roots) {
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
            if (test == null || !test.isPrefixOf(root.getPath())) {
                result.add(root);
            }
        }
    }
    return result.toArray(new Object[result.size()]);
}

From source file:org.obeonetwork.jar2uml.ui.handlers.JDTJarArtifactHandler.java

License:Open Source License

/**
 * {@inheritDoc}/*from w w  w  . j  av  a  2  s. c om*/
 * 
 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection selection = HandlerUtil.getCurrentSelection(event);

    if (!selection.isEmpty() && selection instanceof TreeSelection) {
        TreeSelection treeSelection = (TreeSelection) selection;
        TreePath[] paths = treeSelection.getPaths();
        if (paths.length > 0) {
            Object rootSegment = paths[0].getFirstSegment();
            if (rootSegment instanceof IProject || rootSegment instanceof IJavaProject) {
                IProject project;
                if (rootSegment instanceof IProject) {
                    project = (IProject) rootSegment;
                } else {
                    project = ((IJavaProject) rootSegment).getProject();
                }
                Set<File> files = new HashSet<File>();
                for (Object item : treeSelection.toList()) {
                    if (item instanceof IPackageFragmentRoot) {
                        IPackageFragmentRoot jarFrag = (IPackageFragmentRoot) item;
                        files.add(jarFrag.getPath().toFile());
                    }
                }
                Job jars2uml = new JarConverterJob(project, "model", files);
                jars2uml.schedule();
            }
        }
    }

    return null;
}

From source file:org.occiware.clouddesigner.occi.gen.connector.ui.wizards.NewConnectorWizard.java

License:Open Source License

private void createConnectorJavaProject(String connectorProjectName, String extensionScheme,
        IProgressMonitor monitor) throws CoreException {
    // Get the file containing the OCCI extension.
    String extensionFile = OCCIRegistry.getInstance().getFileURI(extensionScheme);

    // This connector project will require the bundle containing the OCCI extension.
    // Warning extensionFile must be a platform URI (plugin or resource).
    String tmp = extensionFile.substring("platform:/".length());
    tmp = tmp.substring(tmp.indexOf('/') + 1);
    String requireBundle = tmp.substring(0, tmp.indexOf('/'));
    // FIXME we suppose that the project name is equals to the bundle name. 
    IProject requireProject = ResourcesPlugin.getWorkspace().getRoot().getProject(requireBundle);

    // See https://sdqweb.ipd.kit.edu/wiki/JDT_Tutorial:_Creating_Eclipse_Java_Projects_Programmatically

    // Create an Eclipse project.
    IProject connectorProject = ResourcesPlugin.getWorkspace().getRoot().getProject(connectorProjectName);
    connectorProject.create(null);//from w  ww  .  j  a  v  a 2s.c  om
    connectorProject.open(null);

    // Because we need a java project, we have to set the Java nature to the created project:
    IProjectDescription description = connectorProject.getDescription();
    description.setNatureIds(new String[] { JavaCore.NATURE_ID });
    connectorProject.setDescription(description, null);

    // Now we can create our Java project
    IJavaProject javaProject = JavaCore.create(connectorProject);

    // However, it's not enough if we want to add Java source code to the project. We have to set the Java build path:

    // (1) We first specify the output location of the compiler (the bin folder):
    IFolder binFolder = connectorProject.getFolder("bin");
    binFolder.create(false, true, null);
    javaProject.setOutputLocation(binFolder.getFullPath(), null);

    // (2) Define the class path entries.
    IClasspathEntry[] entries = new IClasspathEntry[(requireProject.exists()) ? 3 : 2];

    // Add JRE System Library.
    entries[0] = JavaRuntime.getDefaultJREContainerEntry();

    // (3) We have not yet the source folder created:
    IFolder sourceFolder = connectorProject.getFolder("src");
    sourceFolder.create(false, true, null);

    // (4) Now the created source folder should be added to the class entries of the project, otherwise compilation will fail:
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder);
    entries[1] = JavaCore.newSourceEntry(root.getPath());

    // Add the extension project.
    if (requireProject.exists()) {
        entries[2] = JavaCore.newSourceEntry(requireProject.getFullPath());
    }

    // (5) Set the Java build path.
    javaProject.setRawClasspath(entries, null);

    // Convert this project to a plugin project.
    try {
        new ConvertProjectToPluginOperation(new IProject[] { connectorProject }, false).run(monitor);
    } catch (InvocationTargetException | InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // Generate META-INF/MANIFEST.MF
    IFile manifest = PDEProject.getManifest(connectorProject);
    String manifestContent = "Manifest-Version: 1.0\n" + "Bundle-ManifestVersion: 2\n" + "Bundle-Name: "
            + connectorProjectName + "\n" + "Bundle-SymbolicName: " + connectorProjectName
            + ";singleton:=true\n" + "Bundle-Version: 0.1.0.qualifier\n" + "Bundle-ClassPath: .\n"
            + "Bundle-Vendor: OCCIware\n" +
            //         "Bundle-Localization: plugin\n" + // FIXME generate plugin.properties
            "Bundle-RequiredExecutionEnvironment: JavaSE-1.7\n" + "Bundle-ActivationPolicy: lazy\n"
            + "Require-Bundle: org.slf4j.api,\n" + " org.occiware.clouddesigner.occi,\n" + " " + requireBundle
            + "\n" + "Export-Package: " + connectorProjectName + "\n";
    manifest.setContents(new ByteArrayInputStream(manifestContent.getBytes()), true, false, monitor);

    // Generate build.properties
    IFile build = PDEProject.getBuildProperties(connectorProject);
    String buildContent = "# Copyright (c) 2016 Inria\n" + "#\n"
            + "# All rights reserved. This program and the accompanying materials\n"
            + "# are made available under the terms of the Eclipse Public License v1.0\n"
            + "# which accompanies this distribution, and is available at\n"
            + "# http://www.eclipse.org/legal/epl-v10.html\n" + "#\n" + "# Contributors:\n"
            + "# - Philippe Merle <philippe.merle@inria.fr>\n" + "#\n" + "\n" + "source.. = src/\n"
            + "output.. = bin/\n" + "bin.includes = META-INF/, plugin.xml, .\n";
    build.setContents(new ByteArrayInputStream(buildContent.getBytes()), true, false, monitor);

    // Generate plugin.xml
    IFile pluginXML = PDEProject.getPluginXml(connectorProject);
    String pluginContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<?eclipse version=\"3.0\"?>\n"
            + "<!--\n" + "  Copyright (c) 2016 Inria\n" + "\n"
            + "  All rights reserved. This program and the accompanying materials\n"
            + "  are made available under the terms of the Eclipse Public License v1.0\n"
            + "  which accompanies this distribution, and is available at\n"
            + "  http://www.eclipse.org/legal/epl-v10.html\n" + "\n" + "  Contributors:\n"
            + "  - Philippe Merle <philippe.merle@inria.fr>\n" + "-->\n" + "<plugin>\n" + "\n"
            + "   <!-- Register the factory of this connector. -->\n"
            + "   <extension point=\"org.eclipse.emf.ecore.factory_override\">\n" + "      <factory\n"
            + "            uri=\"" + Occi2Ecore.convertOcciScheme2EcoreNamespace(extensionScheme) + "\"\n"
            + "            class=\"" + connectorProjectName + ".ConnectorFactory\"/>\n" + "   </extension>\n"
            + "\n" + "</plugin>\n";
    pluginXML.create(new ByteArrayInputStream(pluginContent.getBytes()), true, monitor);

    // Generate Java code for the connector.
    try {
        URI modelURI = URI.createURI(extensionFile, true);

        // Generate Java code for the connector.
        IContainer target = connectorProject.getFolder("src");
        // Compute the arguments of the generator.
        ArrayList<String> arguments = new ArrayList<String>();
        // The full name of the package to generate.
        arguments.add(connectorProjectName);
        // The full name of the package to extend.
        arguments.add(requireBundle);
        // Call the generator.
        GenerateAll generator = new GenerateAll(modelURI, target, arguments);
        generator.doGenerate(monitor);
    } catch (IOException e) {
        IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e);
        Activator.getDefault().getLog().log(status);
    } finally {
        connectorProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    }
}

From source file:org.opendaylight.yangide.core.indexing.IndexAllProject.java

License:Open Source License

@Override
public boolean execute(IProgressMonitor progressMonitor) {
    log.info("[I] Project: {}", project.getName());

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) {
        return true;
    }//from   w  w w.j  a va 2 s.  c  om

    if (!this.project.isAccessible()) {
        return true;
    }
    final Set<IPath> ignoredPath = new HashSet<>();
    final Set<IPath> externalJarsPath = new HashSet<>();
    try {
        JavaProject proj = (JavaProject) JavaCore.create(project);
        final Set<String> projectScope = new HashSet<>();
        projectScope.add(project.getName());

        if (proj != null) {
            IClasspathEntry[] classpath = proj.getResolvedClasspath();
            for (IClasspathEntry entry : classpath) {
                IPath entryPath = entry.getPath();
                IPath output = entry.getOutputLocation();
                if (output != null && !entryPath.equals(output)) {
                    ignoredPath.add(output);
                }

                // index dependencies projects
                if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                    IProject prj = ResourcesPlugin.getWorkspace().getRoot()
                            .getProject(entry.getPath().lastSegment());
                    if (prj != null && prj.exists()) {
                        this.manager.indexAll(prj);
                        projectScope.add(prj.getName());
                    }
                }
            }
            IPackageFragmentRoot[] roots = proj.getAllPackageFragmentRoots();
            for (IPackageFragmentRoot root : roots) {
                IPath entryPath = root.getPath();
                if (entryPath != null && entryPath.toFile().exists()
                        && entryPath.lastSegment().toLowerCase().endsWith(".jar")) {
                    externalJarsPath.add(entryPath);
                }
            }
            // Update project information with set of project dependencies
            YangProjectInfo yangProjectInfo = (YangProjectInfo) YangCorePlugin.create(project)
                    .getElementInfo(null);
            yangProjectInfo.setProjectScope(projectScope);
            // fill indirect scope
            Set<String> indirectScope = new HashSet<>();
            indirectScope.add(project.getName());
            for (IJavaProject jproj : JavaCore.create(ResourcesPlugin.getWorkspace().getRoot())
                    .getJavaProjects()) {
                if (jproj != proj) {
                    for (String name : jproj.getRequiredProjectNames()) {
                        if (name.equals(project.getName())) {
                            indirectScope.add(jproj.getProject().getName());
                        }
                    }
                }
            }
            yangProjectInfo.setIndirectScope(indirectScope);
        }
    } catch (JavaModelException | YangModelException e) {
        // java project doesn't exist: ignore
    }

    for (IPath path : externalJarsPath) {
        try (JarFile jarFile = new JarFile(path.toFile())) {
            ZipEntry entry = jarFile.getEntry("META-INF/yang/");
            if (entry != null) {
                this.manager.addJarFile(project, path);
            }
        } catch (IOException e) {
            YangCorePlugin.log(e);
        }
    }
    try {
        final HashSet<IFile> indexedFiles = new HashSet<>();
        project.accept(proxy -> {
            if (IndexAllProject.this.isCancelled) {
                return false;
            }
            if (!ignoredPath.isEmpty() && ignoredPath.contains(proxy.requestFullPath())) {
                return false;
            }
            if (proxy.getType() == IResource.FILE) {
                if (CoreUtil.isYangLikeFileName(proxy.getName())) {
                    IFile file = (IFile) proxy.requestResource();
                    indexedFiles.add(file);
                }
                return false;
            }
            return true;
        }, IResource.NONE);

        for (IFile file : indexedFiles) {
            this.manager.addSource(file);
        }
    } catch (CoreException e) {
        this.manager.removeIndexFamily(project);
        return false;
    }
    return true;
}

From source file:org.openlegacy.ide.eclipse.util.PathsUtil.java

License:Open Source License

public static File toSourceDirectory(IPackageFragmentRoot sourceFolder) {
    IProject project = sourceFolder.getJavaProject().getProject();
    return new File(toOSString(project.getLocation()), toOSString(sourceFolder.getPath()));
}

From source file:org.openquark.cal.eclipse.ui.wizards.NewModuleWizard.java

License:Open Source License

private boolean isJavaSourceFolder(final IPackageFragmentRoot folder) {
    final IJavaProject jProject = folder.getJavaProject();

    IClasspathEntry[] classPathEntries;/*  w  ww .  j  av a  2  s  .  c  om*/
    try {
        classPathEntries = jProject.getRawClasspath();
    } catch (JavaModelException e) {
        // not in class path
        return false;
    }
    boolean alreadyExists = false;
    for (int iClassPathEntries = 0; iClassPathEntries < classPathEntries.length; ++iClassPathEntries) {
        final IClasspathEntry cpe = classPathEntries[iClassPathEntries];
        if (cpe.getPath().equals(folder.getPath())) {
            alreadyExists = true;
            break;
        }
    }
    return alreadyExists;
}

From source file:org.org.eclipse.dws.core.internal.jobs.UpdateJavadocAndSourcesJob.java

License:Open Source License

/**
 * Update sources.//from   w  ww  . ja  v a2s . c  o  m
 * 
 * @param project
 *            the project
 * @param packageFragmentRoot
 *            the package fragment root
 * @param file
 *            the file
 * @param monitor
 *            the monitor
 */
@SuppressWarnings("restriction")
private void updateSources(IJavaProject project, IPackageFragmentRoot packageFragmentRoot, File file,
        IProgressMonitor monitor) {
    try {
        logger.info("updating source attachment of " + packageFragmentRoot.getElementName() + " with " + file);
        IClasspathEntry rawClasspathEntry = packageFragmentRoot.getRawClasspathEntry();
        IPath containerPath = null;
        if (rawClasspathEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
            containerPath = rawClasspathEntry.getPath();
            rawClasspathEntry = handleContainerEntry(containerPath, project, packageFragmentRoot.getPath());
        }
        CPListElement cpElem = CPListElement.createFromExisting(rawClasspathEntry, project);
        String loc = file.getAbsolutePath();
        cpElem.setAttribute(CPListElement.SOURCEATTACHMENT, Path.fromOSString(loc).makeAbsolute());
        IClasspathEntry newEntry = cpElem.getClasspathEntry();
        String[] changedAttributes = { CPListElement.SOURCEATTACHMENT };
        BuildPathSupport.modifyClasspathEntry(null, newEntry, changedAttributes, project, containerPath, true,
                monitor);
    } catch (JavaModelException e) {
        throw new MavenRepositoryInteractionException(
                "Impossible to attach source jar:" + file.getAbsolutePath(), e);
    } catch (CoreException e) {
        throw new MavenRepositoryInteractionException(
                "Impossible to attach source jar:" + file.getAbsolutePath(), e);
    }
}