Search in sources :

Example 26 with Job

use of org.eclipse.core.runtime.jobs.Job in project azure-tools-for-java by Microsoft.

the class AzureNewDockerWizard method createHost.

public void createHost() {
    AzureDockerPreferredSettings dockerPreferredSettings = dockerManager.getDockerPreferredSettings();
    if (dockerPreferredSettings == null) {
        dockerPreferredSettings = new AzureDockerPreferredSettings();
    }
    dockerPreferredSettings.dockerApiName = newHost.apiUrl;
    dockerPreferredSettings.region = newHost.hostVM.region;
    dockerPreferredSettings.vmSize = newHost.hostVM.vmSize;
    dockerPreferredSettings.vmOS = newHost.hostOSType.name();
    dockerManager.setDockerPreferredSettings(dockerPreferredSettings);
    Job createDockerHostJob = new Job("Creating Docker virtual machine " + newHost.name) {

        @Override
        protected IStatus run(IProgressMonitor progressMonitor) {
            progressMonitor.beginTask("start task", 100);
            try {
                DockerHost dockerHost = newHost;
                progressMonitor.subTask(String.format("Reading subscription details for Docker host %s ...", dockerHost.apiUrl));
                progressMonitor.worked(5);
                Azure azureClient = dockerManager.getSubscriptionsMap().get(dockerHost.sid).azureClient;
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.subTask(String.format("Creating new virtual machine %s ...", dockerHost.name));
                progressMonitor.worked(10);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Creating new virtual machine: " + new Date().toString());
                AzureDockerVMOps.createDockerHostVM(azureClient, dockerHost);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done creating new virtual machine: " + new Date().toString());
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.subTask("Getting the new Docker virtual machines details...");
                progressMonitor.worked(5);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Getting the new Docker hosts details: " + new Date().toString());
                VirtualMachine vm = azureClient.virtualMachines().getByResourceGroup(dockerHost.hostVM.resourceGroupName, dockerHost.hostVM.name);
                if (vm != null) {
                    DockerHost updatedHost = AzureDockerVMOps.getDockerHost(vm, dockerManager.getDockerVaultsMap());
                    if (updatedHost != null) {
                        dockerHost.hostVM = updatedHost.hostVM;
                        dockerHost.apiUrl = updatedHost.apiUrl;
                    }
                }
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done getting the new Docker hosts details: " + new Date().toString());
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.subTask(String.format("Waiting for virtual machine %s to be up...", dockerHost.name));
                progressMonitor.worked(55);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Waiting for virtual machine to be up: " + new Date().toString());
                AzureDockerVMOps.waitForVirtualMachineStartup(azureClient, dockerHost);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done Waiting for virtual machine to be up: " + new Date().toString());
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.subTask(String.format("Configuring Docker service for %s ...", dockerHost.apiUrl));
                progressMonitor.worked(15);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Configuring Docker host: " + new Date().toString());
                AzureDockerVMOps.installDocker(dockerHost);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done configuring Docker host: " + new Date().toString());
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Finished setting up Docker host");
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                if (dockerHost.certVault != null && dockerHost.certVault.hostName != null) {
                    AzureDockerUIResources.createDockerKeyVault(dockerHost, dockerManager);
                }
                progressMonitor.subTask("Refreshing the Docker virtual machines details...");
                progressMonitor.worked(5);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Refreshing Docker hosts details: " + new Date().toString());
                vm = azureClient.virtualMachines().getByResourceGroup(dockerHost.hostVM.resourceGroupName, dockerHost.hostVM.name);
                if (vm != null) {
                    DockerHost updatedHost = AzureDockerVMOps.getDockerHost(vm, dockerManager.getDockerVaultsMap());
                    if (updatedHost != null) {
                        updatedHost.sid = dockerHost.sid;
                        updatedHost.hostVM.sid = dockerHost.hostVM.sid;
                        if (updatedHost.certVault == null) {
                            updatedHost.certVault = dockerHost.certVault;
                            updatedHost.hasPwdLogIn = dockerHost.hasPwdLogIn;
                            updatedHost.hasSSHLogIn = dockerHost.hasSSHLogIn;
                            updatedHost.isTLSSecured = dockerHost.isTLSSecured;
                        }
                        dockerManager.addDockerHostDetails(updatedHost);
                        if (AzureUIRefreshCore.listeners != null) {
                            AzureUIRefreshCore.execute(new AzureUIRefreshEvent(AzureUIRefreshEvent.EventType.ADD, updatedHost));
                        }
                    }
                }
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done refreshing Docker hosts details: " + new Date().toString());
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.done();
                return Status.OK_STATUS;
            } catch (Exception e) {
                String msg = "An error occurred while attempting to create Docker host." + "\n" + e.getMessage();
                log.log(Level.SEVERE, "createHost: " + msg, e);
                e.printStackTrace();
                return Status.CANCEL_STATUS;
            }
        //				progressMonitor.subTask("");
        //				progressMonitor.worked(1);
        //				if (progressMonitor.isCanceled()) {
        //					if (displayWarningOnCreateHostCancelAction() == 0) {
        //						progressMonitor.done();
        //						return Status.CANCEL_STATUS;
        //					}
        //				}
        //
        //				for (int i = 0; i < 10; i++) {
        //					try {
        //						Thread.sleep(3000);
        //						progressMonitor.subTask("doing " + i);
        //						// Report that 10 units are done
        //						progressMonitor.worked(10);
        //					} catch (InterruptedException e1) {
        //						e1.printStackTrace();
        //					}
        //				}
        }
    };
    createDockerHostJob.schedule();
//    	DefaultLoader.getIdeHelper().runInBackground(null, "Creating Docker virtual machine " + newHost.name + "...", false, true, "Creating Docker virtual machine " + newHost.name + "...", new Runnable() {
//            @Override
//            public void run() {
//                DefaultLoader.getIdeHelper().invokeLater(new Runnable() {
//                    @Override
//                    public void run() {
//                    	
//                    }
//                });
//            }
//        });
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Azure(com.microsoft.azure.management.Azure) DockerHost(com.microsoft.azure.docker.model.DockerHost) Job(org.eclipse.core.runtime.jobs.Job) AzureUIRefreshEvent(com.microsoft.azuretools.utils.AzureUIRefreshEvent) AzureDockerPreferredSettings(com.microsoft.azure.docker.model.AzureDockerPreferredSettings) Date(java.util.Date) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 27 with Job

use of org.eclipse.core.runtime.jobs.Job in project azure-tools-for-java by Microsoft.

the class BlobExplorerFileEditor method uploadFile.

private void uploadFile(final String path, final File selectedFile) {
    Job job = new Job("Uploading blob...") {

        @Override
        protected IStatus run(final IProgressMonitor monitor) {
            monitor.beginTask("Uploading blob...", IProgressMonitor.UNKNOWN);
            try {
                final BlobDirectory blobDirectory = directoryQueue.peekLast();
                final BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(selectedFile));
                monitor.subTask("0% uploaded");
                try {
                    final CallableSingleArg<Void, Long> callable = new CallableSingleArg<Void, Long>() {

                        @Override
                        public Void call(Long uploadedBytes) throws Exception {
                            double progress = ((double) uploadedBytes) / selectedFile.length();
                            monitor.worked((int) (100 * progress));
                            monitor.subTask(String.format("%s%% uploaded", (int) (progress * 100)));
                            return null;
                        }
                    };
                    try {
                        StorageClientSDKManager.getManager().uploadBlobFileContent(connectionString, blobContainer, path, bufferedInputStream, callable, 1024 * 1024, selectedFile.length());
                    } catch (AzureCmdException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            bufferedInputStream.close();
                        } catch (IOException ignored) {
                        }
                    }
                    if (monitor.isCanceled()) {
                        //                                future.cancel(true);
                        bufferedInputStream.close();
                        for (BlobItem blobItem : StorageClientSDKManager.getManager().getBlobItems(connectionString, blobDirectory)) {
                            if (blobItem instanceof BlobFile && blobItem.getPath().equals(path)) {
                                StorageClientSDKManager.getManager().deleteBlobFile(connectionString, (BlobFile) blobItem);
                            }
                        }
                    }
                    try {
                        directoryQueue.clear();
                        directoryQueue.addLast(StorageClientSDKManager.getManager().getRootDirectory(connectionString, blobContainer));
                        for (String pathDir : path.split("/")) {
                            for (BlobItem blobItem : StorageClientSDKManager.getManager().getBlobItems(connectionString, directoryQueue.getLast())) {
                                if (blobItem instanceof BlobDirectory && blobItem.getName().equals(pathDir)) {
                                    directoryQueue.addLast((BlobDirectory) blobItem);
                                }
                            }
                        }
                    } catch (AzureCmdException e) {
                        DefaultLoader.getUIHelper().showException("Error showing new blob", e, "Error showing new blob", false, true);
                    }
                    DefaultLoader.getIdeHelper().invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            fillGrid();
                        }
                    });
                } catch (Exception e) {
                    Throwable connectionFault = e.getCause();
                    Throwable realFault = null;
                    if (connectionFault != null) {
                        realFault = connectionFault.getCause();
                    }
                    monitor.setTaskName("Error uploading Blob");
                    String message = realFault == null ? null : realFault.getMessage();
                    if (connectionFault != null && message == null) {
                        message = "Error type " + connectionFault.getClass().getName();
                    }
                    monitor.subTask((connectionFault instanceof SocketTimeoutException) ? "Connection timed out" : message);
                }
            } catch (Exception e) {
                DefaultLoader.getUIHelper().showException("Error uploading Blob", e, "Error uploading Blob", false, true);
                return Status.CANCEL_STATUS;
            } finally {
                monitor.done();
            }
            return Status.OK_STATUS;
        }
    };
    job.schedule();
}
Also used : BlobDirectory(com.microsoft.tooling.msservices.model.storage.BlobDirectory) CallableSingleArg(com.microsoft.tooling.msservices.helpers.CallableSingleArg) BlobFile(com.microsoft.tooling.msservices.model.storage.BlobFile) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) PartInitException(org.eclipse.ui.PartInitException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) BlobItem(com.microsoft.tooling.msservices.model.storage.BlobItem) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) SocketTimeoutException(java.net.SocketTimeoutException) BufferedInputStream(java.io.BufferedInputStream) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) Job(org.eclipse.core.runtime.jobs.Job)

