Search in sources :

Example 6 with SubMonitor

use of org.eclipse.core.runtime.SubMonitor in project bndtools by bndtools.

the class GenerateIndexJob method run.

@Override
protected IStatus run(IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor);
    // Generate index
    try (OutputStream outputStream = IO.outputStream(outputFile)) {
        ResourceIndexer indexer = Plugin.getDefault().getResourceIndexer();
        indexer.index(files, outputStream, config);
    } catch (Exception e) {
        return new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error indexing files.", e);
    }
    // Make eclipse aware of the new/changed resource
    final IWorkspace ws = ResourcesPlugin.getWorkspace();
    final IWorkspaceRunnable runnable = new IWorkspaceRunnable() {

        @Override
        public void run(IProgressMonitor monitor) throws CoreException {
            IFile[] outputResources = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(outputFile.toURI());
            if (outputResources != null) {
                for (IFile resource : outputResources) {
                    resource.refreshLocal(IResource.DEPTH_ZERO, monitor);
                }
            }
        }
    };
    try {
        ws.run(runnable, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
    } catch (CoreException e) {
        return new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error refreshing workspace files.", e);
    }
    return Status.OK_STATUS;
}
Also used : Status(org.eclipse.core.runtime.Status) IStatus(org.eclipse.core.runtime.IStatus) IWorkspaceRunnable(org.eclipse.core.resources.IWorkspaceRunnable) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IFile(org.eclipse.core.resources.IFile) CoreException(org.eclipse.core.runtime.CoreException) OutputStream(java.io.OutputStream) IWorkspace(org.eclipse.core.resources.IWorkspace) SubMonitor(org.eclipse.core.runtime.SubMonitor) ResourceIndexer(org.osgi.service.indexer.ResourceIndexer) CoreException(org.eclipse.core.runtime.CoreException)

Example 7 with SubMonitor

use of org.eclipse.core.runtime.SubMonitor in project bndtools by bndtools.

the class WorkspaceSetupWizard method performFinish.

