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

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

Introduction

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

Prototype

IPackageFragmentRoot getPackageFragmentRoot(IResource resource);

Source Link

Document

Returns a package fragment root for the given resource, which must either be a folder representing the top of a package hierarchy, or a ZIP archive (e.g.

Usage

From source file:org.drools.eclipse.wizard.project.NewDroolsProjectWizard.java

License:Apache License

private void addSourceFolder(IJavaProject project, List list, String s, IProgressMonitor monitor)
        throws CoreException {
    IFolder folder = project.getProject().getFolder(s);
    createFolder(folder, monitor);//from   ww w.  j  a  v  a 2  s  . c o m
    IPackageFragmentRoot ipackagefragmentroot = project.getPackageFragmentRoot(folder);
    list.add(JavaCore.newSourceEntry(ipackagefragmentroot.getPath()));
}

From source file:org.ecipse.che.plugin.testing.testng.server.TestSetUpUtil.java

License:Open Source License

/**
 * Adds a source container to a IJavaProject.
 *
 * @param jproject The parent project/*from ww w  .j  av a 2  s  .co m*/
 * @param containerName The name of the new source container
 * @param inclusionFilters Inclusion filters to set
 * @param exclusionFilters Exclusion filters to set
 * @param outputLocation The location where class files are written to, <b>null</b> for project
 *     output folder
 * @return The handle to the new source container
 * @throws CoreException Creation failed
 */
public static IPackageFragmentRoot addSourceContainer(IJavaProject jproject, String containerName,
        String outputLocation) 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()) {
            CoreUtility.createFolder(folder, false, true, null);
        }
        container = folder;
    }
    IPackageFragmentRoot root = jproject.getPackageFragmentRoot(container);

    IPath outputPath = null;
    if (outputLocation != null) {
        IFolder folder = project.getFolder(outputLocation);
        if (!folder.exists()) {
            CoreUtility.createFolder(folder, false, true, null);
        }
        outputPath = folder.getFullPath();
    }
    return root;
}

From source file:org.eclipse.acceleo.internal.ide.ui.wizards.project.AcceleoProjectWizard.java

License:Open Source License

/**
 * Convert the empty project to an Acceleo project.
 * //w  ww . ja  v  a 2  s.  co m
 * @param project
 *            The newly created project.
 * @param selectedJVM
 *            The name of the selected JVM (J2SE-1.5 or JavaSE-1.6 recommended).
 * @param allModules
 *            The description of the module that need to be created.
 * @param shouldGenerateModules
 *            Indicates if we should generate the modules in the project or not. The wizard container to
 *            display the progress monitor
 * @param monitor
 *            The monitor.
 */
