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:net.rim.ejde.internal.ui.wizards.NewResourceFileWizardPage.java

License:Open Source License

@Override
protected boolean validatePage() {
    // perform preliminary page validation with
    // WizardNewFileCreationPage.validatePage() method
    boolean validPage = super.validatePage();

    if (validPage) {
        if (!getFileName().matches("([A-Za-z0-9]+([_][A-Za-z0-9]+){0,2}.rrc)|([A-Za-z0-9]+.rrh)")) {
            setErrorMessage(Messages.INVALID_FILE_NAME);
            validPage = false;/*from   www. j av a  2  s.  c om*/
        }
    }

    if (validPage) {
        /* ensures the user selected a package under an eclipse source directory */
        boolean sourceFolderExists = false;
        _userSelectedProject = getContainerFullPath().segment(0);
        String path = getContainerFullPath().toString();

        IPackageFragmentRoot sourceRoots[] = ProjectUtils
                .getProjectSourceFolders(ProjectUtils.getProject(_userSelectedProject));
        // Iterate through all source folders
        for (IPackageFragmentRoot sourceRoot : sourceRoots) {
            String sourcePath = sourceRoot.getPath().toString() + IPath.SEPARATOR;
            if (path.startsWith(sourcePath) && (path.length() > sourcePath.length())) {
                String selectedPackage = path.substring(sourcePath.length()).replaceAll("/", "."); //$NON-NLS-1$ //$NON-NLS-2$
                // Since our current code standard is 1.5 do not use 1.6 methods yet.
                if (!StringUtils.isEmpty(selectedPackage)
                        && sourceRoot.getPackageFragment(selectedPackage).exists()) {
                    sourceFolderExists = true;
                    _userSelectedPackage = sourceRoot.getPackageFragment(selectedPackage);
                    _userSelectedSourceFolder = sourceRoot;
                    break;
                }
            }
        }
        if (!sourceFolderExists) {
            setErrorMessage(Messages.INVALID_PARENT_FOLDER_WIZARD_PAGE);
            validPage = false;
        }
    }

    if (validPage) {
        try {
            /*
             * Here we get access to the private field linkedResourceGroup and get the URI information for the linked .rrh
             * file. We then parse that file to get its package information
             */
            Field field = WizardNewFileCreationPage.class.getDeclaredField("linkedResourceGroup"); //$NON-NLS-1$
            field.setAccessible(true);
            linkFileLocation = ((CreateLinkedResourceGroup) field.get(this)).getLinkTargetURI();

            // If file is not linked, skip next code.
            if (linkFileLocation == null) {
                _validPackage = true;
            } else {
                // Initialize the resourcePackageID to properly identify if the package is valid
                _resourcePackageId = null;

                File linkFile = new File(linkFileLocation);
                if (getFileName().endsWith(ResourceConstants.RRH_SUFFIX)) {
                    /*
                     * Resource file is a rrh file. We must determine if its going in the correct package.
                     */
                    if (linkFile.length() == 0) {
                        setErrorMessage(Messages.RRH_NO_PACKAGE_ERROR);
                        return false;
                    }
                    _resourcePackageId = PackageUtils.getRRHPackageID(linkFile);

                } else {
                    /*
                     * Resource file is a rrc file. We must determine the correct package with its corresponding rrh file.
                     */
                    String rrhFileName = getFileName();

                    if (rrhFileName.contains("_")) { //$NON-NLS-1$
                        rrhFileName = rrhFileName.substring(0, rrhFileName.indexOf("_")) //$NON-NLS-1$
                                + ResourceConstants.RRH_SUFFIX;
                    } else {
                        rrhFileName = rrhFileName.replace(ResourceConstants.RRC_SUFFIX,
                                ResourceConstants.RRH_SUFFIX);
                    }

                    File rrhFile = new File(linkFile.getParent() + File.separator + rrhFileName);
                    if (rrhFile.exists() && (rrhFile.length() != 0)) {
                        _resourcePackageId = PackageUtils.getRRHPackageID(rrhFile);
                    }
                }

                /*
                 * Get package selected by user within the new resource wizard dialog and ensure it matches the package
                 * described in the .rrh file.
                 */
                _userSelectedProject = getContainerFullPath().segment(0);
                if (_resourcePackageId == null) {
                    /*
                     * Resource header file could not be found or contains no package. Ensuring correct package will have to
                     * be left to user.
                     */
                    _validPackage = true;
                } else if (!_resourcePackageId.equals(_userSelectedPackage.getElementName())) {
                    setMessage(NLS.bind(Messages.INVALID_PACKAGE_SELECTED, _resourcePackageId),
                            IMessageProvider.WARNING);
                    _validPackage = false;
                } else {
                    _validPackage = true;
                }
            }
        } catch (Throwable e) {
            logger.error("Validation Error", e); //$NON-NLS-1$
        }
    }
    if (validPage) {
        // Add warning if existing sibling resource exist
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(_userSelectedProject);
        IFile foundSiblingFile = getSiblingFile(getFileName(), project);

        if (foundSiblingFile != null) {
            if (foundSiblingFile.isLinked()) {
                setMessage(NLS.bind(Messages.EXISTING_LINKED_SIBLING_FOUND_WARNING, foundSiblingFile.getName(),
                        getFileName()), IMessageProvider.WARNING);
            } else {
                setMessage(NLS.bind(Messages.EXISTING_COPIED_SIBLING_FOUND_WARNING, foundSiblingFile.getName(),
                        getFileName()), IMessageProvider.WARNING);
            }
        }
    }
    return validPage;
}