@Override
public boolean performFinish() {
    final IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final File targetDir = previewPage.getTargetDir();
    final Set<String> checkedPaths = previewPage.getCheckedPaths();
    final boolean cleanBuild = setupPage.isCleanBuild();
    try {
        // Expand the template
        ResourceMap outputs = previewPage.getTemplateOutputs();
        final Set<File> topLevelFolders = new HashSet<>();
        for (Entry<String, Resource> entry : outputs.entries()) {
            String path = entry.getKey();
            if (checkedPaths.contains(path)) {
                Resource resource = entry.getValue();
                // Create the folder or file resource
                File file = new File(targetDir, path);
                switch(resource.getType()) {
                    case Folder:
                        Files.createDirectories(file.toPath());
                        break;
                    case File:
                        File parentDir = file.getParentFile();
                        Files.createDirectories(parentDir.toPath());
                        try (InputStream in = resource.getContent()) {
                            IO.copy(in, file);
                        }
                        break;
                    default:
                        throw new IllegalArgumentException("Unknown resource type " + resource.getType());
                }
                // Remember the top-level folders we create, for importing below
                if (file.getParentFile().equals(targetDir))
                    topLevelFolders.add(file);
            }
        }
        // Import anything that looks like an Eclipse project & do a full rebuild
        final IWorkspaceRunnable importProjectsRunnable = new IWorkspaceRunnable() {

            @Override
            public void run(IProgressMonitor monitor) throws CoreException {
                File[] children = targetDir.listFiles();
                if (children != null) {
                    int work = children.length;
                    if (cleanBuild)
                        work += 2;
                    SubMonitor progress = SubMonitor.convert(monitor, work);
                    for (File folder : children) {
                        if (folder.isDirectory() && topLevelFolders.contains(folder)) {
                            String projectName = folder.getName();
                            File projectFile = new File(folder, IProjectDescription.DESCRIPTION_FILE_NAME);
                            if (projectFile.exists()) {
                                IProject project = workspace.getRoot().getProject(projectName);
                                if (!project.exists()) {
                                    // No existing project in the workspace, so import the generated project.
                                    SubMonitor subProgress = progress.newChild(1);
                                    project.create(subProgress.newChild(1));
                                    project.open(subProgress.newChild(1));
                                    // Now make sure it is associated with the right location
                                    IProjectDescription description = project.getDescription();
                                    IPath path = Path.fromOSString(projectFile.getParentFile().getAbsolutePath());
                                    description.setLocation(path);
                                    project.move(description, IResource.REPLACE, progress);
                                } else {
                                    // If a project with the same name exists, does it live in the same location? If not, we can't import the generated project.
                                    File existingLocation = project.getLocation().toFile();
                                    if (!existingLocation.equals(folder)) {
                                        String message = String.format("Cannot import generated project from %s. A project named %s already exists in the workspace and is mapped to location %s", folder.getAbsolutePath(), projectName, existingLocation);
                                        throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, message, null));
                                    }
                                    SubMonitor subProgress = progress.newChild(1);
                                    // Open it if closed
                                    project.open(subProgress.newChild(1));
                                    // Refresh, as the template may have generated new content
                                    project.refreshLocal(IResource.DEPTH_INFINITE, subProgress.newChild(1));
                                }
                            }
                        }
                    }
                    if (cleanBuild)
                        workspace.build(IncrementalProjectBuilder.CLEAN_BUILD, progress.newChild(2));
                }
            }
        };
        getContainer().run(true, true, new IRunnableWithProgress() {

            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    workspace.run(importProjectsRunnable, monitor);
                } catch (CoreException e) {
                    throw new InvocationTargetException(e);
                }
                new WorkspaceJob("Load Repositories") {

                    @Override
                    public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
                        try {
                            Central.refreshPlugins();
                        } catch (Exception e) {
                        // There may be no workspace yet
                        }
                        return Status.OK_STATUS;
                    }
                }.schedule();
            }
        });
        // Prompt to switch to the bndtools perspective
        IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
        IPerspectiveDescriptor currentPerspective = window.getActivePage().getPerspective();
        if (!"bndtools.perspective".equals(currentPerspective.getId())) {
            if (MessageDialog.openQuestion(getShell(), "Bndtools Perspective", "Switch to the Bndtools perspective?")) {
                workbench.showPerspective("bndtools.perspective", window);
            }
        }
        return true;
    } catch (InvocationTargetException e) {
        ErrorDialog.openError(getShell(), "Error", null, new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error generating template output", e.getTargetException()));
        return false;
    } catch (Exception e) {
        ErrorDialog.openError(getShell(), "Error", null, new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error generating template output", e));
        return false;
    }
}
Also used : IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) HashSet(java.util.HashSet) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IWorkspaceRunnable(org.eclipse.core.resources.IWorkspaceRunnable) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) IPath(org.eclipse.core.runtime.IPath) InputStream(java.io.InputStream) Resource(org.bndtools.templating.Resource) IResource(org.eclipse.core.resources.IResource) SubMonitor(org.eclipse.core.runtime.SubMonitor) WorkspaceJob(org.eclipse.core.resources.WorkspaceJob) IProject(org.eclipse.core.resources.IProject) InvocationTargetException(java.lang.reflect.InvocationTargetException) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ResourceMap(org.bndtools.templating.ResourceMap) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) IWorkspace(org.eclipse.core.resources.IWorkspace) IProjectDescription(org.eclipse.core.resources.IProjectDescription) IPerspectiveDescriptor(org.eclipse.ui.IPerspectiveDescriptor) File(java.io.File)

Example 8 with SubMonitor

use of org.eclipse.core.runtime.SubMonitor in project bndtools by bndtools.

the class CreateFileChange method perform.

