Search in sources :

Example 6 with AzureExecutionException

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

the class SpringCloudDependencyManager method getMavenCentralVersions.

private static List<String> getMavenCentralVersions(String groupId, String artifactId) throws IOException, DocumentException, AzureExecutionException {
    URLConnection conn = new URL(String.format("https://repo1.maven.org/maven2/%s/%s/maven-metadata.xml", StringUtils.replace(groupId, ".", "/"), artifactId)).openConnection();
    List<String> res = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
        String xml = IOUtils.toString(reader);
        Document doc = DocumentHelper.parseText(xml);
        List<Node> nodes = doc.selectNodes("//metadata/versioning/versions/version");
        for (Node node : nodes) {
            String version = node.getText();
            if (StringUtils.isNotEmpty(version)) {
                res.add(version);
            }
        }
    }
    if (res.isEmpty()) {
        throw new AzureExecutionException((String.format("Cannot get version from maven central for: %s:%s.", groupId, artifactId)));
    }
    return res;
}
Also used : InputStreamReader(java.io.InputStreamReader) AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) Node(org.dom4j.Node) BufferedReader(java.io.BufferedReader) Document(org.dom4j.Document) URLConnection(java.net.URLConnection) URL(java.net.URL)

Example 7 with AzureExecutionException

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

the class CreateFunctionAction method invokeDialog.

@Override
protected PsiElement[] invokeDialog(Project project, PsiDirectory psiDirectory) {
    final Operation operation = TelemetryManager.createOperation(TelemetryConstants.FUNCTION, TelemetryConstants.CREATE_FUNCTION_TRIGGER);
    try {
        operation.start();
        PsiPackage pkg = JavaDirectoryService.getInstance().getPackage(psiDirectory);
        // get existing package from current directory
        String hintPackageName = pkg == null ? "" : pkg.getQualifiedName();
        CreateFunctionForm form = new CreateFunctionForm(project, hintPackageName);
        List<PsiElement> psiElements = new ArrayList<>();
        if (form.showAndGet()) {
            final FunctionTemplate bindingTemplate;
            try {
                Map<String, String> parameters = form.getTemplateParameters();
                final String connectionName = parameters.get("connection");
                String triggerType = form.getTriggerType();
                String packageName = parameters.get("packageName");
                String className = parameters.get("className");
                PsiDirectory directory = ClassUtil.sourceRoot(psiDirectory);
                String newName = packageName.replace('.', '/');
                bindingTemplate = AzureFunctionsUtils.getFunctionTemplate(triggerType);
                operation.trackProperty(TelemetryConstants.TRIGGER_TYPE, triggerType);
                if (StringUtils.equalsIgnoreCase(triggerType, CreateFunctionForm.EVENT_HUB_TRIGGER)) {
                    if (StringUtils.isBlank(connectionName)) {
                        throw new AzureExecutionException(message("function.createFunction.error.connectionMissed"));
                    }
                    parameters.putIfAbsent("eventHubName", "myeventhub");
                    parameters.putIfAbsent("consumerGroup", "$Default");
                }
                final String functionClassContent = AzureFunctionsUtils.substituteParametersInTemplate(bindingTemplate, parameters);
                if (StringUtils.isNotEmpty(functionClassContent)) {
                    AzureTaskManager.getInstance().write(() -> {
                        CreateFileAction.MkDirs mkDirs = ApplicationManager.getApplication().runWriteAction((Computable<CreateFileAction.MkDirs>) () -> new CreateFileAction.MkDirs(newName + '/' + className, directory));
                        PsiFileFactory factory = PsiFileFactory.getInstance(project);
                        try {
                            mkDirs.directory.checkCreateFile(className + ".java");
                        } catch (final IncorrectOperationException e) {
                            final String dir = mkDirs.directory.getName();
                            final String error = String.format("failed to create function class[%s] in directory[%s]", className, dir);
                            throw new AzureToolkitRuntimeException(error, e);
                        }
                        CommandProcessor.getInstance().executeCommand(project, () -> {
                            PsiFile psiFile = factory.createFileFromText(className + ".java", JavaFileType.INSTANCE, functionClassContent);
                            psiElements.add(mkDirs.directory.add(psiFile));
                        }, null, null);
                        if (StringUtils.equalsIgnoreCase(triggerType, CreateFunctionForm.EVENT_HUB_TRIGGER)) {
                            try {
                                String connectionString = form.getEventHubNamespace() == null ? DEFAULT_EVENT_HUB_CONNECTION_STRING : getEventHubNamespaceConnectionString(form.getEventHubNamespace());
                                AzureFunctionsUtils.applyKeyValueToLocalSettingFile(new File(project.getBasePath(), "local.settings.json"), parameters.get("connection"), connectionString);
                            } catch (IOException e) {
                                EventUtil.logError(operation, ErrorType.systemError, e, null, null);
                                final String error = "failed to get connection string and save to local settings";
                                throw new AzureToolkitRuntimeException(error, e);
                            }
                        }
                    });
                }
            } catch (AzureExecutionException e) {
                AzureMessager.getMessager().error(e);
                EventUtil.logError(operation, ErrorType.systemError, e, null, null);
            }
        }
        if (!psiElements.isEmpty()) {
            FileEditorManager.getInstance(project).openFile(psiElements.get(0).getContainingFile().getVirtualFile(), false);
        }
        return psiElements.toArray(new PsiElement[0]);
    } finally {
        operation.complete();
    }
}
Also used : PsiFileFactory(com.intellij.psi.PsiFileFactory) ArrayList(java.util.ArrayList) PsiPackage(com.intellij.psi.PsiPackage) AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) IOException(java.io.IOException) FunctionTemplate(com.microsoft.azure.toolkit.lib.legacy.function.template.FunctionTemplate) PsiDirectory(com.intellij.psi.PsiDirectory) AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) CreateFunctionForm(com.microsoft.azure.toolkit.intellij.function.CreateFunctionForm) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PsiFile(com.intellij.psi.PsiFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) PsiElement(com.intellij.psi.PsiElement) CreateFileAction(com.intellij.ide.actions.CreateFileAction)