public static void convert(IProject project, String selectedJVM, List<AcceleoModule> allModules,
        boolean shouldGenerateModules, IProgressMonitor monitor) {
    String generatorName = computeGeneratorName(project.getName());
    AcceleoProject acceleoProject = AcceleowizardmodelFactory.eINSTANCE.createAcceleoProject();
    acceleoProject.setName(project.getName());
    acceleoProject.setGeneratorName(generatorName);

    // Default JRE value
    acceleoProject.setJre(selectedJVM);
    if (acceleoProject.getJre() == null || acceleoProject.getJre().length() == 0) {
        acceleoProject.setJre("J2SE-1.5"); //$NON-NLS-1$         
    }

    if (shouldGenerateModules) {
        for (AcceleoModule acceleoModule : allModules) {
            String parentFolder = acceleoModule.getParentFolder();
            IProject moduleProject = ResourcesPlugin.getWorkspace().getRoot()
                    .getProject(acceleoModule.getProjectName());
            if (moduleProject.exists() && moduleProject.isAccessible()
                    && acceleoModule.getModuleElement() != null
                    && acceleoModule.getModuleElement().isIsMain()) {
                IPath parentFolderPath = new Path(parentFolder);
                IFolder folder = moduleProject.getFolder(parentFolderPath.removeFirstSegments(1));
                acceleoProject.getExportedPackages()
                        .add(folder.getProjectRelativePath().removeFirstSegments(1).toString().replaceAll("/", //$NON-NLS-1$
                                "\\.")); //$NON-NLS-1$
            }
            // Calculate project dependencies
            List<String> metamodelURIs = acceleoModule.getMetamodelURIs();
            for (String metamodelURI : metamodelURIs) {
                // Find the project containing this metamodel and add a dependency to it.
                EPackage ePackage = AcceleoPackageRegistry.INSTANCE.getEPackage(metamodelURI);
                if (ePackage != null && !(ePackage instanceof EcorePackage)) {
                    Bundle bundle = AcceleoWorkspaceUtil.getBundle(ePackage.getClass());
                    acceleoProject.getPluginDependencies().add(bundle.getSymbolicName());
                }
            }
        }
    }

    try {
        IProjectDescription description = project.getDescription();
        description.setNatureIds(new String[] { JavaCore.NATURE_ID, IBundleProjectDescription.PLUGIN_NATURE,
                IAcceleoConstants.ACCELEO_NATURE_ID, });
        project.setDescription(description, monitor);

        IJavaProject iJavaProject = JavaCore.create(project);

        // Compute the JRE
        List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
        IExecutionEnvironmentsManager executionEnvironmentsManager = JavaRuntime
                .getExecutionEnvironmentsManager();
        IExecutionEnvironment[] executionEnvironments = executionEnvironmentsManager.getExecutionEnvironments();
        for (IExecutionEnvironment iExecutionEnvironment : executionEnvironments) {
            if (acceleoProject.getJre().equals(iExecutionEnvironment.getId())) {
                entries.add(JavaCore.newContainerEntry(JavaRuntime.newJREContainerPath(iExecutionEnvironment)));
                break;
            }
        }

        // PDE Entry (will not be generated anymore)
        entries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"))); //$NON-NLS-1$

        // Sets the input / output folders
        IFolder target = project.getFolder("src"); //$NON-NLS-1$
        if (!target.exists()) {
            target.create(true, true, monitor);
        }

        IFolder classes = project.getFolder("bin"); //$NON-NLS-1$
        if (!classes.exists()) {
            classes.create(true, true, monitor);
        }

        iJavaProject.setOutputLocation(classes.getFullPath(), monitor);
        IPackageFragmentRoot packageRoot = iJavaProject.getPackageFragmentRoot(target);
        entries.add(JavaCore.newSourceEntry(packageRoot.getPath(), new Path[] {}, new Path[] {},
                classes.getFullPath()));

        iJavaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
        iJavaProject.open(monitor);

        AcceleoProjectUtils.generateFiles(acceleoProject, allModules, project, shouldGenerateModules, monitor);

        // Default settings
        AcceleoBuilderSettings settings = new AcceleoBuilderSettings(project);
        settings.setCompilationKind(AcceleoBuilderSettings.COMPILATION_PLATFORM_RESOURCE);
        settings.setResourceKind(AcceleoBuilderSettings.BUILD_XMI_RESOURCE);
        settings.save();
    } catch (CoreException e) {
        AcceleoUIActivator.log(e, true);
    }
}

From source file:org.eclipse.ajdt.core.javaelements.CompilationUnitTools.java

License:Open Source License

public static PackageFragment getParentPackage(IFile ajFile) {
    IJavaProject jp = JavaCore.create(ajFile.getProject());
    IJavaElement elem = JavaModelManager.determineIfOnClasspath(ajFile, jp);
    if (elem == null) {
        //not on classpath -> default package
        IPackageFragmentRoot root = jp.getPackageFragmentRoot(ajFile.getParent());
        elem = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
    }/*w  w  w. j a  v a  2 s . co  m*/
    if (elem instanceof PackageFragment) {
        return (PackageFragment) elem;
    }
    //should never happen

    return null;
}

From source file:org.eclipse.ajdt.core.tests.AJDTCoreTestCase.java

License:Open Source License

