Search in sources :

Example 16 with AzureTask

use of com.microsoft.azure.toolkit.lib.common.task.AzureTask in project azure-tools-for-java by Microsoft.

the class BlobExplorerFileEditor method fillGrid.

public void fillGrid() {
    setUIState(true);
    final AzureString title = AzureOperationBundle.title("blob.list", blobContainer.getName());
    AzureTaskManager.getInstance().runInBackground(new AzureTask(project, title, false, () -> {
        final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
        try {
            progressIndicator.setIndeterminate(true);
            if (directoryQueue.peekLast() == null) {
                directoryQueue.addLast(StorageClientSDKManager.getManager().getRootDirectory(connectionString, blobContainer));
            }
            blobItems = StorageClientSDKManager.getManager().getBlobItems(connectionString, directoryQueue.peekLast());
            if (!queryTextField.getText().isEmpty()) {
                for (int i = blobItems.size() - 1; i >= 0; i--) {
                    BlobItem blobItem = blobItems.get(i);
                    if (blobItem instanceof BlobFile && !blobItem.getName().startsWith(queryTextField.getText())) {
                        blobItems.remove(i);
                    }
                }
            }
            AzureTaskManager.getInstance().runLater(() -> {
                pathLabel.setText(directoryQueue.peekLast().getPath());
                DefaultTableModel model = (DefaultTableModel) blobListTable.getModel();
                while (model.getRowCount() > 0) {
                    model.removeRow(0);
                }
                for (BlobItem blobItem : blobItems) {
                    if (blobItem instanceof BlobDirectory) {
                        model.addRow(new Object[] { UIHelperImpl.loadIcon("storagefolder.png"), blobItem.getName(), "", "", "", blobItem.getUri() });
                    } else {
                        BlobFile blobFile = (BlobFile) blobItem;
                        model.addRow(new String[] { "", blobFile.getName(), UIHelperImpl.readableFileSize(blobFile.getSize()), new SimpleDateFormat().format(blobFile.getLastModified().getTime()), blobFile.getContentType(), blobFile.getUri() });
                    }
                }
                setUIState(false);
                blobListTable.clearSelection();
            });
        } catch (AzureCmdException ex) {
            String msg = "An error occurred while attempting to query blob list." + "\n" + String.format(message("webappExpMsg"), ex.getMessage());
            PluginUtil.displayErrorDialogAndLog(message("errTtl"), msg, ex);
        }
    }));
}
Also used : BlobItem(com.microsoft.tooling.msservices.model.storage.BlobItem) BlobDirectory(com.microsoft.tooling.msservices.model.storage.BlobDirectory) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) BlobFile(com.microsoft.tooling.msservices.model.storage.BlobFile) DefaultTableModel(javax.swing.table.DefaultTableModel) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) AzureTask(com.microsoft.azure.toolkit.lib.common.task.AzureTask) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) SimpleDateFormat(java.text.SimpleDateFormat)

Example 17 with AzureTask

use of com.microsoft.azure.toolkit.lib.common.task.AzureTask in project azure-tools-for-java by Microsoft.

the class BlobExplorerFileEditor method uploadFile.