Example 8 with AzureExecutionException

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

the class FunctionRunState method prepareStagingFolder.

@AzureOperation(name = "function.prepare_staging_folder_detail", params = { "stagingFolder.getName()", "this.functionRunConfiguration.getFuncPath()" }, type = AzureOperation.Type.SERVICE)
private void prepareStagingFolder(File stagingFolder, RunProcessHandler processHandler, @NotNull final Operation operation) throws Exception {
    AzureTaskManager.getInstance().read(() -> {
        final Path hostJsonPath = FunctionUtils.getDefaultHostJson(project);
        final Path localSettingsJson = Paths.get(functionRunConfiguration.getLocalSettingsJsonPath());
        final PsiMethod[] methods = FunctionUtils.findFunctionsByAnnotation(functionRunConfiguration.getModule());
        final Path folder = stagingFolder.toPath();
        try {
            Map<String, FunctionConfiguration> configMap = FunctionUtils.prepareStagingFolder(folder, hostJsonPath, functionRunConfiguration.getModule(), methods);
            operation.trackProperty(TelemetryConstants.TRIGGER_TYPE, StringUtils.join(FunctionUtils.getFunctionBindingList(configMap), ","));
            final Map<String, String> appSettings = FunctionUtils.loadAppSettingsFromSecurityStorage(functionRunConfiguration.getAppSettingsKey());
            FunctionUtils.copyLocalSettingsToStagingFolder(folder, localSettingsJson, appSettings);
            final Set<BindingEnum> bindingClasses = getFunctionBindingEnums(configMap);
            if (isInstallingExtensionNeeded(bindingClasses, processHandler)) {
                installProcess = getRunFunctionCliExtensionInstallProcessBuilder(stagingFolder).start();
            }
        } catch (AzureExecutionException | IOException e) {
            final String error = String.format("failed prepare staging folder[%s]", folder);
            throw new AzureToolkitRuntimeException(error, e);
        }
    });
    if (installProcess != null) {
        readInputStreamByLines(installProcess.getErrorStream(), inputLine -> {
            if (processHandler.isProcessRunning()) {
                processHandler.println(inputLine, ProcessOutputTypes.STDERR);
            }
        });
        readInputStreamByLines(installProcess.getInputStream(), inputLine -> {
            if (processHandler.isProcessRunning()) {
                processHandler.setText(inputLine);
            }
        });
        int exitCode = installProcess.waitFor();
        if (exitCode != 0) {
            throw new AzureExecutionException(message("function.run.error.installFuncFailed"));
        }
    }
}
Also used : Path(java.nio.file.Path) BindingEnum(com.microsoft.azure.toolkit.lib.legacy.function.bindings.BindingEnum) PsiMethod(com.intellij.psi.PsiMethod) FunctionConfiguration(com.microsoft.azure.toolkit.lib.legacy.function.configurations.FunctionConfiguration) AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) IOException(java.io.IOException) AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) AzureOperation(com.microsoft.azure.toolkit.lib.common.operation.AzureOperation)

Example 9 with AzureExecutionException

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

the class SignInCommandHandler method ensureAzureSubsAvailable.

private static void ensureAzureSubsAvailable() throws AzureExecutionException {
    if (!AuthMethodManager.getInstance().isSignedIn()) {
        throw new AzureExecutionException(NEED_SIGN_IN);
    }
    IdentityAzureManager azureManager = IdentityAzureManager.getInstance();
    final List<Subscription> subscriptions = azureManager.getSubscriptions();
    if (CollectionUtils.isEmpty(subscriptions)) {
        throw new AzureExecutionException(NO_SUBSCRIPTION);
    }
    final List<Subscription> selectedSubscriptions = azureManager.getSelectedSubscriptions();
    if (CollectionUtils.isEmpty(selectedSubscriptions)) {
        throw new AzureExecutionException(MUST_SELECT_SUBSCRIPTION);
    }
}
Also used : IdentityAzureManager(com.microsoft.azuretools.sdkmanage.IdentityAzureManager) AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) Subscription(com.microsoft.azure.toolkit.lib.common.model.Subscription)

Aggregations

AzureExecutionException (com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException)9 AzureToolkitRuntimeException (com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException)3 IOException (java.io.IOException)3 PsiFile (com.intellij.psi.PsiFile)2 PsiMethod (com.intellij.psi.PsiMethod)2 AzureString (com.microsoft.azure.toolkit.lib.common.bundle.AzureString)2 Subscription (com.microsoft.azure.toolkit.lib.common.model.Subscription)2 AzureOperation (com.microsoft.azure.toolkit.lib.common.operation.AzureOperation)2 FunctionConfiguration (com.microsoft.azure.toolkit.lib.legacy.function.configurations.FunctionConfiguration)2 IdentityAzureManager (com.microsoft.azuretools.sdkmanage.IdentityAzureManager)2 File (java.io.File)2 Path (java.nio.file.Path)2 ArrayList (java.util.ArrayList)2 SettableFuture (com.google.common.util.concurrent.SettableFuture)1 CreateFileAction (com.intellij.ide.actions.CreateFileAction)1 ExternalSystemProjectTracker (com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTracker)1 ProjectNotificationAware (com.intellij.openapi.externalSystem.autoimport.ProjectNotificationAware)1 Module (com.intellij.openapi.module.Module)1 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)1 Project (com.intellij.openapi.project.Project)1