Example usage for org.eclipse.jdt.core IPackageFragmentRoot createPackageFragment

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot createPackageFragment

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot createPackageFragment.

Prototype

IPackageFragment createPackageFragment(String name, boolean force, IProgressMonitor monitor)
        throws JavaModelException;

Source Link

Document

Creates and returns a package fragment in this root with the given dot-separated package name.

Usage

From source file:fede.workspace.eclipse.java.JavaProjectManager.java

License:Apache License

/**
 * Creates a new package in the source folder corresponding to an item.
 * //from ww w  .j a  v a 2 s . c o m
 * @param item
 *            the item
 * @param packageName
 *            the package name
 * @param monitor
 *            the monitor
 * 
 * @return the i package fragment
 * 
 * @throws CoreException
 *             the core exception
 */
public static IPackageFragment createPackage(Item item, String packageName, IProgressMonitor monitor)
        throws CoreException {

    IResource resource = getResource(item);
    IJavaElement element = JavaCore.create(resource);

    /*
     * The resource associated with the item is already a package
     */
    if (element instanceof IPackageFragment) {
        if (packageName == null || element.getElementName().equals(packageName)) {
            return (IPackageFragment) element;
        }
    }

    if (packageName == null) {
        throw new CoreException(new Status(Status.ERROR, WSJavaPlugin.PLUGIN_ID, 0,
                "Package name is null in createPackage !!!.", null));
    }

    /*
     * The resource is a source folder
     */
    if (element instanceof IPackageFragmentRoot) {
        IPackageFragmentRoot root = (IPackageFragmentRoot) element;
        return root.createPackageFragment(packageName, true, monitor);
    }

    /*
     * The resource is a project or a non source folder, get the associated
     * source folder
     */
    IPackageFragmentRoot sources = getPackageFragmentRoot(item);
    if (sources == null) {
        throw new CoreException(
                new Status(Status.ERROR, WSJavaPlugin.PLUGIN_ID, 0, "Cannot find the sources folder.", null));
    }

    IProject project = getProject(item);
    if (!project.exists()) {
        project.create(monitor);
    }

    if (!sources.exists()) {
        getDefaultSourceFolder(item).create(true, true, monitor);
    }

    return sources.createPackageFragment(packageName, false, monitor);
}

From source file:fede.workspace.eclipse.java.manager.JavaPackageFolderContentManager.java

License:Apache License

/**
 * Creates the package fragment.//from  w  w w  .ja  v a  2 s .c  o m
 * 
 * @param cxt
 *            the cxt
 * @param name
 *            the name
 * @param force
 *            the force
 * @param monitor
 *            the monitor
 * 
 * @return the i package fragment
 * 
 * @throws JavaModelException
 *             the java model exception
 */
public IPackageFragment createPackageFragment(ContextVariable cxt, String name, boolean force,
        IProgressMonitor monitor) throws JavaModelException {
    IPackageFragment pf = getPackageFragment(cxt);
    if (!pf.isDefaultPackage()) {
        name = getPackageName(cxt) + "." + name;
    }
    IPackageFragmentRoot pfr = getJavaSourceElement(cxt);
    return pfr.createPackageFragment(name, force, monitor);
}

From source file:fede.workspace.eclipse.java.manager.JavaProjectContentManager.java

License:Apache License

/**
 * Creates the package./*w ww .  ja va  2  s .c  o m*/
 * 
 * @param cxt
 *            the cxt
 * @param packageName
 *            the package name
 * 
 * @return the i package fragment
 */