private IPackageFragmentRoot createDefaultSourceFolder(IJavaProject javaProject) throws CoreException {
    IProject project = javaProject.getProject();
    IFolder folder = project.getFolder("src");
    if (!folder.exists())
        ensureExists(folder);//from w ww .j  a  v  a 2  s  . com

    // if already exists, do nothing
    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;
        }
    }

    // else, remove old source folders and add this new one
    IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
    List<IClasspathEntry> oldEntriesList = new ArrayList<IClasspathEntry>();
    oldEntriesList.add(JavaCore.newSourceEntry(root.getPath()));
    for (IClasspathEntry entry : oldEntries) {
        if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
            oldEntriesList.add(entry);
        }
    }

    IClasspathEntry[] newEntries = oldEntriesList.toArray(new IClasspathEntry[0]);
    javaProject.setRawClasspath(newEntries, null);
    return root;
}

From source file:org.eclipse.ajdt.internal.core.ClasspathModifier.java

License:Open Source License

/**
 * Get the source folder of a given <code>IResource</code> element,
 * starting with the resource's parent.//from   ww  w .j a va2 s  . com
 * 
 * @param resource
 *            the resource to get the fragment root from
 * @param project
 *            the Java project
 * @param monitor
 *            progress monitor, can be <code>null</code>
 * @return resolved fragment root
 * @throws JavaModelException
 */
public static IPackageFragmentRoot getFragmentRoot(IResource resource, IJavaProject project,
        IProgressMonitor monitor) throws JavaModelException {
    IJavaElement javaElem = null;
    if (resource.getFullPath().equals(project.getPath()))
        return project.getPackageFragmentRoot(resource);
    IContainer container = resource.getParent();
    do {
        if (container instanceof IFolder)
            javaElem = JavaCore.create((IFolder) container);
        if (container.getFullPath().equals(project.getPath())) {
            javaElem = project;
            break;
        }
        container = container.getParent();
        if (container == null)
            return null;
    } while (javaElem == null || !(javaElem instanceof IPackageFragmentRoot));
    if (javaElem instanceof IJavaProject)
        javaElem = project.getPackageFragmentRoot(project.getResource());
    return (IPackageFragmentRoot) javaElem;
}

From source file:org.eclipse.ajdt.ui.tests.builder.BuilderTest.java

License:Open Source License

/**
 * Test for bug 78579 - when you create a package, this should be copied
 * over to the bin dir. Similarly, when you delete the package, the bin
 * dir should be updated.//w w  w . j a  v  a 2s  .com
 * 
 * @throws Exception
 */