From source file:net.roamstudio.roamflow.wizard.NewProjectWizard.java

License:Open Source License

private void addSourceFolder(IJavaProject javaProject, List<IClasspathEntry> entries, String path)
        throws CoreException {
    IFolder folder = javaProject.getProject().getFolder(path);
    createFolder(folder);/*from  w w  w.  ja v a  2 s.  c om*/
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);
    entries.add(JavaCore.newSourceEntry(root.getPath()));
}

From source file:net.sf.eclipse.tomcat.VMLauncherUtility.java

License:Open Source License

private static ISourceLocator getSourceLocator(boolean trace) throws CoreException {
    ArrayList tempList = new ArrayList();
    StringBuffer traceBuffer = new StringBuffer();

    traceBuffer.append("Projects in source path :\n");
    List projects = TomcatLauncherPlugin.getDefault().getProjectsInSourcePath();
    for (Iterator iter = projects.iterator(); iter.hasNext();) {
        IProject project = ((ProjectListElement) iter.next()).getProject();
        traceBuffer.append("Project " + project.getName());
        if ((project.isOpen()) && project.hasNature(JavaCore.NATURE_ID)) {
            tempList.add(project.getNature(JavaCore.NATURE_ID));
            traceBuffer.append(" added to tempList\n");
        }//  www  .j ava 2s.  c o m
    }

    ISourceLookupDirector sourceLocator = null;

    sourceLocator = new JavaSourceLookupDirector();
    ISourcePathComputer computer = DebugPlugin.getDefault().getLaunchManager()
            .getSourcePathComputer("org.eclipse.jdt.launching.sourceLookup.javaSourcePathComputer");
    sourceLocator.setSourcePathComputer(computer); //$NON-NLS-1$

    ArrayList sourceContainers = new ArrayList();

    if (!tempList.isEmpty()) {
        IJavaProject[] javaProjects = (IJavaProject[]) tempList.toArray(new IJavaProject[1]);

        // Eclipse stops looking for source if it finds a jar containing the source code
        // despite this jar as no attached source (the user will have to use 'Attach source' button).
        // So we have to enforce that sources in project are searched before jar files,
        // To do so we add source containers in this orders :
        // - First project source containers.
        // - second packageFragmentRoot container (jar files in projects build path will be added to source path)
        // - third DefaultSourceContainer (jar files added to classpath will be added to source path)

        // First add all projects source containers
        for (int i = 0; i < javaProjects.length; i++) {
            IJavaProject project = javaProjects[i];
            traceBuffer
                    .append("  -> Add JavaProjectSourceContainer for " + project.getProject().getName() + "\n");
            sourceContainers.add(new JavaProjectSourceContainer(project));
        }

        // Adding packageFragmentRoot source containers, so classes in jar files associated to a project will be seen 
        HashSet external = new HashSet();

        for (int i = 0; i < javaProjects.length; i++) {
            IJavaProject project = javaProjects[i];
            traceBuffer.append("  -> Compute SourceContainers for " + project.getProject().getName() + " :\n");

            IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
            for (int ri = 0; ri < roots.length; ri++) {
                IPackageFragmentRoot root = roots[ri];
                if (root.isExternal()) {
                    IPath location = root.getPath();
                    if (external.contains(location)) {
                        continue;
                    }
                    external.add(location);
                }
                sourceContainers.add(new PackageFragmentRootSourceContainer(root));
                traceBuffer.append(
                        "     RootSourceContainer created for : " + root.getPath().toPortableString() + "\n");
            }
        }
    }

    // Last add DefaultSourceContainer, classes in jar files added to classpath will be visible
    sourceContainers.add(new DefaultSourceContainer());

    sourceLocator.setSourceContainers(
            (ISourceContainer[]) sourceContainers.toArray(new ISourceContainer[sourceContainers.size()]));
    sourceLocator.initializeParticipants();

    if (trace)
        TomcatLauncherPlugin.log(traceBuffer.toString());
    return sourceLocator;
}

