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.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsManager.java

License:Open Source License

/**
 * Get the path of .JAVA/src//w w  w  . ja  v  a  2  s . c  o m
 * 
 * @throws Exception
 */
protected IPath getSrcRootLocation() throws Exception {
    ITalendProcessJavaProject talendProcessJavaProject = RepositoryPlugin.getDefault().getRunProcessService()
            .getTalendProcessJavaProject();
    if (talendProcessJavaProject == null) {
        return new Path(""); //$NON-NLS-1$
    }
    IProject project = talendProcessJavaProject.getProject();
    IJavaProject javaProject = talendProcessJavaProject.getJavaProject();
    IPackageFragmentRoot[] pp = javaProject.getAllPackageFragmentRoots();
    IPackageFragmentRoot src = null;
    for (IPackageFragmentRoot root : pp) {
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
            src = root;
            break;
        }
    }

    IPath root = project.getParent().getLocation();
    root = root.append(src.getPath());
    return root;
}

From source file:org.universaal.tools.externalserviceintegrator.actions.CreateClientProject.java

License:Apache License

public void createProject() {
    final Job job1 = new WorkspaceJob("TEST") {
        public IStatus runInWorkspace(IProgressMonitor monitor) {
            try {
                IProject project = ResourcesPlugin.getWorkspace().getRoot()
                        .getProject(selectedOperation.getOperationName());
                if (!project.exists()) {
                    project.create(monitor);
                    project.open(monitor);
                    // Configure the project to be a Java project and a
                    // maven project
                    IProjectDescription description = project.getDescription();
                    description.setNatureIds(
                            new String[] { JavaCore.NATURE_ID, "org.eclipse.m2e.core.maven2Nature" });
                    project.setDescription(description, monitor);
                    // src
                    IFolder src = project.getFolder("src");
                    src.create(true, true, monitor);
                    // pom file
                    IFile pomFile = project.getFile("pom.xml");
                    InputStream pomSource = new ByteArrayInputStream(createPOMFile().getBytes());
                    pomFile.create(pomSource, true, null);
                    pomSource.close();//from  w  ww .  jav  a2  s  .  c  o m

                    // src/main
                    IFolder srcMain = src.getFolder("main");
                    srcMain.create(true, true, monitor);

                    // src/main/java
                    IFolder srcMainJava = srcMain.getFolder("java");
                    srcMainJava.create(true, true, monitor);

                    IJavaProject javaProject = JavaCore.create(project);

                    // Let's add JavaSE-1.6 to our classpath
                    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
                    IExecutionEnvironmentsManager executionEnvironmentsManager = JavaRuntime
                            .getExecutionEnvironmentsManager();
                    IExecutionEnvironment[] executionEnvironments = executionEnvironmentsManager
                            .getExecutionEnvironments();
                    for (IExecutionEnvironment iExecutionEnvironment : executionEnvironments) {
                        // We will look for JavaSE-1.6 as the JRE container
                        // to add to our classpath
                        if ("J2SE-1.5".equals(iExecutionEnvironment.getId())) {
                            entries.add(JavaCore
                                    .newContainerEntry(JavaRuntime.newJREContainerPath(iExecutionEnvironment)));
                            break;
                        }
                    }

                    // Let's add the maven container to our classpath to let
                    // the maven plug-in add the dependencies computed from
                    // a pom.xml file to our classpath
                    IClasspathEntry mavenEntry = JavaCore.newContainerEntry(
                            new Path("org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"), new IAccessRule[0],
                            new IClasspathAttribute[] { JavaCore.newClasspathAttribute(
                                    "org.eclipse.jst.component.dependency", "/WEB-INF/lib") },
                            false);
                    entries.add(mavenEntry);

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

                    // Let's create our target/classes output folder
                    IFolder target = project.getFolder("target");
                    target.create(true, true, monitor);

                    IFolder classes = target.getFolder("classes");
                    classes.create(true, true, monitor);

                    // Let's add target/classes as our output folder for
                    // compiled ".class"
                    javaProject.setOutputLocation(classes.getFullPath(), monitor);

                    // Now let's add our source folder and output folder to
                    // our classpath
                    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
                    // +1 for our src/main/java entry
                    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
                    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);

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

                    javaProject.setRawClasspath(newEntries, null);

                    // create Activator
                    IPackageFragment pack = javaProject.getPackageFragmentRoot(srcMainJava)
                            .createPackageFragment("org.universAAL."
                                    + selectedOperation.getOperationName().substring(0, 1).toLowerCase()
                                    + selectedOperation.getOperationName().substring(1), false, null);

                    ICompilationUnit cu = pack.createCompilationUnit("Activator.java",
                            createActivator().toString(), false, null);
                    cu.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
                    formatUnitSourceCode(cu, new SubProgressMonitor(monitor, 1));
                    cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));

                    // create Web service client file
                    ICompilationUnit client = pack.createCompilationUnit(
                            selectedOperation.getOperationName().substring(0, 1).toUpperCase()
                                    + selectedOperation.getOperationName().substring(1)
                                    + "WebServiceClient.java",
                            createClient().toString(), false, null);
                    client.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
                    formatUnitSourceCode(client, new SubProgressMonitor(monitor, 1));
                    client.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));

                }
                return Status.OK_STATUS;
            } catch (Exception ex) {
                ex.printStackTrace();
                return new Status(Status.ERROR, Activator.PLUGIN_ID, ex.getMessage());
            } finally {
                monitor.done();
            }

        }
    };

    // Get access to workspace
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    // Now execute the Jobs

    try {
        // Execute the first job (create maven)
        job1.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
        job1.schedule();
        // MNGECLIPSE-766 wait until new project is created

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:org.wso2.developerstudio.eclipse.utils.jdt.JavaUtils.java

License:Open Source License

public static void addJavaSourceFolder(IFolder sourceFolder, IJavaProject javaProject)
        throws CoreException, JavaModelException {
    ProjectUtils.createFolder(sourceFolder);
    int ClASSPATH_ENTRY_KIND = 3;
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourceFolder);
    IClasspathEntry[] oldEntries = getClasspathEntries(javaProject);
    List<IClasspathEntry> validEntries = new ArrayList<IClasspathEntry>();
    for (IClasspathEntry classpathEntry : oldEntries) {
        if (ClASSPATH_ENTRY_KIND != classpathEntry.getEntryKind()) {
            validEntries.add(classpathEntry);
        }//  ww w  .  ja v  a2  s .  c  o  m
    }
    validEntries.add(JavaCore.newSourceEntry(root.getPath()));
    javaProject.setRawClasspath(validEntries.toArray(new IClasspathEntry[] {}), null);
}