public void testCreateAndDeleteNewPackage() throws Exception {
    IProject simpleProject = createPredefinedProject("AnotherSimpleAJProject"); //$NON-NLS-1$

    IJavaProject javaProject = JavaCore.create(simpleProject);
    waitForJobsToComplete();

    String srcPath = javaProject.getUnderlyingResource().getLocation().toOSString() + File.separator + "src" //$NON-NLS-1$
            + File.separator + "newPackage"; //$NON-NLS-1$

    String binPath = javaProject.getUnderlyingResource().getLocation().toOSString() + File.separator + "bin" //$NON-NLS-1$
            + File.separator + "newPackage"; //$NON-NLS-1$

    IFolder src = simpleProject.getFolder("src"); //$NON-NLS-1$
    if (!src.exists()) {
        src.create(true, true, null);
    }
    waitForJobsToComplete();

    IFolder newPackage = src.getFolder("newPackage"); //$NON-NLS-1$
    assertFalse("newPackage should not exist under src tree! (path=" + srcPath + ")", newPackage.exists()); //$NON-NLS-1$ //$NON-NLS-2$

    IFolder bin = simpleProject.getFolder("bin"); //$NON-NLS-1$
    if (!bin.exists()) {
        bin.create(true, true, null);
    }
    waitForJobsToComplete();
    IFolder newBinPackage = bin.getFolder("newPackage"); //$NON-NLS-1$
    assertFalse("newPackage should not exist under bin tree! (path=" + binPath + ")", newBinPackage.exists()); //$NON-NLS-1$ //$NON-NLS-2$

    waitForJobsToComplete();

    String str = "AnotherSimpleAJProject" + File.separator + "src"; //$NON-NLS-1$ //$NON-NLS-2$
    IPath path = new Path(str);
    IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
    IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(res);
    root.createPackageFragment("newPackage", true, null); //$NON-NLS-1$

    simpleProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    waitForJobsToComplete();

    // If either of these fail, then it's more likely than not to be
    // down to the timings of driving this programatically (this is
    // why there is a sleep above.
    IFolder newPackage2 = src.getFolder("newPackage"); //$NON-NLS-1$
    assertTrue("newPackage should exist under src tree! (path=" + srcPath + ")", newPackage2.exists()); //$NON-NLS-1$ //$NON-NLS-2$
    waitForJobsToComplete();
    simpleProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    waitForJobsToComplete();
    IFolder newBinPackage2 = bin.getFolder("newPackage"); //$NON-NLS-1$
    assertTrue("newPackage should exist under bin tree! (path=" + binPath + ")", newBinPackage2.exists()); //$NON-NLS-1$ //$NON-NLS-2$
    waitForJobsToComplete();

    newPackage.delete(true, null);
    waitForJobsToComplete();

    // If either of these fail, then it's more likely than not to be
    // down to the timings of driving this programatically (this is
    // why there is a sleep above.
    IFolder newPackage3 = src.getFolder("newPackage"); //$NON-NLS-1$
    assertFalse("newPackage should not exist under src tree! (path=" + srcPath + ")", newPackage3.exists()); //$NON-NLS-1$ //$NON-NLS-2$
    waitForJobsToComplete();
    simpleProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    waitForJobsToComplete();
    IFolder newBinPackage3 = bin.getFolder("newPackage"); //$NON-NLS-1$
    assertFalse("newPackage should not exist under bin tree! (path=" + binPath + ")", newBinPackage3.exists()); //$NON-NLS-1$ //$NON-NLS-2$

    waitForJobsToComplete();
}

From source file:org.eclipse.ajdt.ui.tests.refactoring.CopyPasteAJTest.java

License:Open Source License