Example 28 with Job

use of org.eclipse.core.runtime.jobs.Job in project azure-tools-for-java by Microsoft.

the class BlobExplorerFileEditor method downloadSelectedFile.

private void downloadSelectedFile(final File targetFile, final boolean open) {
    final BlobFile fileSelection = getFileSelection();
    if (fileSelection != null) {
        Job job = new Job("Downloading blob...") {

            @Override
            protected IStatus run(final IProgressMonitor monitor) {
                monitor.beginTask("Downloading blob...", IProgressMonitor.UNKNOWN);
                try {
                    if (!targetFile.exists()) {
                        if (!targetFile.createNewFile()) {
                            throw new IOException("File not created");
                        }
                    }
                    final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(targetFile), 65536) {

                        private long runningCount = 0;

                        @Override
                        public synchronized void write(@NotNull byte[] bytes, int i, int i1) throws IOException {
                            super.write(bytes, i, i1);
                            runningCount += i1;
                            double progress = (double) runningCount / fileSelection.getSize();
                            monitor.worked((int) (100 * progress));
                            monitor.subTask(String.format("%s%% downloaded", (int) (progress * 100)));
                        }
                    };
                    try {
                        //                                public void run() {
                        try {
                            StorageClientSDKManager.getManager().downloadBlobFileContent(connectionString, fileSelection, bufferedOutputStream);
                            if (open && targetFile.exists()) {
                                try {
                                    final Process p;
                                    Runtime runtime = Runtime.getRuntime();
                                    p = runtime.exec(new String[] { "open", "-R", targetFile.getName() }, null, targetFile.getParentFile());
                                    InputStream errorStream = p.getErrorStream();
                                    String errResponse = new String(IOUtils.readFully(errorStream, -1, true));
                                    if (p.waitFor() != 0) {
                                        throw new Exception(errResponse);
                                    }
                                } catch (Exception e) {
                                    monitor.setTaskName("Error opening file");
                                    monitor.subTask(e.getMessage());
                                }
                            //                                            Desktop.getDesktop().open(targetFile);
                            }
                        } catch (AzureCmdException e) {
                            Throwable connectionFault = e.getCause().getCause();
                            monitor.setTaskName("Error downloading Blob");
                            monitor.subTask((connectionFault instanceof SocketTimeoutException) ? "Connection timed out" : connectionFault.getMessage());
                            return Status.CANCEL_STATUS;
                        }
                    } finally {
                        bufferedOutputStream.close();
                    }
                } catch (IOException e) {
                    DefaultLoader.getUIHelper().showException("Error downloading Blob", e, "Error downloading Blob", false, true);
                    return Status.CANCEL_STATUS;
                } finally {
                    monitor.done();
                }
                return Status.OK_STATUS;
            }
        };
        job.schedule();
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BlobFile(com.microsoft.tooling.msservices.model.storage.BlobFile) IOException(java.io.IOException) NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull) PartInitException(org.eclipse.ui.PartInitException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) SocketTimeoutException(java.net.SocketTimeoutException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) FileOutputStream(java.io.FileOutputStream) Job(org.eclipse.core.runtime.jobs.Job) BufferedOutputStream(java.io.BufferedOutputStream)