From source file:qwickie.hyperlink.WicketHyperlink.java

License:Apache License

public static List<String> getHtmlFiles(final IResource openedResource) {
    Assert.isNotNull(openedResource);//  w w w  .  j  av  a2 s.co m
    final IProject project = openedResource.getProject();
    List<String> htmlFilenames = new ArrayList<String>();
    final String filename = openedResource.getFullPath().removeFileExtension().addFileExtension(HTML)
            .toPortableString();

    final IFile file = getFile(filename);
    // is there a html file in the same folder?
    if (file != null && file.exists()) {
        htmlFilenames.add(filename);
    } else { // if not, search for one with the same name
        final FileSearcher fs = new FileSearcher(project, new Path(filename).lastSegment());
        try {
            final IJavaProject javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
            final IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
            project.accept(fs);
            for (final IFile foundFile : fs.getFoundFiles()) {
                for (final IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) {
                    if (packageFragmentRoot.getKind() == 1) { // if it's in a source folder
                        if (packageFragmentRoot.getPath().segment(1)
                                .equals(foundFile.getFullPath().segment(1))) { // starting with /src
                            htmlFilenames.add(foundFile.getFullPath().toPortableString());
                        }
                    }
                }
            }
        } catch (final CoreException e1) {
        }
    }
    FileSearcher fs = new FileSearcher(project, new Path(filename).removeFileExtension().lastSegment() + "$*");
    try {
        project.accept(fs);
        for (final IFile foundFile : fs.getFoundFiles()) {
            htmlFilenames.add(foundFile.getFullPath().toPortableString());
        }
    } catch (CoreException e) {
    }

    Collections.reverse(htmlFilenames);
    return htmlFilenames;
}

From source file:qwickie.util.FileSearcher.java

License:Apache License

/** return the list of IPath configured as source folders in the project */
public static List<IPath> getSourceFolders(final IProject project) {
    Assert.isNotNull(project);// www  .j  a v a2 s .c  o m
    final List<IPath> srcFolders = new ArrayList<IPath>();
    IJavaProject javaProject;
    try {
        javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
        final IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
        for (final IPackageFragmentRoot pfr : packageFragmentRoots) {
            if (pfr.getKind() == IPackageFragmentRoot.K_SOURCE) {
                srcFolders.add(pfr.getPath());
            }
        }
    } catch (final CoreException e) {
    }
    return srcFolders;
}

From source file:qwickie.util.FileSearcher.java

License:Apache License

/**
 * Checks whether the two resources are in the same relative path to their respective source folders. The resources have to be in the same (java) project.
 * returns true if the resources have the same relative path, false in all other cases.
 * /*ww  w .j ava2s.c  o  m*/
 * @param one
 *            , the one resource you would like to check
 * @param other
 *            , the one resource you would like to check
 * @return true for resources in the same relative path, false otherwise.
 */
