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.eclipse.e4.demo.simpleide.jdt.internal.editor.viewer.JavaElementLabelComposer.java

License:Open Source License

private void appendFolderLabel(IPackageFragmentRoot root, long flags) {
    IResource resource = root.getResource();
    if (resource == null) {
        appendExternalArchiveLabel(root, flags);
        return;//from  www  . jav a 2s  .  c om
    }

    boolean rootQualified = getFlag(flags, JavaElementLabels.ROOT_QUALIFIED);
    boolean referencedQualified = getFlag(flags, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED)
            && isReferenced(root);
    if (rootQualified) {
        fBuffer.append(root.getPath().makeRelative().toString());
    } else {
        IPath projectRelativePath = resource.getProjectRelativePath();
        if (projectRelativePath.segmentCount() == 0) {
            fBuffer.append(resource.getName());
            referencedQualified = false;
        } else {
            fBuffer.append(projectRelativePath.toString());
        }

        int offset = fBuffer.length();
        if (referencedQualified) {
            fBuffer.append(JavaElementLabels.CONCAT_STRING);
            fBuffer.append(resource.getProject().getName());
        } else if (getFlag(flags, JavaElementLabels.ROOT_POST_QUALIFIED)) {
            fBuffer.append(JavaElementLabels.CONCAT_STRING);
            fBuffer.append(root.getParent().getElementName());
        } else {
            return;
        }
        if (getFlag(flags, JavaElementLabels.COLORIZE)) {
            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        }
    }
}

From source file:org.eclipse.e4.demo.simpleide.jdt.internal.editor.viewer.JavaElementLabelComposer.java

License:Open Source License

private boolean appendVariableLabel(IPackageFragmentRoot root, long flags) {
    try {// w  w w. ja  v  a2 s .  c om
        IClasspathEntry rawEntry = root.getRawClasspathEntry();
        if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
            IClasspathEntry entry = JavaModelUtil.getClasspathEntry(root);
            if (entry.getReferencingEntry() != null) {
                return false; // not the variable entry itself, but a
                              // referenced entry
            }
            IPath path = rawEntry.getPath().makeRelative();

            if (getFlag(flags, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED)) {
                int segements = path.segmentCount();
                if (segements > 0) {
                    fBuffer.append(path.segment(segements - 1));
                    if (segements > 1) {
                        int offset = fBuffer.length();
                        fBuffer.append(JavaElementLabels.CONCAT_STRING);
                        fBuffer.append(path.removeLastSegments(1).toOSString());
                        if (getFlag(flags, JavaElementLabels.COLORIZE)) {
                            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
                        }
                    }
                } else {
                    fBuffer.append(path.toString());
                }
            } else {
                fBuffer.append(path.toString());
            }
            int offset = fBuffer.length();
            fBuffer.append(JavaElementLabels.CONCAT_STRING);
            if (root.isExternal())
                fBuffer.append(root.getPath().toOSString());
            else
                fBuffer.append(root.getPath().makeRelative().toString());

            if (getFlag(flags, JavaElementLabels.COLORIZE)) {
                fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
            }
            return true;
        }
    } catch (JavaModelException e) {
        // problems with class path, ignore (bug 202792)
        return false;
    }
    return false;
}

From source file:org.eclipse.e4.demo.simpleide.jdt.internal.editor.viewer.JavaElementLabelComposer.java

License:Open Source License

private void appendInternalArchiveLabel(IPackageFragmentRoot root, long flags) {
    IResource resource = root.getResource();
    boolean rootQualified = getFlag(flags, JavaElementLabels.ROOT_QUALIFIED);
    if (rootQualified) {
        fBuffer.append(root.getPath().makeRelative().toString());
    } else {// w w w  .  ja  va  2s.  c o m
        fBuffer.append(root.getElementName());
        int offset = fBuffer.length();
        boolean referencedPostQualified = getFlag(flags, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED);
        if (referencedPostQualified && isReferenced(root)) {
            fBuffer.append(JavaElementLabels.CONCAT_STRING);
            fBuffer.append(resource.getParent().getFullPath().makeRelative().toString());
        } else if (getFlag(flags, JavaElementLabels.ROOT_POST_QUALIFIED)) {
            fBuffer.append(JavaElementLabels.CONCAT_STRING);
            fBuffer.append(root.getParent().getPath().makeRelative().toString());
        }
        if (referencedPostQualified) {
            try {
                IClasspathEntry referencingEntry = JavaModelUtil.getClasspathEntry(root).getReferencingEntry();
                if (referencingEntry != null) {
                    fBuffer.append(messages.JavaElementLabels_onClassPathOf(Name.CLASS_PATH.toString(),
                            referencingEntry.getPath().lastSegment()));
                }
            } catch (JavaModelException e) {
                // ignore
            }
        }
        if (getFlag(flags, JavaElementLabels.COLORIZE)) {
            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        }
    }
}

