Search in sources :

Example 11 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 12 with SubMonitor

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

the class QueryJpmDependenciesRunnable method run.

public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    SubMonitor progress = SubMonitor.convert(monitor, 5);
    progress.setTaskName("Querying dependencies...");
    try {
        Set<ResourceDescriptor> resources = repository.getResources(origin, true);
        directResources = new HashSet<ResourceDescriptor>();
        indirectResources = new HashSet<ResourceDescriptor>();
        for (ResourceDescriptor resource : resources) {
            if (resource.dependency)
                indirectResources.add(resource);
            else
                directResources.add(resource);
        }
        progress.worked(5);
    } catch (Exception e) {
        error = "Error searching repository: " + e.getMessage();
    }
}
Also used : SubMonitor(org.eclipse.core.runtime.SubMonitor) InvocationTargetException(java.lang.reflect.InvocationTargetException) ResourceDescriptor(aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor)

Example 13 with SubMonitor

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

the class JAREntryPart method readAsHex.

protected static void readAsHex(ZipFile zipFile, ZipEntry entry, Writer out, long limit, int groupsOf8BytesPerLine, IProgressMonitor monitor) throws IOException {
    SubMonitor progress = createProgressMonitor(entry, limit, monitor);
    boolean limitReached = false;
    long offsetInFile = 0;
    int bytesPerLine = groupsOf8BytesPerLine * 8;
    int asciiPosition = 0;
    char[] asciiBuffer = new char[bytesPerLine + (2 * (groupsOf8BytesPerLine - 1))];
    int bytePosition = 0;
    byte[] buffer = new byte[1024];
    try (InputStream stream = zipFile.getInputStream(entry)) {
        long total = 0;
        while (true) {
            if (progress.isCanceled())
                return;
            int bytesRead = stream.read(buffer, 0, 1024);
            if (bytesRead < 0)
                break;
            for (int i = 0; i < bytesRead; i++) {
                if (bytePosition == 0) {
                    String s = String.format("0x%04x ", offsetInFile);
                    out.write(s);
                    offsetInFile += bytesPerLine;
                }
                asciiBuffer[asciiPosition] = byteToChar(buffer[i]);
                asciiPosition++;
                // Convert to a string character
                out.write(pseudo[(buffer[i] & 0xf0) >>> 4]);
                // convert the nibble to a String Character
                out.write(pseudo[(buffer[i] & 0x0f)]);
                out.write(' ');
                bytePosition++;
                /* do a linebreak after the required number of bytes */
                if (bytePosition >= bytesPerLine) {
                    out.write(' ');
                    out.write(asciiBuffer);
                    out.write('\n');
                    asciiPosition = 0;
                    bytePosition = 0;
                }
                /* put 2 extra spaces between bytes */
                if ((bytePosition > 0) && (bytePosition % 8 == 0)) {
                    asciiBuffer[asciiPosition++] = ' ';
                    asciiBuffer[asciiPosition++] = ' ';
                    out.write(' ');
                }
            }
            total += bytesRead;
            progress.worked(bytesRead);
            if (limit >= 0 && total >= limit) {
                limitReached = true;
                return;
            }
        }
    } finally {
        if (bytePosition > 0) {
            while (bytePosition < bytesPerLine) {
                out.write("   ");
                bytePosition++;
                /* put 2 extra spaces between bytes */
                if ((bytePosition > 0) && (bytePosition % 8 == 0)) {
                    out.write(' ');
                }
            }
            out.write(asciiBuffer, 0, asciiPosition);
        }
        if (limitReached) {
            out.write("\nLimit of " + (limit >> 10) + "Kb reached, the rest of the entry is not shown.");
        }
    }
}
Also used : InputStream(java.io.InputStream) SubMonitor(org.eclipse.core.runtime.SubMonitor)

Example 14 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 15 with SubMonitor

use of org.eclipse.core.runtime.SubMonitor in project translationstudio8 by heartsome.

the class PreloadingRepositoryHandler method doExecuteAndLoad.

void doExecuteAndLoad() {
    if (preloadRepositories()) {
        // cancel any load that is already running
        final IStatus[] checkStatus = new IStatus[1];
        Job.getJobManager().cancel(LoadMetadataRepositoryJob.LOAD_FAMILY);
        final LoadMetadataRepositoryJob loadJob = new LoadMetadataRepositoryJob(getProvisioningUI()) {

            public IStatus runModal(IProgressMonitor monitor) {
                SubMonitor sub = SubMonitor.convert(monitor, getProgressTaskName(), 1000);
                IStatus status = super.runModal(sub.newChild(500));
                if (status.getSeverity() == IStatus.CANCEL)
                    return status;
                if (status.getSeverity() != IStatus.OK) {
                    // 记录检查错误
                    checkStatus[0] = status;
                    return Status.OK_STATUS;
                }
                try {
                    doPostLoadBackgroundWork(sub.newChild(500));
                } catch (OperationCanceledException e) {
                    return Status.CANCEL_STATUS;
                }
                return status;
            }
        };
        setLoadJobProperties(loadJob);
        loadJob.setName(P2UpdateUtil.CHECK_UPDATE_JOB_NAME);
        if (waitForPreload()) {
            loadJob.addJobChangeListener(new JobChangeAdapter() {

                public void done(IJobChangeEvent event) {
                    if (PlatformUI.isWorkbenchRunning())
                        if (event.getResult().isOK()) {
                            PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

                                public void run() {
                                    if (checkStatus[0] != null) {
                                        // 提示连接异常
                                        P2UpdateUtil.openConnectErrorInfoDialog(getShell(), P2UpdateUtil.INFO_TYPE_CHECK);
                                        return;
                                    }
                                    doExecute(loadJob);
                                }
                            });
                        }
                }
            });
            loadJob.setUser(true);
            loadJob.schedule();
        } else {
            loadJob.setSystem(true);
            loadJob.setUser(false);
            loadJob.schedule();
            doExecute(null);
        }
    } else {
        doExecute(null);
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) JobChangeAdapter(org.eclipse.core.runtime.jobs.JobChangeAdapter) SubMonitor(org.eclipse.core.runtime.SubMonitor) IJobChangeEvent(org.eclipse.core.runtime.jobs.IJobChangeEvent) LoadMetadataRepositoryJob(org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob)

Aggregations

SubMonitor (org.eclipse.core.runtime.SubMonitor)35 IStatus (org.eclipse.core.runtime.IStatus)14 CoreException (org.eclipse.core.runtime.CoreException)13 Status (org.eclipse.core.runtime.Status)13 IOException (java.io.IOException)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)8 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)8 InputStream (java.io.InputStream)7 IFile (org.eclipse.core.resources.IFile)7 File (java.io.File)5 IProject (org.eclipse.core.resources.IProject)4 MultiStatus (org.eclipse.core.runtime.MultiStatus)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ArrayList (java.util.ArrayList)3 IContainer (org.eclipse.core.resources.IContainer)3 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)3 IRunnableWithProgress (org.eclipse.jface.operation.IRunnableWithProgress)3 ResourceDescriptor (aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 SQLException (java.sql.SQLException)2