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.eclipselabs.spray.xtext.ui.commands.ActivateExtension.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
    ICompilationUnit cu = (ICompilationUnit) selection.getFirstElement();
    IPackageFragmentRoot pfRoot = projectUtil.getPackageFragmentRoot(cu);
    if (projectUtil.isGeneratedExtensionFile(cu)) {
        IJavaProject project = pfRoot.getJavaProject();
        try {//from   w  w  w . ja  v  a2  s  . c o m
            IPackageFragmentRoot srcFolder = projectUtil.getSrcManPackageFragmentRoot(project);
            IPath targetPath = srcFolder.getPath().append(cu.getPath().makeRelativeTo(pfRoot.getPath()));
            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            // assure intermediate packages exist
            for (int i = 2; i < targetPath.segmentCount() - 1; i++) {
                if (!root.exists(targetPath.removeLastSegments(targetPath.segmentCount() - 1 - i))) {
                    root.getFolder(targetPath.removeLastSegments(targetPath.segmentCount() - 1 - i))
                            .create(true, true, new NullProgressMonitor());
                }
            }
            cu.getResource().move(targetPath, true, new NullProgressMonitor());
            root.findMember(targetPath).setDerived(false, new NullProgressMonitor());
            IFile targetFile = (IFile) root.findMember(targetPath);
            IEditorInput editorInput = new FileEditorInput(targetFile);
            IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
            IWorkbenchPage page = window.getActivePage();
            page.openEditor(editorInput, "org.eclipse.jdt.ui.CompilationUnitEditor");
            //cu.move(srcFolder, null, null, false, new NullProgressMonitor());
        } catch (CoreException e) {
            throw new ExecutionException(e.getMessage(), e);
        }
    } else {

    }
    return null;
}

From source file:org.eclipselabs.spray.xtext.ui.commands.SprayJavaProjectUtil.java

License:Open Source License

public boolean hasGeneratedBaseClass(ICompilationUnit cu) {
    IPackageFragmentRoot pfRoot = null;
    try {//from ww  w  .j  a v a  2s.c  o  m
        pfRoot = getSrcGenPackageFragmentRoot(cu.getJavaProject());
        if (pfRoot == null)
            return false;
    } catch (JavaModelException e) {
        return false;
    }

    // compute the relative path of this resource
    IPath relativePath = cu.getPath().makeRelativeTo(getPackageFragmentRoot(cu).getPath());
    IPath baseClassPath = new Path(
            pfRoot.getPath().append(relativePath.removeFileExtension()).toString() + "Base.java");
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    boolean baseClassExists = root.findMember(baseClassPath) != null;
    return baseClassExists;
}

From source file:org.entirej.ide.core.cf.CFProjectHelper.java

License:Apache License

/**
 * Adds a source container to a IJavaProject.
 *//*from  ww  w.  j  a v  a  2 s. c o  m*/
public static IPackageFragmentRoot verifySourceContainer(IJavaProject jproject, String containerName)
        throws CoreException {
    IProject project = jproject.getProject();
    IContainer container = null;
    if (containerName == null || containerName.length() == 0) {
        container = project;
    } else {
        IFolder folder = project.getFolder(containerName);
        if (!folder.exists()) {
            folder.create(false, true, null);
        }
        container = folder;
    }
    IPackageFragmentRoot root = jproject.getPackageFragmentRoot(containerName);
    if (root != null) {
        root = jproject.getPackageFragmentRoot(container);

        IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath());
        addToClasspath(jproject, cpe);
    }
    return root;
}

From source file:org.entirej.ide.ui.editors.descriptors.AbstractProjectSrcFileDescriptor.java

License:Apache License