private void uploadFile(final String path, final File selectedFile) {
    final AzureString title = AzureOperationBundle.title("blob.upload", selectedFile, blobContainer.getName());
    AzureTaskManager.getInstance().runInBackground(new AzureTask(project, title, false, () -> {
        final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
        try {
            final BlobDirectory blobDirectory = directoryQueue.peekLast();
            final BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(selectedFile));
            progressIndicator.setIndeterminate(false);
            progressIndicator.setText("Uploading blob...");
            progressIndicator.setText2("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();
                        progressIndicator.setFraction(progress);
                        progressIndicator.setText2(String.format("%s%% uploaded", (int) (progress * 100)));
                        return null;
                    }
                };
                Future<Void> future = ApplicationManager.getApplication().executeOnPooledThread(new Callable<Void>() {

                    @Override
                    public Void call() throws AzureCmdException {
                        try {
                            StorageClientSDKManager.getManager().uploadBlobFileContent(connectionString, blobContainer, path, bufferedInputStream, callable, 1024 * 1024, selectedFile.length());
                        } finally {
                            try {
                                bufferedInputStream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        return null;
                    }
                });
                while (!future.isDone()) {
                    Thread.sleep(500);
                    progressIndicator.checkCanceled();
                    if (progressIndicator.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) {
                    String msg = "An error occurred while attempting to show new blob." + "\n" + String.format(message("webappExpMsg"), e.getMessage());
                    PluginUtil.displayErrorDialogAndLog(message("errTtl"), msg, e);
                }
                AzureTaskManager.getInstance().runLater(() -> fillGrid());
            } catch (Exception e) {
                Throwable connectionFault = e.getCause();
                Throwable realFault = null;
                if (connectionFault != null) {
                    realFault = connectionFault.getCause();
                }
                progressIndicator.setText("Error uploading Blob");
                String message = realFault == null ? null : realFault.getMessage();
                if (connectionFault != null && message == null) {
                    message = "Error type " + connectionFault.getClass().getName();
                }
                progressIndicator.setText2((connectionFault instanceof SocketTimeoutException) ? "Connection timed out" : message);
            }
        } catch (IOException e) {
            PluginUtil.displayErrorDialogAndLog(message("errTtl"), "An error occurred while attempting to upload Blob.", e);
        }
    }));
}
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) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) SocketTimeoutException(java.net.SocketTimeoutException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) Callable(java.util.concurrent.Callable) BlobItem(com.microsoft.tooling.msservices.model.storage.BlobItem) SocketTimeoutException(java.net.SocketTimeoutException) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) Future(java.util.concurrent.Future) AzureTask(com.microsoft.azure.toolkit.lib.common.task.AzureTask)

Example 18 with AzureTask

use of com.microsoft.azure.toolkit.lib.common.task.AzureTask in project azure-tools-for-java by Microsoft.

the class CreateFunctionAppAction method createFunctionApp.

@AzureOperation(name = "function.create_detail", params = { "config.getName()" }, type = AzureOperation.Type.ACTION)
private Single<IFunctionApp> createFunctionApp(final FunctionAppConfig config) {
    final AzureString title = title("function.create_detail", config.getName());
    final IntellijAzureMessager actionMessenger = new IntellijAzureMessager() {

        @Override
        public boolean show(IAzureMessage raw) {
            if (raw.getType() != IAzureMessage.Type.INFO) {
                return super.show(raw);
            }
            return false;
        }
    };
    final AzureTask<IFunctionApp> task = new AzureTask<>(null, title, false, () -> {
        final Operation operation = TelemetryManager.createOperation(TelemetryConstants.FUNCTION, TelemetryConstants.CREATE_FUNCTION_APP);
        operation.trackProperties(config.getTelemetryProperties());
        try {
            AzureMessager.getContext().setMessager(actionMessenger);
            final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
            indicator.setIndeterminate(true);
            return functionAppService.createFunctionApp(config);
        } finally {
            operation.trackProperties(AzureTelemetry.getActionContext().getProperties());
            operation.complete();
        }
    });
    return AzureTaskManager.getInstance().runInModalAsObservable(task).toSingle().doOnSuccess(app -> {
        AzureMessager.getMessager().success(message("function.create.success.message", app.name()), message("function.create.success.title"));
        this.refreshAzureExplorer(app);
    });
}
Also used : ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) IAzureMessage(com.microsoft.azure.toolkit.lib.common.messager.IAzureMessage) IntellijAzureMessager(com.microsoft.azure.toolkit.intellij.common.messager.IntellijAzureMessager) AzureOperation(com.microsoft.azure.toolkit.lib.common.operation.AzureOperation) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) IFunctionApp(com.microsoft.azure.toolkit.lib.appservice.service.IFunctionApp) AzureTask(com.microsoft.azure.toolkit.lib.common.task.AzureTask) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) AzureOperation(com.microsoft.azure.toolkit.lib.common.operation.AzureOperation)