From source file:org.eclipse.edt.ide.ui.wizards.EGLProjectUtility.java

License:Open Source License

private static IClasspathEntry[] createNewClasspathEntries(IJavaProject javaProject, String folderName,
        String binFolderName, String encoding, IClasspathEntry[] oldEntries) throws InvocationTargetException {
    // Get or create the necessary folders as well as the file.
    IFolder baseFolder = createFolderIfNecessary(javaProject.getProject(), folderName, encoding);
    IFolder binFolder = createFolderIfNecessary(javaProject.getProject(), binFolderName, encoding);

    try {//from  w  w w . j  av  a 2s.com
        IPackageFragmentRoot sourceRoot = javaProject.getPackageFragmentRoot(baseFolder);
        IPackageFragmentRoot binRoot = javaProject.getPackageFragmentRoot(binFolder);
        IClasspathEntry newEntry = JavaCore.newSourceEntry(sourceRoot.getPath(), new IPath[] {},
                binRoot.getPath());
        if (!EGLProjectUtility.classpathEntryExists(javaProject, newEntry)) {
            //oldEntries = javaProject.getRawClasspath();
            IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
            newEntries[0] = newEntry;
            System.arraycopy(oldEntries, 0, newEntries, 1, oldEntries.length);
            return newEntries;
        }
    } catch (JavaModelException ex) {
        throw new InvocationTargetException(ex, ex.getMessage());
    }
    // Return the old ones if a new entry wasn't created
    return oldEntries;
}

From source file:org.eclipse.egit.core.test.TestProject.java

License:Open Source License

public IPackageFragmentRoot createSourceFolder() throws CoreException {
    IFolder folder = project.getFolder("src");
    folder.create(false, true, null);/*from   www  .  j  av  a2s.  c om*/
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);
    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
    javaProject.setRawClasspath(newEntries, null);
    return root;
}

From source file:org.eclipse.egit.ui.test.team.actions.ShowBlameActionHandlerTest.java

License:Open Source License

private IJavaProject createJavaProject(final Repository repository, final String projectName) throws Exception {
    final IJavaProject[] jProjectHolder = new IJavaProject[] { null };
    IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
        @Override/*  ww w .ja va2 s .c  o  m*/
        public void run(IProgressMonitor monitor) throws CoreException {
            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            IProject project = root.getProject(projectName);
            if (project.exists()) {
                project.delete(true, null);
                TestUtil.waitForJobs(100, 5000);
            }
            IProjectDescription desc = ResourcesPlugin.getWorkspace().newProjectDescription(projectName);
            desc.setLocation(new Path(new File(repository.getWorkTree(), projectName).getPath()));
            project.create(desc, null);
            project.open(null);
            TestUtil.waitForJobs(50, 5000);
            // Create a "bin" folder
            IFolder bin = project.getFolder(BIN_FOLDER_NAME);
            if (!bin.exists()) {
                bin.create(IResource.FORCE | IResource.DERIVED, true, null);
            }
            IPath outputLocation = bin.getFullPath();
            // Create a "src" folder
            IFolder src = project.getFolder(SRC_FOLDER_NAME);
            if (!src.exists()) {
                src.create(IResource.FORCE, true, null);
            }
            addNatureToProject(project, JavaCore.NATURE_ID);
            // Set up the IJavaProject
            IJavaProject jProject = JavaCore.create(project);
            IPackageFragmentRoot srcContainer = jProject.getPackageFragmentRoot(src);
            IClasspathEntry srcEntry = JavaCore.newSourceEntry(srcContainer.getPath());
            // Create a JRE classpath entry using the default JRE
            IClasspathEntry jreEntry = JavaRuntime.getDefaultJREContainerEntry();
            jProject.setRawClasspath(new IClasspathEntry[] { srcEntry, jreEntry }, outputLocation, true, null);
            // Create a package with a single test class
            IPackageFragment javaPackage = srcContainer.createPackageFragment(PACKAGE_NAME, true, null);
            javaPackage.createCompilationUnit(JAVA_FILE_NAME,
                    "package " + PACKAGE_NAME + ";\nclass " + JAVA_CLASS_NAME + " {\n\n}", true, null);
            jProjectHolder[0] = jProject;
        }
    };
    ResourcesPlugin.getWorkspace().run(runnable, null);
    return jProjectHolder[0];
}

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   www .j av  a 2 s  . 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.emf.mwe2.language.ui.wizard.NewMwe2FileWizard.java

