Example usage for org.eclipse.jdt.core IPackageFragment getResource

List of usage examples for org.eclipse.jdt.core IPackageFragment getResource

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragment getResource.

Prototype

IResource getResource();

Source Link

Document

Returns the innermost resource enclosing this element.

Usage

From source file:at.bestsolution.efxclipse.tooling.pde.e4.project.E4NewProjectWizard.java

License:Open Source License

/**
 * create products extension detail//ww w.j  a va 2 s .co  m
 * 
 * @param project
 */
public void createApplicationResources(IProject project, IProgressMonitor monitor) {
    Map<String, String> map = fApplicationPage.getData();
    if (map == null || map.get(NewApplicationWizardPage.PRODUCT_NAME) == null)
        return;

    // If the project has invalid characters, the plug-in name would replace
    // them with underscores, product name does the same
    String pluginName = map.get(NewApplicationWizardPage.PRODUCT_NAME);
    String xmiPath = map.get(NewApplicationWizardPage.APPLICATION_XMI_PROPERTY);

    // If there's no Activator created we create default package
    if (!fPluginData.doGenerateClass()) {
        String packageName = fPluginData.getId();
        IPath path = new Path(packageName.replace('.', '/'));
        if (fPluginData.getSourceFolderName().trim().length() > 0)
            path = new Path(fPluginData.getSourceFolderName()).append(path);

        try {
            CoreUtility.createFolder(project.getFolder(path));
        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragment fragment = null;

    try {
        for (IPackageFragment element : javaProject.getPackageFragments()) {
            if (element.getKind() == IPackageFragmentRoot.K_SOURCE) {
                fragment = element;
            }
        }
    } catch (JavaModelException e1) {
        e1.printStackTrace();
    }

    if (xmiPath != null && xmiPath.trim().length() > 0) {
        // Create a resource set
        //
        ResourceSet resourceSet = new ResourceSetImpl();

        // Get the URI of the model file.
        //
        URI fileURI = URI.createPlatformResourceURI(project.getName() + "/" + xmiPath, true);

        // Create a resource for this file.
        //
        Resource resource = resourceSet.createResource(fileURI);

        MApplication application = MApplicationFactory.INSTANCE.createApplication();

        application.setElementId("org.eclipse.e4.ide.application");

        MAddon addon = MApplicationFactory.INSTANCE.createAddon();
        addon.setElementId("org.eclipse.e4.core.commands.service");
        addon.setContributionURI(
                "bundleclass://org.eclipse.e4.core.commands/org.eclipse.e4.core.commands.CommandServiceAddon");
        application.getAddons().add(addon);

        addon = MApplicationFactory.INSTANCE.createAddon();
        addon.setElementId("org.eclipse.e4.ui.contexts.service");
        addon.setContributionURI(
                "bundleclass://org.eclipse.e4.ui.services/org.eclipse.e4.ui.services.ContextServiceAddon");
        application.getAddons().add(addon);

        addon = MApplicationFactory.INSTANCE.createAddon();
        addon.setElementId("at.bestsolution.efxclipse.runtime.bindings.e4.service");
        addon.setContributionURI(
                "bundleclass://at.bestsolution.efxclipse.runtime.bindings.e4/at.bestsolution.efxclipse.runtime.bindings.e4.BindingServiceAddon");
        application.getAddons().add(addon);

        addon = MApplicationFactory.INSTANCE.createAddon();
        addon.setElementId("org.eclipse.e4.ui.workbench.commands.model");
        addon.setContributionURI(
                "bundleclass://org.eclipse.e4.ui.workbench/org.eclipse.e4.ui.internal.workbench.addons.CommandProcessingAddon");
        application.getAddons().add(addon);

        addon = MApplicationFactory.INSTANCE.createAddon();
        addon.setElementId("org.eclipse.e4.ui.workbench.contexts.model");
        addon.setContributionURI(
                "bundleclass://org.eclipse.e4.ui.workbench/org.eclipse.e4.ui.internal.workbench.addons.ContextProcessingAddon");
        application.getAddons().add(addon);

        addon = MApplicationFactory.INSTANCE.createAddon();
        addon.setElementId("at.bestsolution.efxclipse.runtime.bindings.e4.model");
        addon.setContributionURI(
                "bundleclass://at.bestsolution.efxclipse.runtime.bindings.e4/at.bestsolution.efxclipse.runtime.bindings.e4.BindingProcessingAddon");
        application.getAddons().add(addon);

        MBindingContext rootContext = MCommandsFactory.INSTANCE.createBindingContext();
        rootContext.setElementId("org.eclipse.ui.contexts.dialogAndWindow");
        rootContext.setName("In Dialog and Windows");

        MBindingContext childContext = MCommandsFactory.INSTANCE.createBindingContext();
        childContext.setElementId("org.eclipse.ui.contexts.window");
        childContext.setName("In Windows");
        rootContext.getChildren().add(childContext);

        childContext = MCommandsFactory.INSTANCE.createBindingContext();
        childContext.setElementId("org.eclipse.ui.contexts.dialog");
        childContext.setName("In Dialogs");
        rootContext.getChildren().add(childContext);

        application.getRootContext().add(rootContext);
        application.getBindingContexts().add(rootContext);

        resource.getContents().add((EObject) application);

        MCommand openCommand = createCommand("media.open", "openMedia", "OpenHandler", "M1+O", pluginName,
                fragment, application);
        MCommand refreshCommand = createCommand("media.refresh", "refreshMedia", "RefreshHandler", "M1+R",
                pluginName, fragment, application);

        MTrimmedWindow mainWindow = MBasicFactory.INSTANCE.createTrimmedWindow();
        mainWindow.setElementId("org.efxclipse.e4.mainWindow");
        mainWindow.getPersistedState().put("fx.stage.decoration", "platform:/plugin/" + pluginName + "/"
                + fragment.getElementName().replace('.', '/') + "/decoration/TopArea.fxml");
        application.getChildren().add(mainWindow);
        {
            mainWindow.setLabel(pluginName);
            mainWindow.setX(30);
            mainWindow.setY(30);
            mainWindow.setWidth(1024);
            mainWindow.setHeight(768);

            // Top-Sash
            {
                MPartSashContainer sash = MBasicFactory.INSTANCE.createPartSashContainer();
                sash.setHorizontal(true);

                // Create a left part
                {
                    MPart part = MBasicFactory.INSTANCE.createPart();
                    part.setContributionURI("bundleclass://" + pluginName + "/" + fragment.getElementName()
                            + ".parts.MediaListPart");
                    part.setContainerData("0.3");
                    sash.getChildren().add(part);
                }

                // Create a right a stack
                {
                    MPartStack stack = MBasicFactory.INSTANCE.createPartStack();
                    stack.setContainerData("0.7");
                    stack.setElementId("content.stack");
                    sash.getChildren().add(stack);
                }

                mainWindow.getChildren().add(sash);
            }

            // WindowTrim
            {
                MTrimBar trimBar = MBasicFactory.INSTANCE.createTrimBar();
                mainWindow.getTrimBars().add(trimBar);

                MToolBar toolBar = MMenuFactory.INSTANCE.createToolBar();
                toolBar.setElementId("org.efxclipse.e4.maintoolbar");
                trimBar.getChildren().add(toolBar);

                MHandledToolItem toolItemOpen = MMenuFactory.INSTANCE.createHandledToolItem();
                toolBar.getChildren().add(toolItemOpen);
                toolItemOpen.setElementId("org.efxclipse.e4.toolitem.open");
                toolItemOpen.setIconURI("platform:/plugin/" + pluginName + "/icons/edit-image-face-show.png");
                toolItemOpen.setCommand(openCommand);

                MHandledToolItem toolItemSave = MMenuFactory.INSTANCE.createHandledToolItem();
                toolBar.getChildren().add(toolItemSave);
                toolItemSave.setElementId("org.efxclipse.e4.toolitem.save");
                toolItemSave.setIconURI("platform:/plugin/" + pluginName + "/icons/system-reboot.png");
                toolItemSave.setCommand(refreshCommand);
            }
        }

        Map<Object, Object> options = new HashMap<Object, Object>();
        options.put(XMLResource.OPTION_ENCODING, "UTF-8");
        try {
            resource.save(options);
        } catch (IOException e) {
            PDEPlugin.logException(e);
        }
    }

    IFile f = project.getFile(new Path(project.getName() + ".product.launch"));
    E4LaunchDef def = new E4LaunchDef();
    def.setProjectName(project.getName());
    def.getTargetPlugins().addAll(E4LaunchDef.getE4TargetPlugins());
    def.getWorkbenchPlugins().add(new PluginLaunchDef(project.getName()));
    try {
        ByteArrayInputStream in = new ByteArrayInputStream(
                new LaunchGenerator().generate(def).toString().getBytes());
        f.create(in, true, monitor);
        in.close();
    } catch (CoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String cssPath = map.get(NewApplicationWizardPage.APPLICATION_CSS_PROPERTY);
    if (cssPath != null && cssPath.trim().length() > 0) {
        IFile file = project.getFile(cssPath);

        try {
            prepareFolder(file.getParent(), monitor);

            URL corePath = ResourceLocator.getProjectTemplateFiles("css/default.css");
            file.create(corePath.openStream(), true, monitor);
        } catch (Exception e) {
            PDEPlugin.logException(e);
        }
    }

    String template_id = "common";
    Set<String> binaryExtentions = new HashSet<String>();
    binaryExtentions.add(".gif");
    binaryExtentions.add(".png");
    binaryExtentions.add(".jpg");
    binaryExtentions.add(".flv");

    Map<String, String> keys = new HashMap<String, String>();
    keys.put("projectName", pluginName);
    keys.put("packageName", fragment.getElementName() + ".handlers");
    keys.put("packageName_parts", fragment.getElementName() + ".parts");
    keys.put("packageName_model", fragment.getElementName() + ".model");
    keys.put("packageName_decoration", fragment.getElementName() + ".decoration");

    try {
        URL corePath = ResourceLocator.getProjectTemplateFiles(template_id);
        IRunnableWithProgress op = new TemplateOperation(corePath, project, keys, binaryExtentions);
        getContainer().run(false, true, op);
    } catch (Exception e) {
        PDEPlugin.logException(e);
    }

    try {
        URL corePath = ResourceLocator.getProjectTemplateFiles("src");
        IRunnableWithProgress op = new TemplateOperation(corePath, (IContainer) fragment.getResource(), keys,
                binaryExtentions);
        getContainer().run(false, true, op);
    } catch (Exception e) {
        PDEPlugin.logException(e);
    }
}

From source file:at.bestsolution.javafx.ide.jdt.internal.JavaClassResourceService.java

License:Open Source License

IResource handleElementCreation(IContainer container, String packageName, String className) {
    // FIXME This is temporary
    if (!container.getProject().isOpen()) {
        try {//  w w w.  j  a va 2s . co  m
            container.getProject().open(new NullProgressMonitor());
        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    IProject pr = container.getProject();

    IJavaElement jElement = getInitialJavaElement(container);
    IPackageFragmentRoot jRoot = getFragmentRoot(jElement);

    try {
        IJavaProject jProject = JavaCore.create(pr);
        jProject.open(new NullProgressMonitor());
        jRoot.open(new NullProgressMonitor());
        IPackageFragment fragment = jRoot.getPackageFragment(packageName);
        if (!fragment.exists()) {
            ((IFolder) fragment.getResource()).create(true, true, null);
        }
        ICompilationUnit u = fragment.getCompilationUnit(className + ".java");
        IFile f = (IFile) u.getResource();
        ByteArrayInputStream in = new ByteArrayInputStream(
                new String("public class " + className + " {\n}").getBytes());
        f.create(in, IFile.FORCE | IFile.KEEP_HISTORY, new NullProgressMonitor());
        in.close();
        // pr.build(IncrementalProjectBuilder.FULL_BUILD, new
        // NullProgressMonitor());
        return f;
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.err.println(jRoot);

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.refactorings.core.AndroidTypeMoveParticipant.java

License:Open Source License

@Override
protected boolean initialize(Object element) {
    if (element instanceof IType) {
        IType type = (IType) element;//from   w w  w .ja  va 2  s .  c  o m
        IJavaProject javaProject = (IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT);
        mProject = javaProject.getProject();
        IResource manifestResource = mProject
                .findMember(AdtConstants.WS_SEP + SdkConstants.FN_ANDROID_MANIFEST_XML);

        if (manifestResource == null || !manifestResource.exists() || !(manifestResource instanceof IFile)) {
            RefactoringUtil.logInfo("Invalid or missing the " + SdkConstants.FN_ANDROID_MANIFEST_XML
                    + " in the " + mProject.getName() + " project.");
            return false;
        }
        mManifestFile = (IFile) manifestResource;
        ManifestData manifestData;
        manifestData = AndroidManifestHelper.parseForData(mManifestFile);
        if (manifestData == null) {
            return false;
        }
        mAppPackage = manifestData.getPackage();
        mOldFqcn = type.getFullyQualifiedName();
        Object destination = getArguments().getDestination();
        if (destination instanceof IPackageFragment) {
            IPackageFragment packageFragment = (IPackageFragment) destination;
            mNewFqcn = packageFragment.getElementName() + "." + type.getElementName();
        } else if (destination instanceof IResource) {
            try {
                IPackageFragment[] fragments = javaProject.getPackageFragments();
                for (IPackageFragment fragment : fragments) {
                    IResource resource = fragment.getResource();
                    if (resource.equals(destination)) {
                        mNewFqcn = fragment.getElementName() + '.' + type.getElementName();
                        break;
                    }
                }
            } catch (JavaModelException e) {
                // pass
            }
        }
        return mOldFqcn != null && mNewFqcn != null;
    }

    return false;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Locates the package declarations corresponding to the search pattern.
 *///from   w w  w  .  ja  va  2 s.  co m
protected void locatePackageDeclarations(SearchPattern searchPattern, SearchParticipant participant,
        IJavaProject[] projects) throws CoreException {
    if (this.progressMonitor != null && this.progressMonitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    if (searchPattern instanceof OrPattern) {
        SearchPattern[] patterns = ((OrPattern) searchPattern).patterns;
        for (int i = 0, length = patterns.length; i < length; i++) {
            locatePackageDeclarations(patterns[i], participant, projects);
        }
    } else if (searchPattern instanceof PackageDeclarationPattern) {
        IJavaElement focus = searchPattern.focus;
        if (focus != null) {
            if (encloses(focus)) {
                SearchMatch match = new PackageDeclarationMatch(
                        focus.getAncestor(IJavaElement.PACKAGE_FRAGMENT), SearchMatch.A_ACCURATE, -1, -1,
                        participant, focus.getResource());
                report(match);
            }
            return;
        }
        PackageDeclarationPattern pkgPattern = (PackageDeclarationPattern) searchPattern;
        boolean isWorkspaceScope = this.scope == JavaModelManager.getJavaModelManager().getWorkspaceScope();
        IPath[] scopeProjectsAndJars = isWorkspaceScope ? null : this.scope.enclosingProjectsAndJars();
        int scopeLength = isWorkspaceScope ? 0 : scopeProjectsAndJars.length;
        SimpleSet packages = new SimpleSet();
        for (int i = 0, length = projects.length; i < length; i++) {
            IJavaProject javaProject = projects[i];
            if (this.progressMonitor != null) {
                if (this.progressMonitor.isCanceled())
                    throw new OperationCanceledException();
                this.progressWorked++;
                if ((this.progressWorked % this.progressStep) == 0)
                    this.progressMonitor.worked(this.progressStep);
            }
            // Verify that project belongs to the scope
            if (!isWorkspaceScope) {
                boolean found = false;
                for (int j = 0; j < scopeLength; j++) {
                    if (javaProject.getPath().equals(scopeProjectsAndJars[j])) {
                        found = true;
                        break;
                    }
                }
                if (!found)
                    continue;
            }
            // Get all project package fragment names
            this.nameLookup = ((JavaProject) projects[i]).newNameLookup(this.workingCopies);
            IPackageFragment[] packageFragments = this.nameLookup
                    .findPackageFragments(new String(pkgPattern.pkgName), false, true);
            int pLength = packageFragments == null ? 0 : packageFragments.length;
            // Report matches avoiding duplicate names
            for (int p = 0; p < pLength; p++) {
                IPackageFragment fragment = packageFragments[p];
                if (packages.addIfNotIncluded(fragment) == null)
                    continue;
                if (encloses(fragment)) {
                    IResource resource = fragment.getResource();
                    if (resource == null) // case of a file in an external jar
                        resource = javaProject.getProject();
                    try {
                        if (encloses(fragment)) {
                            SearchMatch match = new PackageDeclarationMatch(fragment, SearchMatch.A_ACCURATE,
                                    -1, -1, participant, resource);
                            report(match);
                        }
                    } catch (JavaModelException e) {
                        throw e;
                    } catch (CoreException e) {
                        throw new JavaModelException(e);
                    }
                }
            }
        }
    }
}

From source file:com.google.gdt.eclipse.designer.wizards.model.common.AbstractCreateOperation.java

License:Open Source License

/**
 * Creates file with name 'targetName' in package using given template name and variables map.
 *//*from w  w  w  .java2  s  .c om*/
protected static IFile createFileFromTemplate(IPackageFragment targetPackage, String targetName,
        String templateName, Map<String, String> variables) throws Exception {
    return createFileFromTemplate((IFolder) targetPackage.getResource(), targetName, templateName, variables);
}

From source file:com.google.gdt.eclipse.designer.wizards.model.common.AbstractCreateOperation.java

License:Open Source License

/**
 * Creates file with name 'targetName' in package using given source.
 *///from w  w  w  .  j av  a 2s.  c o m
protected static IFile createFile(IPackageFragment targetPackage, String targetName, String source)
        throws Exception {
    return createFile((IFolder) targetPackage.getResource(), targetName, source.getBytes());
}

From source file:com.google.gdt.eclipse.designer.wizards.model.mvp.ViewComposite.java

License:Open Source License

public static String getClientFactoryName(IPackageFragment packageFragment) throws Exception {
    return packageFragment.getResource().getPersistentProperty(KEY_CLIENT_FACTORY);
}

From source file:com.google.gdt.eclipse.designer.wizards.model.mvp.ViewComposite.java

License:Open Source License

public static void setClientFactoryName(IPackageFragment packageFragment, String value) throws Exception {
    packageFragment.getResource().setPersistentProperty(KEY_CLIENT_FACTORY, value);
}

From source file:com.google.gwt.eclipse.core.modules.ModuleFile.java

License:Open Source License

/**
 * <p>/* w w  w. j  a v  a2 s .co m*/
 * Returns whether a package is on the client source path of this module. The source paths include
 * the paths explicitly declared with <code>&lt;source&gt;</code> tags and all of their descendant
 * packages.
 * </p>
 * <p>
 * For example, if a module is located in <code>com.hello</code> and has the default client source
 * path "client", then <code>com.hello.client</code> and <code>com.hello.client.utils</code> would
 * both return true.
 * </p>
 *
 * @param pckg package to check
 * @return <code>true</code> if this package is on a client source path, and <code>false</code>
 *         otherwise
 */
public boolean isSourcePackage(IPackageFragment pckg) {
    IResource resource = pckg.getResource();
    if (resource.getType() == IResource.FOLDER) {
        IPath pckgFolderPath = resource.getFullPath();

        // Check each source path to see if it's an ancestor of this package
        for (IFolder clientFolder : getFolders(getSourcePaths())) {
            IPath clientFolderPath = clientFolder.getFullPath();
            if (clientFolderPath.isPrefixOf(pckgFolderPath)) {
                return true;
            }
        }
    }

    return false;
}

From source file:com.google.gwt.eclipse.core.wizards.NewUiBinderWizardPage.java

License:Open Source License

private IPath getUiXmlFilePath() {
    IPackageFragment pckgFragment = getPackageFragment();
    if (pckgFragment == null) {
        return null;
    }// w  w w  .j a v  a2  s  .c  om
    return pckgFragment.getResource().getFullPath()
            .append(getTypeName() + UiBinderConstants.UI_BINDER_XML_EXTENSION);
}