public IPackageFragment createPackage(ContextVariable cxt, String packageName) {
    IPackageFragmentRoot source = getJavaSourceElement(cxt);
    if (source != null) {
        IProgressMonitor monitor = EclipseTool.getDefaultMonitor();
        try {
            return source.createPackageFragment(packageName, true, monitor);
        } catch (JavaModelException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:fede.workspace.eclipse.java.manager.JavaProjectContentManager.java

License:Apache License

/**
 * Creates the package fragment./*w ww .j  a  va  2s  .co  m*/
 * 
 * @param cxt
 *            the cxt
 * @param name
 *            the name
 * @param force
 *            the force
 * @param monitor
 *            the monitor
 * 
 * @return the i package fragment
 * 
 * @throws JavaModelException
 *             the java model exception
 */
public IPackageFragment createPackageFragment(ContextVariable cxt, String name, boolean force,
        IProgressMonitor monitor) throws JavaModelException {
    IPackageFragmentRoot pfr = getJavaSourceElement(cxt);
    if (pfr != null) {
        return pfr.createPackageFragment(name, force, monitor);
    }
    throw new IllegalArgumentException("Cannot create a package " + name + " in item " + getOwnerItem());
}

From source file:fede.workspace.eclipse.java.manager.JavaSourceFolderContentManager.java

License:Apache License

/**
 * Creates the package fragment./* ww w  .  jav a 2  s. c  o m*/
 * 
 * @param name
 *            the name
 * @param force
 *            the force
 * @param monitor
 *            the monitor
 * 
 * @return the i package fragment
 * 
 * @throws JavaModelException
 *             the java model exception
 */
public IPackageFragment createPackageFragment(String name, boolean force, IProgressMonitor monitor)
        throws JavaModelException {
    IPackageFragmentRoot pfr = getJavaSourceElement();
    return pfr.createPackageFragment(name, force, monitor);
}

From source file:fede.workspace.eclipse.java.manager.JavaSourceFolderContentManager.java

License:Apache License

/**
 * Creates the package fragment./* ww w  .ja va 2s  .  c o m*/
 * 
 * @param name
 *            the name
 * @param force
 *            the force
 * @param monitor
 *            the monitor
 * 
 * @return the i package fragment
 * 
 * @throws JavaModelException
 *             the java model exception
 */
public IPackageFragment createPackageFragment(ContextVariable cxt, String name, boolean force,
        IProgressMonitor monitor) throws JavaModelException {
    IPackageFragmentRoot pfr = getJavaSourceElement(cxt);
    return pfr.createPackageFragment(name, force, monitor);
}

From source file:fr.imag.adele.cadse.cadseg.operation.MigrateCodePagesAction.java

License:Apache License

/**
 * Finish1./*from w  w  w  . j  a  va2s.co m*/
 * 
 * @param pmo
 *            the pmo
 * 
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws JAXBException
 *             the JAXB exception
 * @throws CoreException
 *             the core exception
 */
private void finish1(IProgressMonitor pmo) throws IOException, JAXBException, CoreException {
    CadseCore.getCadseDomain().beginOperation("Import binary cadse");
    List<IJavaElement> destinations = new ArrayList<IJavaElement>();
    List<IJavaElement> elements = new ArrayList<IJavaElement>();
    List<String> names = new ArrayList<String>();
    try {
        pmo.beginTask("migrate code from " + oldCadse.getName() + " to " + newCadse.getName(),
                oldCadse.getItemType().size() * 2 + 1);

        its_old = new HashMap<String, CItemType>();
        its_new = new HashMap<String, CItemType>();
        IFolder oldsources = oldProject.getFolder("sources");
        IFolder newsources = newProject.getFolder("sources");
        IJavaProject oldjp = JavaCore.create(oldProject);
        IJavaProject newjp = JavaCore.create(newProject);

        IPackageFragmentRoot joldsources = oldjp.getPackageFragmentRoot(oldsources);
        IPackageFragmentRoot jnewsources = newjp.getPackageFragmentRoot(newsources);

        for (CItemType cit : oldCadse.getItemType()) {
            its_old.put(cit.getId(), cit);
        }
        for (CItemType cit : newCadse.getItemType()) {
            its_new.put(cit.getId(), cit);
        }
        pmo.worked(1);

        for (CItemType cit : oldCadse.getItemType()) {
            pmo.worked(1);

            String qclazz = cit.getManagerClass();
            if (qclazz == null)
                continue;

            String oldpn = getPackage(qclazz);
            String oldcn = getClassName(qclazz);

            CItemType newcit = its_new.get(cit.getId());
            if (newcit == null) {
                System.out.println("Cannot migrate " + qclazz);
                continue;
            }
            String newqclazz = newcit.getManagerClass();
            if (newqclazz == null) {
                System.out.println("Cannot migrate " + qclazz);
                continue;
            }
            String newpn = getPackage(newqclazz);
            String newcn = getClassName(newqclazz);
            IFile fo = oldsources.getFile(new Path(oldpn.replace('.', '/')).append(oldcn + ".java"));
            IFile fn = newsources.getFile(new Path(newpn.replace('.', '/')).append(newcn + ".java"));
            if (!fo.exists() || !fn.exists()) {
                System.out.println("Cannot migrate " + qclazz);
                continue;
            }

            ICompilationUnit oldcu = JavaCore.createCompilationUnitFrom(fo);
            ICompilationUnit newcu = JavaCore.createCompilationUnitFrom(fn);
            if (oldcu == null || newcu == null || !oldcu.exists() || !newcu.exists()) {
                System.out.println("Cannot migrate " + qclazz);
                continue;
            }

            IJavaElement findelement = oldcu;
            IJavaElement newdestination = joldsources.createPackageFragment(oldpn, true, pmo);
            ;
            String newname = oldcn + ".java";

            if (!oldpn.equals(newpn)) {
                // move
                System.out.println("move " + oldpn + " to " + newpn);
                newdestination = joldsources.createPackageFragment(newpn, true, pmo);
            }
            if (!oldcn.equals(newcn)) {
                System.out.println("rename " + oldcn + " to " + newcn);
                newname = newcn + ".java";
            }
            elements.add(findelement);
            destinations.add(newdestination);
            names.add(newname);

            cit.setManagerClass(oldCadse.getName() + "/" + newpn + "." + newcn);
            System.out.println("change manager to " + cit.getManagerClass());
        }
        IJavaModel jm = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
        jm.rename((IJavaElement[]) elements.toArray(new IJavaElement[elements.size()]),
                (IJavaElement[]) destinations.toArray(new IJavaElement[destinations.size()]),
                (String[]) names.toArray(new String[names.size()]), false, pmo);

        writeCadse(oldProject);
        //         
        // for (CItemType cit : cadse.getItemType()) {
        // Item sourceItemType = its.get(cit.getId());
        // if (sourceItemType == null) continue;
        // for( CLinkType clt : cit.getOutgoingLink()) {
        //               
        // }
        // pmo.worked(1);
        // }

    } catch (JavaModelException e) {
        System.out.println(e.getStatus());
        e.printStackTrace();
    } finally {
        CadseCore.getCadseDomain().endOperation();
    }
}

From source file:hydrograph.ui.expression.editor.sourceviewer.SourceViewer.java

License:Apache License

public SourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
        boolean showAnnotationsOverview, int styles, IAnnotationAccess annotationAccess,
        ISharedTextColors sharedColors, IDocument document) {
    super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, SWT.BOLD);
    int id = currentId++;
    filename = VIEWER_CLASS_NAME + id++ + ".java";
    this.sharedColors = sharedColors;
    this.annotationAccess = annotationAccess;
    this.fOverviewRuler = overviewRuler;
    oldAnnotations = new HashMap<ProjectionAnnotation, Position>();

    IJavaProject javaProject = JavaCore.create(BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject());
    try {//from   www . j a v a 2 s.c o  m
        IPackageFragmentRoot[] ipackageFragmentRootList = javaProject.getPackageFragmentRoots();
        IPackageFragmentRoot ipackageFragmentRoot = null;
        for (IPackageFragmentRoot tempIpackageFragmentRoot : ipackageFragmentRootList) {
            if (tempIpackageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE
                    && StringUtils.equals(PathConstant.TEMP_BUILD_PATH_SETTINGS_FOLDER,
                            tempIpackageFragmentRoot.getPath().removeFirstSegments(1).toString())) {
                ipackageFragmentRoot = tempIpackageFragmentRoot;
                break;
            }
        }

        IPackageFragment compilationUnitPackage = ipackageFragmentRoot
                .createPackageFragment(HYDROGRAPH_COMPILATIONUNIT_PACKAGE, true, new NullProgressMonitor());
        compilatioUnit = compilationUnitPackage.createCompilationUnit(filename, document.get(), true,
                new NullProgressMonitor());
    } catch (Exception exception) {
        LOGGER.warn("Exception occurred while initializing source viewer", exception);
    } finally {
        if (javaProject != null) {
            try {
                javaProject.close();
            } catch (JavaModelException javaModelException) {
                LOGGER.warn("Exception occurred while closing java-project", javaModelException);
            }
        }
    }
    initializeViewer(document);
    updateContents();
}

From source file:icy.icy4eclipse.core.NewIcyProjectWizard.java

License:Open Source License

@Override
public boolean performFinish() {
    String pluginName = myPage.getPluginName();
    String devName = Icy4EclipsePlugin.getIcyDeveloper();
    String subpackageName = myPage.getSubpackageName();

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = root.getProject(pluginName);

    String templateName = myPage.getTemplateName();
    IcyTemplateLocator locator = Icy4EclipsePlugin.getDefault().getTemplateLocator();
    locator.init();/*from  www.j  a  va  2s . co  m*/
    IcyProjectTemplate template = locator.getTemplate(templateName);
    if (template == null) {
        Icy4EclipsePlugin.logError("Unable to find a template (" + templateName + ")");
        return false;
    }

    try {
        // Project creation
        project.create(null);
        if (!project.isOpen()) {
            project.open(null);
        }
    } catch (CoreException e) {
        Icy4EclipsePlugin.logException(e);
        return false;
    }

    try {
        // Natures
        Icy4EclipsePlugin.addNature(project, JavaCore.NATURE_ID);
        IJavaProject javaProject = JavaCore.create(project);
        Icy4EclipsePlugin.addIcyNature(javaProject);

        // Folder
        IFolder src = project.getFolder("src");
        if (!src.exists()) {
            src.create(true, true, null);
        }

        // Classpath
        List<IClasspathEntry> classpath = new ArrayList<IClasspathEntry>();
        classpath.add(JavaCore.newSourceEntry(src.getFullPath()));
        for (String e : ICY_JARS) {
            classpath.add(JavaCore.newVariableEntry(new Path(ICY4ECLIPSE_HOME_VARIABLE + "/" + e), null, null));
        }
        List<IClasspathEntry> templateEntries = template.getSpecificClasspathEntries();
        if (templateEntries != null) {
            classpath.addAll(templateEntries);
        }
        IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();
        for (IClasspathEntry cpe : jreEntries) {
            classpath.add(cpe);
        }
        javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), null);

        // Default plugin java file
        String packageName = Icy4EclipsePlugin.getFullPackageName(devName, subpackageName);
        IPackageFragmentRoot srcRoot = javaProject.getPackageFragmentRoot(src);
        IPackageFragment pack = srcRoot.createPackageFragment(packageName, false, null);

        String className = Icy4EclipsePlugin.fromPluginnameToClassname(pluginName);

        pack.createCompilationUnit(className + ".java",
                template.getPluginMainClassImplementation(pluginName, packageName, className), false, null);

        // Compile
        project.build(IncrementalProjectBuilder.FULL_BUILD, null);

    } catch (CoreException e) {
        Icy4EclipsePlugin.logException(e);
        try {
            project.delete(true, true, null);
        } catch (CoreException e1) {
            Icy4EclipsePlugin.logException(e1);
        }
        return false;
    }

    return true;
}