public static boolean haveSameRelativePathToParentSourceFolder(final IResource one, final IResource other) {
    // both resources have to be non-null
    if (one == null || other == null) {
        return false;
    }

    IProject project = one.getProject();
    // if the resources are in different projects, return false
    if (!project.equals(other.getProject())) {
        return false;
    }

    IJavaProject javaProject = null;
    try {
        javaProject = (IJavaProject) project.getNature(JavaCore.NATURE_ID);
    } catch (CoreException e) {
        // When it's not a java project, return false
        return false;
    }

    IPath onePath = one.getParent().getProjectRelativePath();
    IPath otherPath = other.getParent().getProjectRelativePath();

    IPath srcPath;
    boolean oneFound = false, otherFound = false;

    try {
        for (IPackageFragmentRoot pfr : javaProject.getPackageFragmentRoots()) {
            if (pfr.getKind() == 1) {
                // we've got a source path
                // remove the first segment, since that's the project folder.
                srcPath = pfr.getPath().removeFirstSegments(1);
                if (!oneFound && srcPath.isPrefixOf(onePath)) {
                    // remove the sourcepath from this path
                    onePath = onePath.removeFirstSegments(srcPath.segmentCount());
                    oneFound = true;
                }
                if (!otherFound && srcPath.isPrefixOf(otherPath)) {
                    // remove the sourcepath from this path
                    otherPath = otherPath.removeFirstSegments(srcPath.segmentCount());
                    otherFound = true;
                }
            }
            if (oneFound && otherFound) {
                break;
            }
        }
    } catch (JavaModelException e) {
        return false;
    }

    // return true if both paths are the same
    return onePath.equals(otherPath);
}

From source file:sharpen.ui.popup.actions.ConvertPackageAction.java

License:Open Source License

protected void safeRun() throws Throwable {
    IPackageFragmentRoot root = (IPackageFragmentRoot) _selection.getFirstElement();

    List<ICompilationUnit> units = new ArrayList<ICompilationUnit>();
    JavaModelUtility.collectCompilationUnits(units, root);

    scheduleConversionJob("C# Conversion of package '" + root.getPath() + "'", units, root.getJavaProject());
}

From source file:x10dt.ui.wizards.NewX10PackageWizardPage.java

License:Open Source License

private IStatus packageChanged() {
    StatusInfo status = new StatusInfo();
    String packName = getPackageText();
    if (packName.length() > 0) {
        IStatus val = JavaConventions.validatePackageName(packName);
        if (val.getSeverity() == IStatus.ERROR) {
            status.setError(MessageFormat
                    .format(NewWizardMessages.NewPackageWizardPage_error_InvalidPackageName, val.getMessage()));
            return status;
        } else if (val.getSeverity() == IStatus.WARNING) {
            status.setWarning(MessageFormat.format(
                    NewWizardMessages.NewPackageWizardPage_warning_DiscouragedPackageName, val.getMessage()));
        }//from   w ww .  j  a  v  a  2s  .co  m
    } else {
        status.setError(NewWizardMessages.NewPackageWizardPage_error_EnterName);
        return status;
    }

    IPackageFragmentRoot root = getPackageFragmentRoot();
    if (root != null && root.getJavaProject().exists()) {
        IPackageFragment pack = root.getPackageFragment(packName);
        try {
            IPath rootPath = root.getPath();
            IPath outputPath = root.getJavaProject().getOutputLocation();
            if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
                // if the bin folder is inside of our root, don't allow to
                // name a package
                // like the bin folder
                IPath packagePath = pack.getPath();
                if (outputPath.isPrefixOf(packagePath)) {
                    status.setError(NewWizardMessages.NewPackageWizardPage_error_IsOutputFolder);
                    return status;
                }
            }
            if (pack.exists()) {
                if (pack.containsJavaResources() || !pack.hasSubpackages()) {
                    status.setError(NewWizardMessages.NewPackageWizardPage_error_PackageExists);
                } else {
                    status.setError(NewWizardMessages.NewPackageWizardPage_error_PackageNotShown);
                }
            }
            // 11/14/2007 RMF disabled to avoid dependency on EFS for now
            else {
                URI location = URIUtils.getExpectedURI(pack.getResource().getLocationURI());
                if (location != null) {
                    IFileStore store = EFS.getStore(location);
                    if (store.fetchInfo().exists()) {
                        status.setError(
                                NewWizardMessages.NewPackageWizardPage_error_PackageExistsDifferentCase);
                    }
                }
            }
        } catch (CoreException e) {
            X10DTCorePlugin.getInstance().logException(e.getMessage(), e);
        }
    }
    return status;
}

From source file:Xtext2SonarM2T.launcher.popupMenus.AcceleoGenerateGenerateSonarQubePluginAction.java

License:Open Source License

private void addSourceFolder(IProject project, IPath[] excludePatterns, IFolder sourcefolder,
        IProgressMonitor monitor) throws JavaModelException {
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(sourcefolder);
    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    System.out.println("Root path: " + root.getPath());
    System.out/*from ww w  .j a v  a2 s  . co  m*/
            .println("Exclude paths: " + excludePatterns[0].toString() + " - " + excludePatterns[1].toString());
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath(), excludePatterns);
    javaProject.setRawClasspath(newEntries, monitor);
}