License:Open Source License

@Override
public void addPages() {
    super.addPages();
    mainPage = new WizardNewFileCreationPage("newFilePage1", getSelection()) { //$NON-NLS-1$
        @Override//from   w  w  w  .  j  a v  a  2  s  .c o  m
        protected InputStream getInitialContents() {
            String module = getModule();
            if (module != null) {
                String content = String.format(Messages.NewMwe2FileWizard_initialContent, module);
                return new StringInputStream(content);
            }
            return new StringInputStream(""); //$NON-NLS-1$
        }

        protected String getModule() {
            IPath path = getContainerFullPath();
            IProject project = null;
            for (IProject p : workspace.getRoot().getProjects()) {
                if (p.getFullPath().isPrefixOf(path)) {
                    project = p;
                    break;
                }
            }
            IJavaProject javaProject = JavaCore.create(project);
            if (javaProject != null) {
                try {
                    IPackageFragmentRoot root = null;
                    for (IPackageFragmentRoot candidate : javaProject.getPackageFragmentRoots()) {
                        if (candidate.getPath().isPrefixOf(path)) {
                            root = candidate;
                            break;
                        }
                    }
                    if (root != null) {
                        IPath relativePath = path.makeRelativeTo(root.getPath());
                        String pack = relativePath.toString().replace('/', '.');
                        String fileName = getFileName();
                        fileName = fileName.substring(0, fileName.indexOf("." + extension)); //$NON-NLS-1$
                        String module = pack + "." + fileName; //$NON-NLS-1$
                        return module;
                    }
                } catch (JavaModelException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            return null;
        }
    };
    mainPage.setTitle(Messages.NewMwe2FileWizard_title);
    mainPage.setDescription(Messages.NewMwe2FileWizard_description);
    mainPage.setFileExtension(extension);
    addPage(mainPage);
}

From source file:org.eclipse.fx.ide.css.validation.CssDslJavaValidator.java

License:Open Source License

@SuppressWarnings("restriction")
@Check/*w w  w.  java  2  s .  c  om*/
public void checkDeclaration(css_declaration dec) {
    //      System.err.println("CHECK DECL " + dec);
    css_property property = dec.getProperty();

    // Only validate files who are:
    // * in a plug-in project
    //   - when css is part of build.properties bin.includes
    //   - when css is part of the source-folder
    IFile file = Utils.getFile(dec.eResource());

    //TODO We should add a service possibility to contribute these lookups
    boolean validate = false;

    try {
        if (file.getProject().hasNature("org.eclipse.pde.PluginNature")) { //$NON-NLS-1$
            // validate = true;
            IFile properties = PDEProject.getBuildProperties(file.getProject());
            Properties p = new Properties();
            try (InputStream in = properties.getContents()) {
                p.load(in);
                String includes = p.getProperty("bin.includes"); //$NON-NLS-1$
                if (includes != null) {
                    IPath path = file.getProjectRelativePath();
                    for (String s : includes.split(",")) { //$NON-NLS-1$
                        if (path.toString().startsWith(s.trim())) {
                            validate = true;
                            break;
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (!validate && file.getProject().hasNature("org.eclipse.jdt.core.javanature")) { //$NON-NLS-1$
            IJavaProject jp = JavaCore.create(file.getProject());
            for (IPackageFragmentRoot r : jp.getPackageFragmentRoots()) {
                if (r.getKind() == IPackageFragmentRoot.K_SOURCE) {
                    if (file.getProjectRelativePath().toString()
                            .startsWith(r.getPath().removeFirstSegments(1).toString())) {
                        validate = true;
                        break;
                    }
                }
            }
        }
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (!validate) {
        return;
    }

    if (dec.eContainer() instanceof font_face) {
        if ("font-family".equals(property.getName())) {
            if (dec.getValueTokens().stream().filter(this::filterWS).count() != 1) {
                error("Font family has to define a name", dec,
                        CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS);
            } else {
                if (!(dec.getValueTokens().stream().filter(this::filterWS).findFirst()
                        .get() instanceof IdentifierTok)) {
                    CssTok tok = dec.getValueTokens().stream().filter(this::filterWS).findFirst().get();
                    error("Invalid font family name", dec, CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS,
                            dec.getValueTokens().indexOf(tok));
                }
            }
        } else if ("src".equals(property.getName())) {
            if (dec.getValueTokens().stream().filter(this::filterWS).count() == 0) {
                error("At least one URL is required", dec,
                        CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS);
            } else {
                dec.getValueTokens().stream().filter(this::filterWS).filter(this::filterSymbol)
                        .filter((t) -> !(t instanceof UrlTok)).forEach((t) -> {
                            error("Only url-values are allowed", dec,
                                    CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS,
                                    dec.getValueTokens().indexOf(t));
                        });
            }
        } else if ("font-stretch".equals(property.getName())) {

        } else if ("font-style".equals(property.getName())) {

        } else if ("font-weight".equals(property.getName())) {

        } else if ("unicode-range".equals(property.getName())) {

        } else {
            warning("Unknown property: \"" + property.getName() + "\"", property,
                    CssDslPackage.Literals.CSS_PROPERTY__NAME);
        }

        return;
    }

    List<Proposal> properties = ext.getPropertyProposalsForSelector(file, dec, null);
    //extension.getAllProperties(uri);

    boolean known = false;
    for (Proposal p : properties) {
        if (p.getProposal().equals(property.getName())) {
            known = true;
            break;
        }
    }

    if (!known) {
        ICompositeNode node = NodeModelUtils.getNode(dec.getProperty());

        boolean suppress = node.getText().contains("@SuppressWarning");
        if (!suppress && !PREDEFINED_VAR_PROPS.contains(property.getName())
                && !property.getName().startsWith("-var")) { //$NON-NLS-1$
            warning("Unknown property: \"" + property.getName() + "\"", property,
                    CssDslPackage.Literals.CSS_PROPERTY__NAME);
        }
    } else {

        ruleset rs = (ruleset) dec.eContainer();
        List<selector> selectors = rs.getSelectors();
        //         Set<CssProperty> selectorProps = new HashSet<>();
        //         for (selector selector : selectors) {
        //            selectorProps.addAll(extension.getPropertiesForSelector(uri, selector));
        //         }

        List<Proposal> selectorProps = ext.getPropertyProposalsForSelector(Utils.getFile(dec.eResource()), dec,
                selectors);

        if (selectorProps.size() > 0) {
            boolean supported = false;
            for (Proposal p : selectorProps) {
                if (p.getProposal().equals(property.getName())) {
                    supported = true;
                    break;
                }
            }

            if (!supported) {
                ICompositeNode node = NodeModelUtils.getNode(dec.getProperty());

                boolean suppress = node.getText().contains("@SuppressWarning"); //$NON-NLS-1$

                if (!PREDEFINED_VAR_PROPS.contains(property.getName())
                        && !property.getName().startsWith("-var")) {
                    warning("\"" + property.getName() + "\" is not supported by the given selectors",
                            CssDslPackage.Literals.CSS_DECLARATION__PROPERTY);
                }
            }
        }

        //         List<ValidationResult> result = extension.validateProperty(uri, null, property.getName(), tokens);

        //         System.err.println(result);
        //
        //         System.err.println("validation of " + property.getName());

        //         if (!result.isEmpty()) {
        //            for (ValidationResult r : result) {
        //               if (r.status == ValidationStatus.ERROR) {
        //                  if (r.object != null) {
        //                     if (r.object instanceof FuncTok) {
        //                        FuncTok f = (FuncTok) r.object;
        //                        error(r.message, f, CssDslPackage.Literals.FUNC_TOK__NAME, -1);
        //                     }
        //                     else {
        //                        error(r.message, r.object, null, 0);
        //                     }
        //                  }
        //                  else {
        //                     error(r.message, dec, CssDslPackage.Literals.CSS_DECLARATION__VALUE_TOKENS, r.index);
        //                  }
        //               }
        //            }
        //         }
    }
}

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

License:Open Source License

public IPackageFragmentRoot findPackageFragmentRoot0(IPath path) throws JavaModelException {

    IPackageFragmentRoot[] allRoots = this.getAllPackageFragmentRoots();
    if (!path.isAbsolute()) {
        throw new IllegalArgumentException(Messages.path_mustBeAbsolute);
    }//from  ww w. j a  v  a 2  s.  c o  m
    for (int i = 0; i < allRoots.length; i++) {
        IPackageFragmentRoot classpathRoot = allRoots[i];
        if (classpathRoot.getPath().equals(path)) {
            return classpathRoot;
        }
    }
    return null;
}