Example 29 with Job

use of org.eclipse.core.runtime.jobs.Job in project ow by vtst.

the class ClosureBuilder method buildAll.

/**
   * Force a build of all JavaScript projects in the workspace.
   */
public static void buildAll() {
    // Get the list of projects having the Closure nature
    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    final ArrayList<IBuildConfiguration> configs = new ArrayList<IBuildConfiguration>(projects.length);
    for (IProject project : projects) {
        try {
            if (project.hasNature(ClosureNature.NATURE_ID)) {
                configs.add(project.getActiveBuildConfig());
            }
        } catch (CoreException e) {
        // This happens if the project is not open
        }
    }
    // Build
    Job buildAll = new Job(OwJsClosurePlugin.getDefault().getMessages().getString("build_all")) {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                ResourcesPlugin.getWorkspace().build(configs.toArray(new IBuildConfiguration[0]), IncrementalProjectBuilder.FULL_BUILD, false, monitor);
                return Status.OK_STATUS;
            } catch (CoreException e) {
                return e.getStatus();
            }
        }
    };
    buildAll.schedule();
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) ArrayList(java.util.ArrayList) Job(org.eclipse.core.runtime.jobs.Job) IProject(org.eclipse.core.resources.IProject) IBuildConfiguration(org.eclipse.core.resources.IBuildConfiguration)