From source file:nz.ac.vuw.ecs.kcassell.GroovyTestProject.java

License:Apache License

private IPackageFragmentRoot createSourceFolder() throws CoreException {
    IFolder folder = project.getFolder("src");
    if (!folder.exists())
        ensureExists(folder);/*w  w w  .j a  v a  2  s. c o  m*/
    final IClasspathEntry[] entries = javaProject.getResolvedClasspath(false);
    final IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);
    for (int i = 0; i < entries.length; i++) {
        final IClasspathEntry entry = entries[i];
        if (entry.getPath().equals(folder.getFullPath()))
            return root;
    }
    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:nz.ac.vuw.ecs.kcassell.GroovyTestProject.java

License:Apache License

public IPackageFragmentRoot createSourceFolder(String path, String outPath, IPath[] exclusionPattern)
        throws CoreException {
    IFolder folder = project.getFolder(path);
    if (!folder.exists()) {
        ensureExists(folder);//from  ww  w  .  ja v a 2  s .  c om
    }

    final IClasspathEntry[] entries = javaProject.getResolvedClasspath(false);
    final IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);
    for (int i = 0; i < entries.length; i++) {
        final IClasspathEntry entry = entries[i];
        if (entry.getPath().equals(folder.getFullPath())) {
            return root;
        }
    }
    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    IPath outPathPath = outPath == null ? null : getProject().getFullPath().append(outPath).makeAbsolute();
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath(), exclusionPattern, outPathPath);
    javaProject.setRawClasspath(newEntries, null);
    return root;

}

From source file:org.agilereview.test.common.utils.TmpJavaProject.java

License:Open Source License

/**
 * Creates the source folder for a valid java project
 * @throws CoreException if an error occurs while creating the source folder
 * @author Malte Brunnlieb (09.07.2012)//from ww w.ja v  a2 s.c  o  m
 */
private void createSourceFolder() throws CoreException {
    IFolder sourceFolder = javaProject.getProject().getFolder("src");
    sourceFolder.create(true, true, new NullProgressMonitor());

    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, new NullProgressMonitor());
}

From source file:org.apache.tapestrytools.ui.internal.tcc.editor.Utils.java

License:Open Source License