From source file:metabup.annotations.wizards.NewAnnotationWizard.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.j av  a 2s  .  c  o m*/

private void doFinish(String projectName, String fileName, String annotationName, String description,
        IProgressMonitor monitor) throws CoreException {
    // create a sample file
    monitor.beginTask("Creating " + fileName, 2);
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IResource resource = root.findMember(new Path(projectName));
    if (!resource.exists() || !(resource instanceof IProject))
        throwCoreException("Project \"" + projectName + "\" does not exist.");

    monitor.worked(1);

    IProject project = (IProject) resource;

    /*
     * Turn project into a Java project, if not yet
     */

    IProjectDescription projectDescription = project.getDescription();
    String javaNature[] = { JavaCore.NATURE_ID };
    String projectNatures[] = projectDescription.getNatureIds();

    boolean isJavaEnabled = false;

    for (int i = 0; i < projectNatures.length; i++) {
        if (projectNatures[i].equals(javaNature[0])) {
            isJavaEnabled = true;
            i = projectNatures.length;
        }
    }

    IJavaProject javaProject = JavaCore.create(project);

    if (!isJavaEnabled) {
        IProjectDescription pDescription = project.getDescription();
        pDescription.setNatureIds(new String[] { JavaCore.NATURE_ID });
        project.setDescription(pDescription, monitor);

        IFolder binFolder = project.getFolder("bin");
        if (!binFolder.exists())
            binFolder.create(false, true, monitor);
        javaProject.setOutputLocation(binFolder.getFullPath(), monitor);

    }

    monitor.worked(1);

    //Import Activator library

    Bundle plugin = Activator.getDefault().getBundle();

    IPath relativePagePath = new Path(AnnotationsPluginPreferenceConstants.P_ANNOTATIONS_LIB_FILES);
    URL fileInPlugin = FileLocator.find(plugin, relativePagePath, null);

    if (fileInPlugin != null) {
        // the file exists         
        URL fileUrl;
        try {
            fileUrl = FileLocator.toFileURL(fileInPlugin);

            File file = new File(fileUrl.getPath());

            IClasspathEntry libEntry[] = { JavaCore.newLibraryEntry(new Path(file.getAbsolutePath()), null, // no source
                    null, // no source
                    false) }; // not exported

            monitor.worked(1);

            //set the build path      
            IClasspathEntry[] buildPath = { JavaCore.newSourceEntry(project.getFullPath().append("src")),
                    JavaRuntime.getDefaultJREContainerEntry(), libEntry[0] };

            javaProject.setRawClasspath(buildPath, project.getFullPath().append("bin"), null);

            IFolder srcFolder = project.getFolder("src");
            if (!srcFolder.exists())
                srcFolder.create(true, true, monitor);
            project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

            monitor.worked(1);

            //Add folder to Java element
            IPackageFragmentRoot folder = javaProject.getPackageFragmentRoot(srcFolder);
            //create package fragment
            IPackageFragment fragment = folder.createPackageFragment(
                    AnnotationsPluginPreferenceConstants.P_ANNOTATIONS_PACKAGE, true, monitor);
            StringBuffer buffer = new StringBuffer();
            ICompilationUnit cu = fragment.createCompilationUnit(fileName,
                    AnnotationHandler.generateInstanceCode(buffer, annotationName, description).toString(),
                    false, monitor);
            project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

            monitor.worked(1);

            project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Activator.log(IStatus.ERROR, "Activator library couldn't be added to the java build path.");
        }
    } else {
        Activator.log(IStatus.ERROR, "Activator library couldn't be added to the java build path.");
    }

    /*final IFile file = container.getFile(new Path(fileName));
    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.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);
}