Example usage for org.eclipse.jdt.core IJavaProject getPackageFragmentRoots

List of usage examples for org.eclipse.jdt.core IJavaProject getPackageFragmentRoots

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject getPackageFragmentRoots.

Prototype

IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException;

Source Link

Document

Returns all of the package fragment roots contained in this project, identified on this project's resolved classpath.

Usage

From source file:org.apache.metro.studio.eclipse.core.templateengine.test.DirectoryTemplateManagerTest.java

License:Apache License

/**
 * Test, whether libraries are added//  w ww.  ja va  2 s  .c om
 *
 */
public final void testStandardBlockClasspath() {
    int libCount = 0;
    int rootCount = 0;
    int sourceCount = 0;

    DirectoryTemplateManager m = DirectoryTemplateManager.load(configFileLocation);
    DirectoryTemplate template = m.getTemplate("StandardBlock");

    Vector sourceFolders = template.getSourceFolderNames();

    try {
        IJavaProject javaProject = JavaCore.create(project);
        IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();

        for (int i = 0; i < roots.length; i++) {
            rootCount++;
            if (roots[i].isArchive()) {
                libCount++;
            } else {
                sourceCount++;
            }
        }
    } catch (JavaModelException e) {
        fail("can't retrieve project libraries");
    }

    assertEquals("not all required sourcedirectories are created", sourceFolders.size(), sourceCount);

    BlockProjectManager.delete(project);
}

From source file:org.apache.metro.studio.eclipse.core.templateengine.test.DirectoryTemplateManagerTest.java

License:Apache License

/**
 * Test, whether libraries are added/*from  ww w . ja v a 2s.  co  m*/
 *
 */
public final void testImplApiBlockClasspath() {
    int libCount = 0;
    int rootCount = 0;
    int sourceCount = 0;

    DirectoryTemplateManager m = DirectoryTemplateManager.load(configFileLocation);
    DirectoryTemplate template = m.getTemplate("ImplApiBlock");

    Vector sourceFolders = template.getSourceFolderNames();

    try {
        IJavaProject javaProject = JavaCore.create(project);
        IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();

        for (int i = 0; i < roots.length; i++) {
            rootCount++;
            if (roots[i].isArchive()) {
                libCount++;
            } else {
                sourceCount++;
            }
        }
    } catch (JavaModelException e) {
        fail("can't retrieve project libraries");
    }

    assertEquals("not all required sourcedirectories are created", sourceFolders.size(), sourceCount);
}

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  a  va2  s.c  om*/
 */

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./*from   www . ja v  a 2 s . co m*/
 */
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.cloudfoundry.ide.eclipse.server.standalone.internal.application.JavaPackageFragmentRootHandler.java

License:Open Source License

public IPackageFragmentRoot[] getPackageFragmentRoots(IProgressMonitor monitor) throws CoreException {
    IType type = getMainType(monitor);/*from w w w  . ja  v a2 s  . co  m*/

    IPath[] classpathEntries = null;
    ILaunchConfiguration configuration = null;
    try {
        configuration = createConfiguration(type);
        classpathEntries = getRuntimeClasspaths(configuration);
    } finally {
        if (configuration != null) {
            configuration.delete();
        }
    }

    List<IPackageFragmentRoot> pckRoots = new ArrayList<IPackageFragmentRoot>();

    // Since the java project may have other required projects, fetch the
    // ordered
    // list of required projects that will be used to search for package
    // fragment roots
    // corresponding to the resolved class paths. The order of the java
    // projects to search in should
    // start with the most immediate list of required projects of the java
    // project.
    List<IJavaProject> javaProjectsToSearch = getOrderedJavaProjects(javaProject);

    // Find package fragment roots corresponding to the path entries.
    // Search through all java projects, not just the immediate java project
    // for the application that is being pushed to CF.
    for (IPath path : classpathEntries) {

        for (IJavaProject javaProject : javaProjectsToSearch) {

            try {
                IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();

                if (roots != null) {
                    List<IPackageFragmentRoot> foundRoots = new ArrayList<IPackageFragmentRoot>();

                    for (IPackageFragmentRoot packageFragmentRoot : roots) {
                        // Note that a class path entry may correspond to a
                        // Java project's target directory.
                        // Different fragment roots may use the same target
                        // directory, so relationship between fragment roots
                        // to a class path entry may be many-to-one.

                        if (isRootAtEntry(packageFragmentRoot, path)) {
                            foundRoots.add(packageFragmentRoot);
                        }
                    }

                    // Stop after the first successful search
                    if (!foundRoots.isEmpty()) {
                        pckRoots.addAll(foundRoots);
                        break;
                    }
                }

            } catch (Exception e) {
                throw CloudErrorUtil.toCoreException(e);
            }
        }

    }

    return pckRoots.toArray(new IPackageFragmentRoot[pckRoots.size()]);

}