@Override
public String browseType() {
    List<IPackageFragmentRoot> elements = new ArrayList<IPackageFragmentRoot>();
    IJavaProject javaProject = projectProvider.getJavaProject();
    try {/*from  www  .  j a  v  a2 s.c  o m*/
        IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
        for (int i = 0; i < roots.length; i++) {
            if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                elements.add(roots[i]);

            }
        }
    } catch (JavaModelException e) {
        EJCoreLog.logException(e);
    }

    final List<IResource> resources = new ArrayList<IResource>();
    for (IPackageFragmentRoot root : elements) {
        try {
            IResource resource = root.getResource();
            if (resource instanceof IContainer)
                ((IContainer) resource).accept(new IResourceProxyVisitor() {
                    public boolean visit(IResourceProxy proxy) {

                        if (proxy.isDerived()) {
                            return false;
                        }
                        int type = proxy.getType();
                        if ((IResource.FILE & type) != 0) {

                            IResource res = proxy.requestResource();

                            resources.add(res);
                            return true;

                        }
                        if (type == IResource.FILE) {
                            return false;
                        }
                        return true;
                    }
                }, IResource.NONE);
        } catch (CoreException e) {
            // ignore
        }
    }

    ResourceListSelectionDialog dialog = new ResourceListSelectionDialog(EJUIPlugin.getActiveWorkbenchShell(),
            resources.toArray(new IResource[0]));

    dialog.setTitle("Select File");
    dialog.setMessage("Select a project file:");

    if (dialog.open() == Window.OK) {
        Object[] result = dialog.getResult();
        if (result != null && result.length > 0) {
            IResource resource = (IResource) result[0];

            String chosenPath = resource.getFullPath().toPortableString();

            // Return the chosen package without the source directory path

            for (IPackageFragmentRoot root : elements) {
                String sourcePath = root.getPath().toPortableString();
                if (chosenPath.startsWith(sourcePath)) {
                    chosenPath = chosenPath.replace(sourcePath, "");
                    break;
                }
            }
            return chosenPath;
        }
    }

    return getValue();
}

From source file:org.evolizer.core.util.projecthandling.JavaProjectHelper.java

License:Apache License

/**
 * Adds a source folder.//from ww  w  .j  ava2  s  .c o m
 * 
 * @param sourceFolderName
 *            the source folder name
 * @param progressMonitor
 *            the progress monitor
 * @throws CoreException
 *             if this method fails. Reasons include:
 *             <ul>
 *             <li>A project could not be deleted.</li>
 *             <li>A project's contents could not be deleted.</li>
 *             <li>Resource changes are disallowed during certain types of resource change event notification.</li>
 *             </ul>
 */
public void addSourceFolder(String sourceFolderName, IProgressMonitor progressMonitor) throws CoreException {

    IProgressMonitor monitor = (progressMonitor == null) ? new NullProgressMonitor() : progressMonitor;

    try {
        monitor.beginTask("Creating Source Folder: " + sourceFolderName, 2);

        IFolder folder = fProject.getFolder(sourceFolderName);
        createFolderStructure(folder);
        monitor.worked(1);

        monitor.setTaskName("Adding Source Folder to Classpath");
        IPackageFragmentRoot root = fJavaProject.getPackageFragmentRoot(folder);
        IClasspathEntry[] oldEntries = fJavaProject.getRawClasspath();
        IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
        System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
        newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
        fJavaProject.setRawClasspath(newEntries, null);
        monitor.worked(1);
    } finally {
        monitor.done();
    }
}

From source file:org.evosuite.eclipse.popup.actions.TestGenerationAction.java

License:Open Source License

/**
 * Main action: check if evosuite-tests exists, and add test generation job
 * //from  w  ww . j a va 2 s.  co  m
 * @param target
 */