Example 30 with Job

use of org.eclipse.core.runtime.jobs.Job in project cubrid-manager by CUBRID.

the class StopServiceAction method doRun.

/**
	 * Perform do run
	 * 
	 * @param servers
	 */
public void doRun(CubridServer[] servers) {
    CubridNavigatorView view = CubridNavigatorView.getNavigatorView(CubridHostNavigatorView.ID);
    final TreeViewer viewer = view.getViewer();
    if (servers.length > 0) {
        CubridServer server = servers[0];
        if (isSupported(server)) {
            final JobFamily jobFamily = new JobFamily();
            final String serverName = server.getName();
            String dbName = JobFamily.ALL_DB;
            jobFamily.setServerName(serverName);
            jobFamily.setDbName(dbName);
            Job[] jobs = Job.getJobManager().find(jobFamily);
            if (jobs.length > 0) {
                CommonUITool.openWarningBox(Messages.bind(Messages.msgStopServiceWithJob, serverName));
                return;
            }
            TaskExecutor taskExcutor = new StopServiceExecutor(server, getShell(), viewer);
            ServerInfo serverInfo = server.getServerInfo();
            GetCubridConfParameterTask task = new GetCubridConfParameterTask(serverInfo);
            taskExcutor.addTask(task);
            new ExecTaskWithProgress(taskExcutor).exec();
        }
    }
//		for(CubridServer server : servers) {
//			final JobFamily jobFamily = new JobFamily();
//			final String serverName = server.getName();
//			String dbName = JobFamily.ALL_DB;
//			jobFamily.setServerName(serverName);
//			jobFamily.setDbName(dbName);
//			Job[] jobs = Job.getJobManager().find(jobFamily);
//			if (jobs.length > 0) {
//				CommonUITool.openWarningBox(Messages.bind(
//						Messages.msgStopServiceWithJob, serverName));
//				return;
//			}
//
//			TaskExecutor taskExcutor = new StopServiceExecutor(server, getShell(),
//					viewer);
//			ServerInfo serverInfo = server.getServerInfo();
//			GetCubridConfParameterTask task = new GetCubridConfParameterTask(
//					serverInfo);
//			taskExcutor.addTask(task);
//			new ExecTaskWithProgress(taskExcutor).exec();
//		}
}
Also used : CubridNavigatorView(com.cubrid.common.ui.common.navigator.CubridNavigatorView) TaskExecutor(com.cubrid.common.ui.spi.progress.TaskExecutor) TreeViewer(org.eclipse.jface.viewers.TreeViewer) ServerInfo(com.cubrid.cubridmanager.core.common.model.ServerInfo) ExecTaskWithProgress(com.cubrid.common.ui.spi.progress.ExecTaskWithProgress) JobFamily(com.cubrid.common.ui.spi.progress.JobFamily) GetCubridConfParameterTask(com.cubrid.cubridmanager.core.common.task.GetCubridConfParameterTask) CubridServer(com.cubrid.common.ui.spi.model.CubridServer) Job(org.eclipse.core.runtime.jobs.Job)

Aggregations

Job (org.eclipse.core.runtime.jobs.Job)177 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)134 IStatus (org.eclipse.core.runtime.IStatus)33 IOException (java.io.IOException)27 File (java.io.File)20 Status (org.eclipse.core.runtime.Status)20 IJobChangeEvent (org.eclipse.core.runtime.jobs.IJobChangeEvent)20 JobChangeAdapter (org.eclipse.core.runtime.jobs.JobChangeAdapter)20 CoreException (org.eclipse.core.runtime.CoreException)17 IDockerConnection (org.eclipse.linuxtools.docker.core.IDockerConnection)17 JobFamily (com.cubrid.common.ui.spi.progress.JobFamily)14 DockerException (org.eclipse.linuxtools.docker.core.DockerException)14 IFile (org.eclipse.core.resources.IFile)13 URL (java.net.URL)11 ArrayList (java.util.ArrayList)11 IPath (org.eclipse.core.runtime.IPath)10 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)9 IWorkbenchPart (org.eclipse.ui.IWorkbenchPart)9 DockerConnection (org.eclipse.linuxtools.internal.docker.core.DockerConnection)8 Display (org.eclipse.swt.widgets.Display)8