Example 19 with AzureTask

use of com.microsoft.azure.toolkit.lib.common.task.AzureTask in project azure-tools-for-java by Microsoft.

the class AddDependencyAction method onActionPerformed.

@Override
public boolean onActionPerformed(@NotNull AnActionEvent event, @Nullable Operation operation) {
    final Module module = event.getData(LangDataKeys.MODULE);
    final Project project = module.getProject();
    final MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project);
    final MavenProject mavenProject = projectsManager.findProject(module);
    if (mavenProject == null) {
        PluginUtil.showErrorNotificationProject(project, "Error", String.format("Project '%s' is not a maven project.", project.getName()));
        return true;
    }
    final AzureString title = AzureOperationBundle.title("springcloud.update_dependency", project.getName());
    AzureTaskManager.getInstance().runInBackground(new AzureTask(project, title, true, () -> {
        ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
        progressIndicator.setText("Syncing maven project " + project.getName());
        final SettableFuture<Boolean> isDirty = SettableFuture.create();
        AzureTaskManager.getInstance().runAndWait(() -> {
            ProjectNotificationAware notificationAware = ProjectNotificationAware.getInstance(project);
            isDirty.set(notificationAware.isNotificationVisible());
            if (notificationAware.isNotificationVisible()) {
                ExternalSystemProjectTracker projectTracker = ExternalSystemProjectTracker.getInstance(project);
                projectTracker.scheduleProjectRefresh();
            }
        });
        try {
            if (isDirty.get().booleanValue()) {
                projectsManager.forceUpdateProjects(Collections.singletonList(mavenProject)).get();
            }
        } catch (InterruptedException | ExecutionException e) {
            PluginUtil.showErrorNotification("Error", "Failed to update project due to error: " + e.getMessage());
            return;
        }
        try {
            progressIndicator.setText("Check existing dependencies");
            final String evaluateEffectivePom = MavenUtils.evaluateEffectivePom(project, mavenProject);
            ProgressManager.checkCanceled();
            if (StringUtils.isEmpty(evaluateEffectivePom)) {
                PluginUtil.showErrorNotificationProject(project, "Error", "Failed to evaluate effective pom.");
                return;
            }
            final String springBootVer = getMavenLibraryVersion(mavenProject, SPRING_BOOT_GROUP_ID, "spring-boot-autoconfigure");
            if (StringUtils.isEmpty(springBootVer)) {
                throw new AzureExecutionException(String.format("Module %s is not a spring-boot application.", module.getName()));
            }
            progressIndicator.setText("Get latest versions ...");
            SpringCloudDependencyManager dependencyManager = new SpringCloudDependencyManager(evaluateEffectivePom);
            Map<String, DependencyArtifact> versionMaps = dependencyManager.getDependencyVersions();
            Map<String, DependencyArtifact> managerDependencyVersionsMaps = dependencyManager.getDependencyManagementVersions();
            // given the spring-cloud-commons is greater or equal to 2.2.5.RELEASE, we should not add spring-cloud-starter-azure-spring-cloud-client
            // because the code is already merged into spring repo: https://github.com/spring-cloud/spring-cloud-commons/pull/803
            boolean noAzureSpringCloudClientDependency = shouldNotAddAzureSpringCloudClientDependency(versionMaps) || shouldNotAddAzureSpringCloudClientDependency(managerDependencyVersionsMaps);
            ProgressManager.checkCanceled();
            final List<DependencyArtifact> versionChanges = calculateVersionChanges(springBootVer, noAzureSpringCloudClientDependency, versionMaps);
            if (versionChanges.isEmpty()) {
                PluginUtil.showInfoNotificationProject(project, "Your project is update-to-date.", "No updates are needed.");
                return;
            }
            progressIndicator.setText("Applying versions ...");
            final File pomFile = new File(mavenProject.getFile().getCanonicalPath());
            ProgressManager.checkCanceled();
            if (applyVersionChanges(dependencyManager, pomFile, springBootVer, managerDependencyVersionsMaps, versionChanges)) {
                noticeUserVersionChanges(project, pomFile, versionChanges);
            } else {
                PluginUtil.showInfoNotificationProject(project, "Your project is update-to-date.", "No updates are needed.");
            }
        } catch (DocumentException | IOException | AzureExecutionException | MavenProcessCanceledException e) {
            PluginUtil.showErrorNotification("Error", "Failed to update Azure Spring Cloud dependencies due to error: " + e.getMessage());
        }
    }));
    return false;
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) MavenProjectsManager(org.jetbrains.idea.maven.project.MavenProjectsManager) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) Project(com.intellij.openapi.project.Project) MavenProject(org.jetbrains.idea.maven.project.MavenProject) ProjectNotificationAware(com.intellij.openapi.externalSystem.autoimport.ProjectNotificationAware) MavenProject(org.jetbrains.idea.maven.project.MavenProject) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) ExternalSystemProjectTracker(com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTracker) ArrayList(java.util.ArrayList) List(java.util.List) Module(com.intellij.openapi.module.Module) AzureTask(com.microsoft.azure.toolkit.lib.common.task.AzureTask) Map(java.util.Map) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File)