public void generateTests(IResource target) {
    Boolean disabled = System.getProperty("evosuite.disable") != null; //  && System.getProperty("evosuite.disable").equals("1")
    if (disabled) {
        MessageDialog.openInformation(shell, "Sorry!", "The EvoSuite Plugin is disabled :(");
        return;
    }
    System.out.println("EvoSuite Plugin is enabled");
    System.out.println("[TestGenerationAction] Generating tests for " + target.toString());
    IFolder folder = target.getProject().getFolder("evosuite-tests");
    if (!folder.exists()) {
        // Create evosuite-tests directory and add as source folder
        try {
            folder.create(false, true, null);
            IJavaProject jProject = JavaCore.create(target.getProject());

            IPackageFragmentRoot root = jProject.getPackageFragmentRoot(folder);
            IClasspathEntry[] oldEntries = jProject.getRawClasspath();
            IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
            System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
            newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
            jProject.setRawClasspath(newEntries, null);

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    addTestJob(target);
}

From source file:org.fastcode.util.CreateSimilarDescriptor.java

License:Open Source License

/**
 *
 * @param type/*  ww  w.j av a 2 s. co  m*/
 * @param pattern
 * @return
 */
private static boolean isValidType(final IType type, final String pattern) {
    String path = EMPTY_STR;
    if (pattern.startsWith(FORWARD_SLASH)) {
        final IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type.getPackageFragment()
                .getParent();
        path = packageFragmentRoot.getPath().toString();
        path = path.substring(type.getJavaProject().getElementName().length() + 1);
        if (!pattern.startsWith(path)) {
            path += FORWARD_SLASH + type.getJavaProject().getElementName();
            if (!pattern.startsWith(path)) {
                return false;
            }
        }
    }

    if (!isEmpty(path)) {
        path += FORWARD_SLASH;
    }

    final Pattern pattrn = Pattern.compile(pattern);
    final Matcher m = pattrn.matcher(path + type.getFullyQualifiedName());

    return m.matches();
}

From source file:org.fastcode.util.SourceUtil.java

License:Open Source License

/**
 *
 * @param project/*from   w  ww.j a  va  2s . co  m*/
 * @param paramType
 * @return
 * @throws Exception
 */
public static Object getElementFromProject(final IJavaProject project, final String paramType,
        final String filter) throws Exception {

    IType type = project.findType(paramType);
    if (type != null && type.exists()) {
        return type;
    }

    IFile file = project.getProject().getFile(paramType);
    if (file != null && file.exists()) {
        return file;
    }

    final IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
    int nClasses = 0;

    for (final IPackageFragmentRoot root : roots) {
        if (root.getElementName() != null && filter != null && root.getElementName().endsWith(filter)) {
            continue;
        }
        final IJavaElement[] elements = root.getChildren();
        for (int i = 0; i < elements.length; i++) {
            final IJavaElement element = elements[i];
            final IPackageFragment fragment = (IPackageFragment) element.getAdapter(IPackageFragment.class);
            if (fragment == null) {
                continue;
            }

            // TODO redo this logic later with JavaCore.create(file)
            String path = fragment.getPath().toString();
            if (path.length() > root.getPath().toString().length()) {
                path = path.substring(root.getPath().toString().length() + 1);
            }

            final String newpath = path.replaceAll(FORWARD_SLASH, "\\.");

            if (paramType.startsWith(newpath)) {
                String tmpName = paramType.replaceFirst(newpath, path);
                tmpName = tmpName.replaceFirst("\\.", FORWARD_SLASH);
                tmpName = root.getPath().toString() + FORWARD_SLASH + tmpName;
                tmpName = tmpName.substring(project.getProject().getName().length() + 1);
                final IResource resource = project.getProject().findMember(tmpName);
                // JavaCore.create(file);

                if (resource != null && resource.exists()) {
                    return resource;
                }
            }

            final IJavaElement fes[] = fragment.getChildren();

            for (int j = 0; j < fes.length; j++) {
                final String className = fes[j].getElementName();

                final int elementType = fes[j].getElementType();
                if (elementType == TYPE) {
                    type = (IType) fes[j];
                } else if (elementType == COMPILATION_UNIT) {
                    type = ((ICompilationUnit) fes[j]).findPrimaryType();
                } else if (elementType == CLASS_FILE) {
                    type = ((IClassFile) fes[j]).findPrimaryType();
                } else if (elementType == IResource.FILE) {
                    file = (IFile) fes[j];
                }

                if (type != null && type.getFullyQualifiedName().equals(paramType)) {
                    return type;
                } else if (file != null
                        && paramType.equals(fragment.getElementName() + DOT + fes[j].getElementName())) {
                    return file;
                }

                nClasses++;
            }
        }
    }
    final String projectName = project.getElementName();
    return null;
}

From source file:org.fastcode.util.SourceUtil.java

License:Open Source License

/**
 *
 * @param project/*from   ww  w.  jav  a 2s  .  c om*/
 * @param srcPath
 * @return
 * @throws Exception
 */
public static IPackageFragmentRoot getPackageRootFromProject(final IJavaProject project, final String srcPath)
        throws Exception {
    final IPackageFragmentRoot[] roots = getPackageRootsFromProject(project);
    for (final IPackageFragmentRoot root : roots) {
        // if (root.getPath().toString().equals("/" +
        // project.getElementName() + srcPath)) {
        if (root.getPath().toString().equals(FORWARD_SLASH + project.getElementName() + srcPath)) {
            return root;
        }
    }
    return null;
}

From source file:org.fastcode.util.SourceUtil.java

License:Open Source License

/**
 *
 * @param srcPath/*from  w  w w. j  a  va 2 s  .  c  o m*/
 * @param checkFullPath
 *
 * @return
 * @throws JavaModelException
 */
public static IPackageFragmentRoot getJavaElementFromSourcePathFromProject(final String srcPath,
        final IJavaProject javaProject, final boolean checkFullPath) throws JavaModelException {
    for (final IPackageFragmentRoot packageFragmentRoot : javaProject.getAllPackageFragmentRoots()) {
        final String rootPath = packageFragmentRoot.getPath().toString();
        if (srcPath.equals(
                checkFullPath ? rootPath : rootPath.substring(javaProject.getElementName().length() + 1))) {
            return packageFragmentRoot;
        }
    }
    return null;
}