public void testCopyPasteAJ() throws Exception {
    IProject proj = createPredefinedProject("Bug 254431"); //$NON-NLS-1$
    IFile file = proj.getFile("src/ajdt/renamepackagebug1/A.aj"); //$NON-NLS-1$
    IJavaProject jProj = JavaCore.create(proj);
    IJavaElement elt = AspectJCore.create(file);
    Clipboard clipboard = new Clipboard(Display.getDefault());
    clipboard.setContents(new Object[] { new IJavaElement[] { elt } },
            new Transfer[] { JavaElementTransfer.getInstance() });

    PasteAction paste = new PasteAction(EditorUtility.openInEditor(elt).getEditorSite(), clipboard);

    // can't paste to the same location because a dialog appears and there is no way to OK it
    // instead paste to "ajdt" package
    paste.run(new StructuredSelection(
            jProj.getPackageFragmentRoot(proj.getFolder("src")).getPackageFragment("ajdt"))); //$NON-NLS-1$ //$NON-NLS-2$

    IFile newFile = proj.getFile("src/ajdt/A.aj"); //$NON-NLS-1$
    assertTrue("Paste operation should have created a new AJ compilation unit", newFile.exists()); //$NON-NLS-1$
    AJCompilationUnit newUnit = (AJCompilationUnit) AspectJCore.create(newFile);
    IPackageDeclaration[] packDecls = newUnit.getPackageDeclarations();
    assertEquals("New compilation unit should have only one package declaration", 1, packDecls.length); //$NON-NLS-1$
    assertEquals("wrong name for package declaration", "ajdt", packDecls[0].getElementName()); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:org.eclipse.ajdt.ui.tests.refactoring.RenamePackageTest.java

License:Open Source License

public void testRenamePackage() throws Exception {
    IProject proj = createPredefinedProject("Bug 254431"); //$NON-NLS-1$
    IJavaProject jProj = JavaCore.create(proj);
    IPackageFragmentRoot packRoot = jProj.getPackageFragmentRoot(proj.getFolder("src")); //$NON-NLS-1$
    IPackageFragment frag = packRoot.getPackageFragment("ajdt.renamepackagebug1"); //$NON-NLS-1$
    assertTrue("Package fragment " + frag.getElementName() + " should exist", frag.exists()); //$NON-NLS-1$ //$NON-NLS-2$
    RenamePackageProcessor processor = new RenamePackageProcessor(frag);
    processor.setNewElementName("ajdt.renamed"); //$NON-NLS-1$
    IProgressMonitor pm = new NullProgressMonitor();
    CheckConditionsContext context = new CheckConditionsContext();
    context.add(new ValidateEditChecker(context));
    context.add(new ResourceChangeChecker());
    processor.checkInitialConditions(pm);
    processor.checkFinalConditions(pm, context);
    Change change = processor.createChange(pm);
    change.perform(pm);//from   www  .  ja v a  2s. co m

    waitForJobsToComplete();
    IPackageFragment newFrag = packRoot.getPackageFragment("ajdt.renamed"); //$NON-NLS-1$
    assertTrue("Package fragment " + newFrag.getElementName() + " should exist after a rename", //$NON-NLS-1$//$NON-NLS-2$
            newFrag.exists());

    IFile ajFile = proj.getFile("src/ajdt/renamed/A.aj"); //$NON-NLS-1$
    assertTrue("A.aj should exist after its package has been renamed", ajFile.exists()); //$NON-NLS-1$
    IMarker[] markers = ajFile.findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE);
    if (markers.length > 0) {
        StringBuffer sb = new StringBuffer();
        sb.append("No markers should have been found, but the following markers were found on A.aj:\n"); //$NON-NLS-1$
        for (int i = 0; i < markers.length; i++) {
            sb.append("\t" + markers[i].getAttribute(IMarker.MESSAGE) + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        assertEquals(sb.toString(), 0, markers.length);
    }

    IFile javaFile = proj.getFile("src/ajdt/renamepackagebug2/B.aj"); //$NON-NLS-1$
    assertTrue("B.aj should exist", javaFile.exists()); //$NON-NLS-1$
    markers = javaFile.findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE);
    if (markers.length > 0) {
        StringBuffer sb = new StringBuffer();
        sb.append("No markers should have been found, but the following markers were found on B.aj:\n"); //$NON-NLS-1$
        for (int i = 0; i < markers.length; i++) {
            sb.append("\t" + markers[i].getAttribute(IMarker.MESSAGE) + "\n"); //$NON-NLS-1$//$NON-NLS-2$
        }
        assertEquals(sb.toString(), 0, markers.length);
    }
}

From source file:org.eclipse.ant.internal.ui.datatransfer.ProjectCreator.java

License:Open Source License

/**
 * Adds a source container to a IJavaProject.
 *//*from   w w  w .j  a va  2s.  co m*/
private void addSourceContainer(IJavaProject jproject, String srcName, String srcPath, String outputName,
        String outputPath, IProgressMonitor monitor) throws CoreException {
    IProject project = jproject.getProject();
    IContainer container = null;
    if (srcName == null || srcName.length() == 0) {
        container = project;
    } else {
        IFolder folder = project.getFolder(srcName);
        if (!folder.exists()) {
            folder.createLink(new Path(srcPath), IResource.ALLOW_MISSING_LOCAL, monitor);
        }
        container = folder;
    }
    IPackageFragmentRoot root = jproject.getPackageFragmentRoot(container);

    IPath output = null;
    if (outputName != null) {
        IFolder outputFolder = project.getFolder(outputName);
        if (!outputFolder.exists()) {
            outputFolder.createLink(new Path(outputPath), IResource.ALLOW_MISSING_LOCAL, monitor);
        }
        output = outputFolder.getFullPath();
    }

    IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath(), new IPath[0], output);

    addToClasspath(jproject, cpe, monitor);
}