Example 20 with AzureTask

use of com.microsoft.azure.toolkit.lib.common.task.AzureTask in project azure-tools-for-java by Microsoft.

the class NodeActionListenerAsync method actionPerformedAsync.

/**
 * Async action.
 *
 * @param actionEvent event object.
 * @return ListenableFuture object.
 */
public ListenableFuture<Void> actionPerformedAsync(final NodeActionEvent actionEvent) {
    Callable<Boolean> booleanCallable = beforeAsyncActionPerformed();
    boolean shouldRun = true;
    try {
        shouldRun = booleanCallable.call();
    } catch (Exception ignored) {
    // ignore
    }
    final SettableFuture<Void> future = SettableFuture.create();
    if (shouldRun) {
        final Object project = actionEvent.getAction().getNode().getProject();
        AzureTaskManager.getInstance().runInBackground(new AzureTask(project, progressMessage, false, () -> {
            try {
                actionPerformed(actionEvent);
                future.set(null);
            } catch (AzureCmdException e) {
                future.setException(e);
            }
        }));
    } else {
        future.set(null);
    }
    return future;
}
Also used : AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) AzureTask(com.microsoft.azure.toolkit.lib.common.task.AzureTask) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException)

Aggregations

AzureTask (com.microsoft.azure.toolkit.lib.common.task.AzureTask)38 AzureString (com.microsoft.azure.toolkit.lib.common.bundle.AzureString)36 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)22 Project (com.intellij.openapi.project.Project)7 AzureCmdException (com.microsoft.azuretools.azurecommons.helpers.AzureCmdException)6 VirtualFile (com.intellij.openapi.vfs.VirtualFile)5 AzureOperationBundle (com.microsoft.azure.toolkit.lib.common.operation.AzureOperationBundle)5 AzureTaskManager (com.microsoft.azure.toolkit.lib.common.task.AzureTaskManager)5 AzureOperation (com.microsoft.azure.toolkit.lib.common.operation.AzureOperation)4 EventUtil (com.microsoft.azuretools.telemetrywrapper.EventUtil)4 BlobFile (com.microsoft.tooling.msservices.model.storage.BlobFile)4 MessageType (com.intellij.openapi.ui.MessageType)3 LightVirtualFile (com.intellij.testFramework.LightVirtualFile)3 AzureAccount (com.microsoft.azure.toolkit.lib.auth.AzureAccount)3 File (java.io.File)3 List (java.util.List)3 javax.swing (javax.swing)3 FileChooserDescriptorFactory (com.intellij.openapi.fileChooser.FileChooserDescriptorFactory)2 FileEditorManager (com.intellij.openapi.fileEditor.FileEditorManager)2 ProgressManager (com.intellij.openapi.progress.ProgressManager)2