@Override
public Change perform(IProgressMonitor monitor) throws CoreException {
    SubMonitor progress = SubMonitor.convert(monitor, encoding != null ? 2 : 1);
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IFile file = root.getFile(path);
    file.create(source, updateFlags, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
    if (encoding != null)
        file.setCharset(encoding, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
    return new DeleteResourceChange(path, true);
}
Also used : IFile(org.eclipse.core.resources.IFile) IWorkspaceRoot(org.eclipse.core.resources.IWorkspaceRoot) SubMonitor(org.eclipse.core.runtime.SubMonitor) DeleteResourceChange(org.eclipse.ltk.core.refactoring.resource.DeleteResourceChange)

Example 9 with SubMonitor

use of org.eclipse.core.runtime.SubMonitor in project bndtools by bndtools.

the class NewBndProjectWizard method generateProjectContent.

@Override
protected void generateProjectContent(IProject project, IProgressMonitor monitor, Map<String, String> params) throws IOException {
    Map<String, List<Object>> templateParams = new HashMap<>();
    for (Entry<String, String> param : params.entrySet()) {
        templateParams.put(param.getKey(), Collections.<Object>singletonList(param.getValue()));
    }
    Template template = templatePage.getTemplate();
    try {
        ResourceMap outputs;
        if (template != null) {
            outputs = template.generateOutputs(templateParams);
        } else {
            // empty
            outputs = new ResourceMap();
        }
        SubMonitor progress = SubMonitor.convert(monitor, outputs.size() * 3);
        for (Entry<String, Resource> outputEntry : outputs.entries()) {
            String path = outputEntry.getKey();
            Resource resource = outputEntry.getValue();
            // Strip leading slashes from path
            while (path.startsWith("/")) path = path.substring(1);
            switch(resource.getType()) {
                case Folder:
                    if (!path.isEmpty()) {
                        IFolder folder = project.getFolder(path);
                        FileUtils.mkdirs(folder, progress.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
                    }
                    break;
                case File:
                    IFile file = project.getFile(path);
                    FileUtils.mkdirs(file.getParent(), progress.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
                    try (InputStream in = resource.getContent()) {
                        if (file.exists())
                            file.setContents(in, 0, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
                        else
                            file.create(in, 0, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
                        file.setCharset(resource.getTextEncoding(), progress.newChild(1));
                    }
                    break;
                default:
                    throw new IllegalArgumentException("Unknown resource type " + resource.getType());
            }
        }
    } catch (Exception e) {
        String message = MessageFormat.format("Error generating project contents from template \"{0}\": {1}", template != null ? template.getName() : "<null>", e.getMessage());
        throw new IOException(message);
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) HashMap(java.util.HashMap) InputStream(java.io.InputStream) SubMonitor(org.eclipse.core.runtime.SubMonitor) StringResource(org.bndtools.templating.StringResource) Resource(org.bndtools.templating.Resource) IOException(java.io.IOException) IOException(java.io.IOException) BuiltInTemplate(org.bndtools.core.ui.wizards.shared.BuiltInTemplate) Template(org.bndtools.templating.Template) ResourceMap(org.bndtools.templating.ResourceMap) List(java.util.List) IFolder(org.eclipse.core.resources.IFolder)

Example 10 with SubMonitor

use of org.eclipse.core.runtime.SubMonitor in project bndtools by bndtools.

the class ResourceCopier method copy.

public static IFile copy(URL url, IFile dst, Map<String, String> replaceRegularExpressions, IProgressMonitor monitor) throws IOException, CoreException {
    InputStream is = null;
    try {
        SubMonitor progress = SubMonitor.convert(monitor, 2);
        if (url.getPath().endsWith("/")) {
            File file = dst.getProjectRelativePath().toFile();
            if (file.isDirectory())
                // already done
                return dst;
            if (file.isFile())
                throw new IllegalArgumentException("Expected no file or a directory, but was a file: " + file);
            file.mkdirs();
            // already done
            return dst;
        }
        ResourceReplacer replacer = null;
        if ((replaceRegularExpressions == null) || replaceRegularExpressions.isEmpty()) {
            is = url.openStream();
        } else {
            replacer = new ResourceReplacer(replaceRegularExpressions, url);
            replacer.start();
            is = replacer.getStream();
        }
        if (dst.exists()) {
            dst.setContents(is, false, true, progress.newChild(2, SubMonitor.SUPPRESS_NONE));
        } else {
            FileUtils.recurseCreate(dst.getParent(), progress.newChild(1, SubMonitor.SUPPRESS_NONE));
            dst.create(is, false, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
        }
        if (replacer != null) {
            try {
                replacer.join();
            } catch (InterruptedException e) {
            /* swallow */
            }
            if (replacer.getResult() != null) {
                throw replacer.getResult();
            }
        }
    } finally {
        IO.close(is);
    }
    return dst;
}
Also used : InputStream(java.io.InputStream) SubMonitor(org.eclipse.core.runtime.SubMonitor) IFile(org.eclipse.core.resources.IFile) File(java.io.File)

Aggregations

SubMonitor (org.eclipse.core.runtime.SubMonitor)61 CoreException (org.eclipse.core.runtime.CoreException)27 IStatus (org.eclipse.core.runtime.IStatus)25 Status (org.eclipse.core.runtime.Status)24 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)15 IOException (java.io.IOException)12 IFile (org.eclipse.core.resources.IFile)10 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)10 InputStream (java.io.InputStream)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)9 IPath (org.eclipse.core.runtime.IPath)9 IProject (org.eclipse.core.resources.IProject)8 File (java.io.File)7 MultiStatus (org.eclipse.core.runtime.MultiStatus)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)5 IContainer (org.eclipse.core.resources.IContainer)4 IWorkspaceRoot (org.eclipse.core.resources.IWorkspaceRoot)4 IRunnableWithProgress (org.eclipse.jface.operation.IRunnableWithProgress)4 URI (java.net.URI)3