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.recommenders.internal.models.rcp.ProjectCoordinateProvider.java

License:Open Source License

private static boolean isPartOfJRE(IPackageFragmentRoot root, IJavaProject javaProject) {
    try {//w ww. j  a v  a  2  s  .  c  o m
        for (IClasspathEntry entry : javaProject.getRawClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                if (entry.getPath().toString().contains("org.eclipse.jdt.launching.JRE_CONTAINER")) { //$NON-NLS-1$
                    for (IPackageFragmentRoot packageFragmentRoot : javaProject
                            .findPackageFragmentRoots(entry)) {
                        if (!packageFragmentRoot.getPath().toFile().getParentFile().getName().equals("ext")) { //$NON-NLS-1$
                            if (packageFragmentRoot.equals(root)) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        Logs.log(LogMessages.ERROR_FAILED_TO_TRAVERSE_PROJECT_DEPENDENCIES, e, javaProject);
    }
    return false;
}

From source file:org.eclipse.recommenders.internal.types.rcp.ProjectTypesIndex.java

License:Open Source License

private List<IPackageFragmentRoot> findArchivePackageFragmentRoots() {
    Iterable<IPackageFragmentRoot> filtered = Iterables.filter(
            JavaElementsFinder.findPackageFragmentRoots(project), new ArchiveFragmentRootsOnlyPredicate());
    Iterable<IPackageFragmentRoot> result;
    result = Iterables.filter(filtered, new Predicate<IPackageFragmentRoot>() {

        @Override//ww  w.  j  a va2s.c  o  m
        public boolean apply(IPackageFragmentRoot input) {
            return onlyIndexedJar == null || input.getPath().toFile().equals(onlyIndexedJar);
        }
    });
    return Ordering.usingToString().sortedCopy(result);
}

From source file:org.eclipse.recommenders.jdt.JavaElementsFinder.java

License:Open Source License

/**
 * Returns the compilation unit's absolute location on the local hard drive - if it exists.
 *//*  w  ww.j  a  va  2  s  . c o m*/
public static Optional<File> findLocation(@Nullable IPackageFragmentRoot root) {
    if (root == null) {
        return absent();
    }
    File res = null;

    final IResource resource = root.getResource();
    if (resource != null) {
        if (resource.getLocation() == null) {
            res = resource.getRawLocation().toFile().getAbsoluteFile();
        } else {
            res = resource.getLocation().toFile().getAbsoluteFile();
        }
    }
    if (root.isExternal()) {
        res = root.getPath().toFile().getAbsoluteFile();
    }

    // if the file (for whatever reasons) does not exist return absent().
    if (res != null && !res.exists()) {
        return absent();
    }
    return fromNullable(res);
}

From source file:org.eclipse.recommenders.models.dependencies.rcp.EclipseDependencyListener.java

License:Open Source License

public static Set<IPackageFragmentRoot> detectJREPackageFragementRoots(final IJavaProject javaProject) {
    // Please notice that this is a heuristic to detect if a Jar is part of
    // the JRE or not.
    // All Jars in the JRE_Container which are not located in the ext folder
    // are defined as part of the JRE
    Set<IPackageFragmentRoot> jreRoots = new HashSet<IPackageFragmentRoot>();
    try {//from   w w w.  j a va  2 s.  c  om
        for (IClasspathEntry entry : javaProject.getRawClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                if (entry.getPath().toString().contains("org.eclipse.jdt.launching.JRE_CONTAINER")) {
                    for (IPackageFragmentRoot packageFragmentRoot : javaProject
                            .findPackageFragmentRoots(entry)) {
                        if (!packageFragmentRoot.getPath().toFile().getParentFile().getName().equals("ext")) {
                            jreRoots.add(packageFragmentRoot);
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return jreRoots;
}

From source file:org.eclipse.recommenders.rcp.utils.JdtUtils.java

License:Open Source License

public static Optional<File> getLocation(@Nullable final IPackageFragmentRoot packageRoot) {
    if (packageRoot == null) {
        return absent();
    }/*from  www  .j av  a  2s. c o m*/
    File res = null;
    final IResource resource = packageRoot.getResource();
    if (resource != null) {
        if (resource.getLocation() == null) {
            res = resource.getRawLocation().toFile().getAbsoluteFile();
        } else {
            res = resource.getLocation().toFile().getAbsoluteFile();
        }
    }
    if (packageRoot.isExternal()) {
        res = packageRoot.getPath().toFile().getAbsoluteFile();
    }

    // if the file (for whatever reasons) does not exist, skip it.
    if (res != null && !res.exists()) {
        res = null;
    }
    return Optional.fromNullable(res);
}

From source file:org.eclipse.recommenders.testing.rcp.completion.rules.TemporaryProject.java

License:Open Source License

private void createProject() {
    final IWorkspaceRunnable populate = new IWorkspaceRunnable() {

        @Override/*from  w w w .  ja  va2 s.c  o m*/
        public void run(final IProgressMonitor monitor) throws CoreException {
            createAndOpenProject(project);

            if (!hasJavaNature(project)) {
                addJavaNature(project);
                addToClasspath(JavaRuntime.getDefaultJREContainerEntry());
                addSourcePackageFragmentRoot(project);
            }
        }

        private void createAndOpenProject(IProject project) throws CoreException {
            if (!project.exists()) {
                project.create(null);
            }
            project.open(null);
        }

        private boolean hasJavaNature(final IProject project) throws CoreException {
            final IProjectDescription description = project.getDescription();
            final String[] natures = description.getNatureIds();
            return ArrayUtils.contains(natures, JavaCore.NATURE_ID);
        }

        private void addJavaNature(final IProject project) throws CoreException {
            final IProjectDescription description = project.getDescription();
            final String[] natures = description.getNatureIds();
            final String[] newNatures = ArrayUtils.add(natures, JavaCore.NATURE_ID);

            description.setNatureIds(newNatures);
            project.setDescription(description, null);
            javaProject = JavaCore.create(project);
        }

        private void addSourcePackageFragmentRoot(IProject project) throws CoreException {
            // create the source folder
            IFolder sourceFolder = project.getFolder(SRC_FOLDER_NAME);
            sourceFolder.create(false, true, null);

            // replace the classpath's project root entry with the src folder
            IPackageFragmentRoot src = javaProject.getPackageFragmentRoot(sourceFolder);
            IClasspathEntry[] entries = javaProject.getRawClasspath();

            for (int i = 0; i < entries.length; i++) {
                if (entries[i].getPath().toString().equals(separator + name)) {
                    entries[i] = JavaCore.newSourceEntry(src.getPath());
                    break;
                }
            }

            javaProject.setRawClasspath(entries, null);
        }
    };

    try {
        workspace.run(populate, null);
    } catch (final Exception e) {
        e.printStackTrace();
        Throws.throwUnhandledException(e);
    }
    javaProject = JavaCore.create(project);
}

From source file:org.eclipse.recommenders.tests.models.EclipseDependencyListenerTest.java

License:Open Source License

private IJavaProject createProject(final String projectName) throws Exception {
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = workspaceRoot.getProject(projectName);
    project.create(null);//ww  w  . ja  v a2s .c  om
    project.open(null);
    IProjectDescription description = project.getDescription();
    description.setNatureIds(new String[] { JavaCore.NATURE_ID });
    project.setDescription(description, null);
    IJavaProject javaProject = JavaCore.create(project);

    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    entries.add(JavaRuntime.getDefaultJREContainerEntry());
    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
    IFolder sourceFolder = project.getFolder("src");
    sourceFolder.create(false, true, null);

    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder);
    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);

    javaProject.open(null);
    return javaProject;
}

From source file:org.eclipse.servicesregistry.testutils.TestProject.java

License:Open Source License

public IPackageFragmentRoot createSourceFolder(String name) throws CoreException {
    IFolder folder = project.getFolder(name);
    folder.create(false, true, null);/*  w  w  w.j  av  a  2s  .  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);
    this.sourceFolder = root;

    String log = "\n" + javaProject.getProject().getName() + "\n"
            + String.valueOf(javaProject.getRawClasspath().length) + "\n";

    for (int ii = 0; ii < javaProject.getRawClasspath().length; ii++) {
        log = log + javaProject.getRawClasspath()[ii].getPath().toString() + "\n";
    }

    if (javaProject.getRawClasspath().length == 0) {
        log = log + "Classpath not initialized !\n";
    }

    ResourcesPlugin.getPlugin().getLog().log(new Status(0, "testOutput", log));

    return root;
}

From source file:org.eclipse.titan.codegenerator.AstWalkerJava.java

License:Open Source License

public void run(IAction action) {

    /**//*w  w w .ja va2 s.c  o  m*/
    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    for (IProject p : projects) {
        if (p.getName().equals("org.eclipse.titan.codegenerator.output"))
            try {
                p.delete(true, true, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
    IProject project = ResourcesPlugin.getWorkspace().getRoot()
            .getProject("org.eclipse.titan.codegenerator.output");
    try {
        project.create(null);
        project.open(null);
        IProjectDescription description = project.getDescription();
        description.setNatureIds(new String[] { JavaCore.NATURE_ID });
        project.setDescription(description, null);
        IJavaProject javaProject = JavaCore.create(project);
        IFolder binFolder = project.getFolder("bin");
        binFolder.create(false, true, null);
        javaProject.setOutputLocation(binFolder.getFullPath(), null);
        List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
        IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
        LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall);
        for (LibraryLocation element : locations) {
            entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null));
        }
        javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
        IFolder sourceFolder = project.getFolder("src");
        sourceFolder.create(false, true, null);
        IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder);
        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);
        javaProject.getPackageFragmentRoot(sourceFolder)
                .createPackageFragment("org.eclipse.titan.codegenerator.javagen", false, null);
        javaProject.getPackageFragmentRoot(sourceFolder)
                .createPackageFragment("org.eclipse.titan.codegenerator.TTCN3JavaAPI", false, null);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String destpath = new String("");
    String wspath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString().replaceAll("/", "\\\\");
    destpath += wspath;
    destpath += "\\org.eclipse.titan.codegenerator.output\\src\\org\\eclipse\\titan\\codegenerator\\javagen\\";
    props.setProperty("javafile.path", destpath);
    /**/

    AstWalkerJava.files.clear();
    AstWalkerJava.fileNames.clear();
    AstWalkerJava.componentList.clear();
    AstWalkerJava.testCaseList.clear();
    AstWalkerJava.testCaseRunsOnList.clear();
    AstWalkerJava.functionList.clear();
    AstWalkerJava.functionRunsOnList.clear();

    AstWalkerJava.initOutputFolder();
    AstWalkerJava.getActiveProject();

    /*
     * // init console logger IConsole myConsole = findConsole("myLogger");
     * IWorkbenchPage page = window.getActivePage(); String id =
     * IConsoleConstants.ID_CONSOLE_VIEW; IConsoleView view; try { view =
     * (IConsoleView) page.showView(id); view.display(myConsole); } catch
     * (PartInitException e) { // TODO Auto-generated catch block
     * e.printStackTrace(); }
     */

    // initialize common files

    myASTVisitor.currentFileName = "TTCN_functions";

    myASTVisitor.visualizeNodeToJava(myASTVisitor.importListStrings);
    myASTVisitor.visualizeNodeToJava("class TTCN_functions{\r\n}\r\n");

    Def_Template_Visit_Handler.isTemplate = false;

    final ProjectSourceParser sourceParser = GlobalParser.getProjectSourceParser(selectedProject);
    sourceParser.analyzeAll();

    logToConsole("Version built on 2016.10.24");
    logToConsole("Starting to generate files into: " + props.getProperty("javafile.path"));

    myASTVisitor visitor = new myASTVisitor();
    for (Module module : sourceParser.getModules()) {
        // start AST processing
        walkChildren(visitor, module.getOutlineChildren());
    }
    visitor.finish();

    logToConsole("Files generated into: " + props.getProperty("javafile.path"));

    // write additional classes
    Additional_Class_Writer additional_class = new Additional_Class_Writer();
    myASTVisitor.currentFileName = "HC";

    myASTVisitor.visualizeNodeToJava(myASTVisitor.importListStrings);
    myASTVisitor.visualizeNodeToJava(additional_class.writeHCClass());

    myASTVisitor.currentFileName = "HCType";
    myASTVisitor.visualizeNodeToJava(myASTVisitor.importListStrings);
    myASTVisitor.visualizeNodeToJava(additional_class.writeHCTypeClass());

    // clear lists

    logger.severe("analysis complete");

    /**/
    File fromdir = new File(wspath
            + "\\org.eclipse.titan.codegenerator\\src\\org\\eclipse\\titan\\codegenerator\\TTCN3JavaAPI\\");
    String toapidir = wspath
            + "\\org.eclipse.titan.codegenerator.output\\src\\org\\eclipse\\titan\\codegenerator\\TTCN3JavaAPI\\";
    File[] fromfiles = fromdir.listFiles();
    for (File f : fromfiles) {
        try {
            Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(toapidir + f.getName()),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String tppath = wspath + "\\" + selectedProject.getFullPath().toString().split("/")[1] + "\\src\\";
    File tp_cfg_dir = new File(tppath);
    String togendir = wspath
            + "\\org.eclipse.titan.codegenerator.output\\src\\org\\eclipse\\titan\\codegenerator\\javagen\\";
    File[] from_testports_cfg = tp_cfg_dir.listFiles();
    for (File f : from_testports_cfg) {
        if (f.getName().endsWith(".java")) {
            try {
                Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(togendir + f.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (f.getName().endsWith(".cfg")) {
            try {
                Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(toapidir + "cfg.cfg"),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    try {
        ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE,
                new NullProgressMonitor());
    } catch (Exception e) {
        e.printStackTrace();
    }
    /**/

}

From source file:org.eclipse.umlgen.gen.java.services.WorkspaceServices.java

License:Open Source License

/**
 * Creates a project from scratch in the workspace.
 *
 * @param eObject/* w w w .  jav  a2s .com*/
 *            The model element
 */
public void createDefaultProject(EObject eObject) {
    if (!EMFPlugin.IS_ECLIPSE_RUNNING) {
        return;
    }

    IProgressMonitor monitor = new NullProgressMonitor();
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    try {
        IWorkspaceRoot workspaceRoot = workspace.getRoot();

        String projectName = UML2JavaConfigurationHolder.getDefaultProjectName(eObject);
        IProject project = workspaceRoot.getProject(projectName);

        if (project.exists() && project.isAccessible()) {
            if (!project.isOpen()) {
                project.open(monitor);
            }
        } else {
            project.create(new NullProgressMonitor());
            project.open(new NullProgressMonitor());

            IContainer intputContainer = project;

            String sourceFolderName = UML2JavaConfigurationHolder.getSourceFolderPath(eObject);
            StringTokenizer stringTokenizer = new StringTokenizer(sourceFolderName, "/");
            while (stringTokenizer.hasMoreTokens()) {
                String token = stringTokenizer.nextToken();
                IFolder src = intputContainer.getFolder(new Path(token));
                if (!src.exists()) {
                    src.create(true, true, monitor);
                }

                intputContainer = src;
            }

            IContainer outputContainer = project;

            String outputFolderName = UML2JavaConfigurationHolder.getOutputFolderPath(eObject);
            stringTokenizer = new StringTokenizer(outputFolderName, "/");
            while (stringTokenizer.hasMoreTokens()) {
                String token = stringTokenizer.nextToken();
                IFolder out = outputContainer.getFolder(new Path(token));
                if (!out.exists()) {
                    out.create(true, true, monitor);
                }

                outputContainer = out;
            }

            IProjectDescription description = project.getDescription();
            String[] natures = new String[] {};
            if (IUML2JavaConstants.Default.DEFAULT_COMPONENT_ARTIFACTS_TYPE_OSGI
                    .equals(UML2JavaConfigurationHolder.getComponentBasedArchitecture(eObject))
                    || IUML2JavaConstants.Default.DEFAULT_COMPONENT_ARTIFACTS_TYPE_ECLIPSE
                            .equals(UML2JavaConfigurationHolder.getComponentBasedArchitecture(eObject))) {
                natures = new String[] { JavaCore.NATURE_ID, IUML2JavaConstants.PDE_PLUGIN_NATURE_ID };
            } else {
                natures = new String[] { JavaCore.NATURE_ID, };
            }
            description.setNatureIds(natures);
            project.setDescription(description, monitor);

            IJavaProject javaProject = JavaCore.create(project);

            List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
            IExecutionEnvironmentsManager executionEnvironmentsManager = JavaRuntime
                    .getExecutionEnvironmentsManager();
            IExecutionEnvironment[] executionEnvironments = executionEnvironmentsManager
                    .getExecutionEnvironments();

            String defaultJREExecutionEnvironment = UML2JavaConfigurationHolder
                    .getJREExecutionEnvironment(eObject);
            for (IExecutionEnvironment iExecutionEnvironment : executionEnvironments) {
                if (defaultJREExecutionEnvironment.equals(iExecutionEnvironment.getId())) {
                    entries.add(
                            JavaCore.newContainerEntry(JavaRuntime.newJREContainerPath(iExecutionEnvironment)));
                    break;
                }
            }

            javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);

            IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
            IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
            System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);

            javaProject.setOutputLocation(outputContainer.getFullPath(), monitor);

            IPackageFragmentRoot packageRoot = javaProject
                    .getPackageFragmentRoot(intputContainer.getFullPath().toString());
            newEntries[oldEntries.length] = JavaCore.newSourceEntry(packageRoot.getPath(), new Path[] {},
                    new Path[] {}, outputContainer.getFullPath());

            javaProject.setRawClasspath(newEntries, null);

            IFile buildPropertiesFile = project.getFile("build.properties");
            if (!buildPropertiesFile.exists()) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(
                        "#################################################################################"
                                + System.getProperty(LINE_SEPARATOR));
                stringBuilder.append("## " + UML2JavaConfigurationHolder.getCopyrightAndLicense(eObject)
                        + System.getProperty(LINE_SEPARATOR));
                stringBuilder.append(
                        "#################################################################################"
                                + System.getProperty(LINE_SEPARATOR));
                stringBuilder.append("source.. = " + UML2JavaConfigurationHolder.getSourceFolderPath(eObject)
                        + System.getProperty(LINE_SEPARATOR));
                stringBuilder.append("output.. = " + UML2JavaConfigurationHolder.getOutputFolderPath(eObject)
                        + System.getProperty(LINE_SEPARATOR));
                stringBuilder.append("" + System.getProperty(LINE_SEPARATOR));
                buildPropertiesFile.create(new ByteArrayInputStream(stringBuilder.toString().getBytes()), true,
                        monitor);
            }
        }
    } catch (CoreException coreException) {
        AcceleoEnginePlugin.log(coreException, true);
    }
}