public static Set<IJavaElement> getSrcDirectories(IProject project) {
    Set<IJavaElement> list = new HashSet<IJavaElement>();
    try {/*www . j a  v  a  2s. co m*/
        IPackageFragmentRoot[] sourceFolders = JavaCore.create(project).getAllPackageFragmentRoots();
        for (int i = 0; i < sourceFolders.length; i++) {
            IPackageFragmentRoot item = sourceFolders[i];
            String jarPath = item.getPath().toString();
            String jarName = jarPath.substring(jarPath.lastIndexOf('/'));
            if (sourceFolders[i].getResource() != null && !sourceFolders[i].isArchive()
                    || item.isArchive() && jarPath.endsWith(".jar") && !BLOCKED_JARS.contains(jarName)) {
                IJavaElement[] eles = sourceFolders[i].getChildren();
                for (IJavaElement ele : eles) {
                    if (!ele.getElementName().trim().isEmpty())
                        list.add(ele);
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return list;
}

From source file:org.apache.tapestrytools.ui.internal.wizards.AddTapestryComponentWizard.java

License:Open Source License

/**
 * The worker method. It will find the container, create the file if missing
 * or just replace its contents, and open the editor on the newly created
 * file.//from  ww w . j  ava 2s. c  o  m
 */

private void doFinish(String projectName, String folderName, String packageName, String className,
        boolean createTemplate, IProgressMonitor monitor) throws CoreException {
    IProject project = ResourcesPlugin.getWorkspace().getRoot().findMember(projectName).getProject();//ProjectUtilities.getProject(projectName);
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot src = null;
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (IPackageFragmentRoot pfr : roots) {
        if (pfr.getPath().toString().equals(folderName)) {
            src = pfr;
            break;
        }
    }
    monitor.beginTask("Creating " + className, 3);
    IPackageFragment aimPackage = src.getPackageFragment(packageName);
    String classContent = "package " + packageName + ";\n\n";
    classContent += "public class " + className + " {\n\n";
    classContent += "}";
    aimPackage.createCompilationUnit(className + ".java", classContent, false, null);
    monitor.worked(1);

    if (createTemplate) {
        IPath templatePath = aimPackage.getPath();
        if (TapestryWizardUtils.isMavenProject(project)) {
            String javaPath = aimPackage.getPath().toString();
            String temPath = javaPath;
            if (javaPath.indexOf("/main/java/") > -1) {
                temPath = javaPath.replace("/main/java/", "/main/resources/");
            } else if (javaPath.indexOf("/test/java/") > -1) {
                temPath = javaPath.replace("/test/java/", "/test/resources/");
            }
            IPath tmpPath = new Path(temPath);
            if (tmpPath.isValidPath(temPath)) {
                templatePath = tmpPath;
            }
        }

        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        final IFile file = root.getFile(templatePath.append(className + ".tml"));
        try {
            InputStream stream = openContentStream();
            if (file.exists()) {
                file.setContents(stream, true, true, monitor);
            } else {
                file.create(stream, true, monitor);
            }
            stream.close();
        } catch (IOException e) {
        }
        monitor.worked(1);
        monitor.setTaskName("Opening file for editing...");
        getShell().getDisplay().asyncExec(new Runnable() {
            public void run() {
                IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                try {
                    IDE.openEditor(page, file, true);
                } catch (PartInitException e) {
                }
            }
        });
    }

    monitor.worked(1);

}

From source file:org.apache.tapestrytools.ui.internal.wizards.AddTapestryPageWizard.java

License:Open Source License

/**
 * The worker method. It will find the container, create the file if missing
 * or just replace its contents, and open the editor on the newly created
 * file.// w ww  .  jav a2s . c om
 */
private void doFinish(String projectName, String folderName, String packageName, String className,
        IProgressMonitor monitor) throws CoreException {
    IProject project = ResourcesPlugin.getWorkspace().getRoot().findMember(projectName).getProject();//ProjectUtilities.getProject(projectName);
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot src = null;
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (IPackageFragmentRoot pfr : roots) {
        if (pfr.getPath().toString().equals(folderName)) {
            src = pfr;
            break;
        }
    }
    monitor.beginTask("Creating " + className, 3);
    IPackageFragment aimPackage = src.getPackageFragment(packageName);
    String classContent = "package " + packageName + ";\n\n";
    classContent += "public class " + className + " {\n\n";
    classContent += "}";

    aimPackage.createCompilationUnit(className + ".java", classContent, false, null);
    monitor.worked(1);

    IPath templatePath = aimPackage.getPath();
    if (TapestryWizardUtils.isMavenProject(project)) {
        String javaPath = aimPackage.getPath().toString();
        String temPath = javaPath;
        if (javaPath.indexOf("/main/java/") > -1) {
            temPath = javaPath.replace("/main/java/", "/main/resources/");
        } else if (javaPath.indexOf("/test/java/") > -1) {
            temPath = javaPath.replace("/test/java/", "/test/resources/");
        }
        IPath tmpPath = new Path(temPath);
        if (tmpPath.isValidPath(temPath)) {
            templatePath = tmpPath;
        }
    }

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IFile pageFile = root.getFile(templatePath.append(className + ".tml"));

    final IFile file = pageFile;
    try {
        InputStream stream = openContentStream();
        if (file.exists()) {
            file.setContents(stream, true, true, monitor);
        } else {
            file.create(stream, true, monitor);
        }
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    monitor.worked(1);
    monitor.setTaskName("Opening file for editing...");
    getShell().getDisplay().asyncExec(new Runnable() {
        public void run() {
            IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
            try {
                IDE.openEditor(page, file, true);
            } catch (PartInitException e) {
            }
        }
    });
    monitor.worked(1);

}

From source file:org.apache.tapestrytools.ui.internal.wizards.NewTapestryComponentPage.java

License:Open Source License

/**
 * Add package group to composite/*  w  ww  . j  a  va  2  s .com*/
 */
private void addPackageGroup(Composite composite) {
    // package
    packageLabel = new Label(composite, SWT.LEFT);
    packageLabel.setText("Package");
    packageLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));

    packageText = new Text(composite, SWT.SINGLE | SWT.BORDER);
    packageText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    IPackageFragment packageFragment = getSelectedPackageFragment();
    String targetProject = projectNameCombo.getText();
    if (packageFragment != null && packageFragment.exists()
            && packageFragment.getJavaProject().getElementName().equals(targetProject)) {
        IPackageFragmentRoot root = getPackageFragmentRoot(packageFragment);
        model.put("JAVA_PACKAGE_FRAGMENT_ROOT", root);
        if (root != null)
            folderText.setText(root.getPath().toString());
        //model.put(INewJavaClassDataModelProperties.JAVA_PACKAGE, packageFragment.getElementName());
        packageText.setText(packageFragment.getElementName());
    }

    packageButton = new Button(composite, SWT.PUSH);
    packageButton.setText("Browse");
    packageButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    packageButton.addSelectionListener(new SelectionListener() {
        public void widgetSelected(SelectionEvent e) {
            handlePackageButtonPressed();
        }

        public void widgetDefaultSelected(SelectionEvent e) {
            // Do nothing
        }
    });
}