From source file:org.codehaus.groovy.eclipse.refactoring.test.RefactoringTest.java

License:Open Source License

public static IPackageFragmentRoot getSourceFolder(IJavaProject javaProject, String name)
        throws JavaModelException {
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        if (!roots[i].isArchive() && roots[i].getElementName().equals(name))
            return roots[i];
    }/*from   w w  w.  j av a2 s .c om*/
    return null;
}

From source file:org.dyno.visual.swing.base.ResourceIcon.java

License:Open Source License

public ResourceIcon(String p) {
    this.path = p;
    IJavaProject prj = VisualSwingPlugin.getCurrentProject();
    IProject project = prj.getProject();
    IResource resource = project.findMember(new Path(p));
    if (resource == null) {
        IPackageFragmentRoot[] roots;//  w  w  w .  ja  va2  s.c  o m
        try {
            roots = prj.getPackageFragmentRoots();
            for (IPackageFragmentRoot root : roots) {
                if (!root.isArchive()) {
                    String src = root.getElementName();
                    src = "/" + src + p;
                    resource = project.findMember(new Path(src));
                    if (resource != null) {
                        String ext = resource.getFileExtension();
                        if (ext.equals("gif") || ext.equals("png") || ext.equals("jpg")) {
                            IPath fullPath = project.getWorkspace().getRoot().getRawLocation()
                                    .append(resource.getFullPath());
                            String fullpath = fullPath.toString();
                            Image image = Toolkit.getDefaultToolkit().getImage(fullpath);
                            icon = new ImageIcon(image);
                        } else {
                            break;
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
            VisualSwingPlugin.getLogger().error(e);
        }
    }
}

From source file:org.dyno.visual.swing.base.ResourceImage.java

License:Open Source License

public ResourceImage(String p) {
    this.path = p;
    IJavaProject prj = VisualSwingPlugin.getCurrentProject();
    IProject project = prj.getProject();
    IResource resource = project.findMember(new Path(p));
    if (resource == null) {
        IPackageFragmentRoot[] roots;//w w  w.  j a  v  a  2 s  .c o m
        try {
            roots = prj.getPackageFragmentRoots();
            for (IPackageFragmentRoot root : roots) {
                if (!root.isArchive()) {
                    String src = root.getElementName();
                    src = "/" + src + p; //$NON-NLS-1$
                    resource = project.findMember(new Path(src));
                    if (resource != null) {
                        String ext = resource.getFileExtension();
                        if (ext.equals("gif") || ext.equals("png") || ext.equals("jpg")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            IPath fullPath = project.getWorkspace().getRoot().getRawLocation()
                                    .append(resource.getFullPath());
                            String fullpath = fullPath.toString();
                            image = Toolkit.getDefaultToolkit().getImage(fullpath);
                        } else {
                            break;
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
            VisualSwingPlugin.getLogger().error(e);
        }
    }
    if (image == null)
        throw new IllegalArgumentException(Messages.RESOURCE_IMAGE_CANNOT_FIND_IMG_PATH + p);
}

From source file:org.dyno.visual.swing.types.ImageIconValidator.java

License:Open Source License

public String isValid(Object value) {
    if (value == null || value.equals("")) //$NON-NLS-1$
        return null;
    StringTokenizer tokenizer = new StringTokenizer((String) value, "/"); //$NON-NLS-1$
    if (!tokenizer.hasMoreTokens()) {
        return Messages.ImageIconValidator_Incorrect_Icon_Image_Format;
    }//from   www.  j  a  v a 2s  . c  om
    do {
        String token = tokenizer.nextToken().trim();
        if (token.length() == 0)
            return Messages.ImageIconValidator_Incorrect_Icon_Image_Format;
        if (tokenizer.hasMoreTokens()) {
            char c = token.charAt(0);
            if (!Character.isJavaIdentifierStart(c)) {
                return Messages.ImageIconValidator_Incorrect_Icon_Image_Format_Segment_Id;
            }
            int i = 0;
            while (true) {
                c = token.charAt(i++);
                if (!Character.isJavaIdentifierPart(c) && c != '.')
                    return Messages.ImageIconValidator_Incorrect_Icon_Image_Format_Segment_Id;
                if (i >= token.length())
                    break;
            }
        }
    } while (tokenizer.hasMoreTokens());
    IJavaProject prj = VisualSwingPlugin.getCurrentProject();
    IProject project = prj.getProject();
    IResource resource = project.findMember(new Path((String) value));
    if (resource == null) {
        IPackageFragmentRoot[] roots;
        try {
            roots = prj.getPackageFragmentRoots();
            for (IPackageFragmentRoot root : roots) {
                if (!root.isArchive()) {
                    String src = root.getElementName();
                    src = "/" + src + value; //$NON-NLS-1$
                    resource = project.findMember(new Path(src));
                    if (resource != null) {
                        String ext = resource.getFileExtension();
                        if (ext != null && (ext.equalsIgnoreCase("gif") || ext.equalsIgnoreCase("png") //$NON-NLS-1$//$NON-NLS-2$
                                || ext.equalsIgnoreCase("jpg"))) //$NON-NLS-1$
                            return null;
                        else
                            return Messages.ImageIconValidator_Not_Image_File + value;
                    }
                }
            }
        } catch (JavaModelException e) {
            VisualSwingPlugin.getLogger().error(e);
            return e.getLocalizedMessage();
        }
        return Messages.ImageIconValidator_Cannot_Find_Such_Image_File + value + "!"; //$NON-NLS-2$
    }
    return null;
}

From source file:org.eclim.plugin.jdt.command.src.NewCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    String projectName = commandLine.getValue(Options.PROJECT_OPTION);
    String type = commandLine.getValue(Options.TYPE_OPTION);
    String name = commandLine.getValue(Options.NAME_OPTION);
    String srcRoot = commandLine.getValue(Options.ROOT_OPTION);

    // handle someone typing a file path instead of a fully qualified class name
    if (name.endsWith(".java")) {
        name = name.substring(0, name.length() - 5);
    }/*from   ww  w.  ja va 2  s  .com*/
    name = name.replace('/', '.');

    int classStart = name.lastIndexOf('.');
    final String packageName = classStart >= 0 ? name.substring(0, classStart) : name;
    final String typeName = classStart >= 0 ? name.substring(classStart + 1) : name;
    final String fileName = typeName + ".java";

    IJavaProject javaProject = JavaUtils.getJavaProject(projectName);

    ArrayList<IPackageFragmentRoot> roots = new ArrayList<IPackageFragmentRoot>();

    // find all roots the requested package is found in.
    for (IPackageFragment f : javaProject.getPackageFragments()) {
        if (f.getElementName().equals(packageName)) {
            IJavaElement parent = f.getParent();
            while (parent != null) {
                if (parent instanceof IPackageFragmentRoot) {
                    IPackageFragmentRoot root = (IPackageFragmentRoot) parent;
                    if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                        roots.add(root);
                    }
                    break;
                }
                parent = parent.getParent();
            }
        }
    }

    // the package isn't found in any roots
    if (roots.size() == 0) {
        // no root supplied, so we have to add all src roots to a list for the
        // user to choose from.
        for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
            if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                roots.add(root);
            }
        }
    }

    // still no source roots, so we have to fail
    if (roots.size() == 0) {
        throw new RuntimeException("No project source directories found.");
    }

    if (roots.size() > 1) {
        // user chosen root supplied, so grab that one.
        if (srcRoot != null) {
            roots.clear();
            for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
                if (root.getKind() == IPackageFragmentRoot.K_SOURCE && getPath(root).equals(srcRoot)) {
                    roots.add(root);
                    break;
                }
            }

            if (roots.size() == 0) {
                throw new RuntimeException("Unable to find project source directory: " + srcRoot);
            }
        }

        if (roots.size() > 1) {
            ArrayList<String> srcRoots = new ArrayList<String>();
            for (IPackageFragmentRoot root : roots) {
                srcRoots.add(getPath(root));
            }
            return srcRoots;
        }
    }

    IPackageFragmentRoot root = roots.get(0);
    IPackageFragment fragment = root.createPackageFragment(packageName, false, null);

    // locate the to-be created file
    File fragmentPath = fragment.getUnderlyingResource().getLocation().toFile();
    final File file = new File(fragmentPath, fileName);

    // make sure eclipse is up to date, in case the user
    //  deleted the file outside of eclipse's knowledge
    fragment.getUnderlyingResource().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());

    // create!
    final String content = String.format(TEMPLATE, packageName, getType(type), typeName);

    // NB: If we delete the file outside of Eclipse'
    //  awareness, it will whine if we then try to
    //  recreate it. So, if we *know* the file doesn't
    //  exist, force it.
    ICompilationUnit unit = fragment.createCompilationUnit(fileName, content, false, new NullProgressMonitor());

    if (unit == null || !file.exists()) {
        throw new RuntimeException("Could not create " + file);
    }

    JavaUtils.format(unit, CodeFormatter.K_COMPILATION_UNIT, 0, unit.getBuffer().getLength());

    return file.getAbsolutePath();
}