Search in sources :

Example 21 with AzureToolkitRuntimeException

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

the class FunctionUtils method getTempStagingFolder.

public static File getTempStagingFolder() {
    try {
        final Path path = Files.createTempDirectory(AZURE_FUNCTIONS);
        final File file = path.toFile();
        FileUtils.forceDeleteOnExit(file);
        return file;
    } catch (final IOException e) {
        throw new AzureToolkitRuntimeException("failed to get temp staging folder", e);
    }
}
Also used : Path(java.nio.file.Path) AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) IOException(java.io.IOException) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 22 with AzureToolkitRuntimeException

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

the class JarUtils method buildJarFileToStagingPath.

public static Path buildJarFileToStagingPath(String stagingFolder, Module module) throws IOException {
    final File stagingFolderFile = new File(stagingFolder);
    if (!stagingFolderFile.exists()) {
        stagingFolderFile.mkdirs();
    }
    final String moduleName = module.getName();
    final String path = CompilerPaths.getModuleOutputPath(module, false);
    final Path outputFile = Paths.get(stagingFolder, moduleName + ".jar");
    final JarArchiver jar = new JarArchiver();
    jar.setCompress(true);
    jar.setDestFile(outputFile.toFile());
    jar.addDirectory(new File(path));
    final Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().put(new Attributes.Name("Created-By"), "Azure Intellij Plugin");
    try {
        jar.addConfiguredManifest(manifest);
    } catch (ManifestException e) {
        throw new AzureToolkitRuntimeException("Cannot create manifest for function jar.", e);
    }
    jar.createArchive();
    return outputFile;
}
Also used : Path(java.nio.file.Path) Attributes(java.util.jar.Attributes) AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) Manifest(org.codehaus.plexus.archiver.jar.Manifest) ManifestException(org.codehaus.plexus.archiver.jar.ManifestException) File(java.io.File) JarArchiver(org.codehaus.plexus.archiver.jar.JarArchiver)

Example 23 with AzureToolkitRuntimeException

use of com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException 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 24 with AzureToolkitRuntimeException

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

the class FunctionRunState method validateFunctionRuntime.

@AzureOperation(name = "function.validate_runtime", params = { "this.functionRunConfiguration.getFuncPath()" }, type = AzureOperation.Type.TASK)
private void validateFunctionRuntime(RunProcessHandler processHandler) {
    try {
        final String funcPath = functionRunConfiguration.getFuncPath();
        if (StringUtils.isEmpty(funcPath)) {
            throw new AzureToolkitRuntimeException(message("function.run.error.runtimeNotFound"));
        }
        final ComparableVersion funcVersion = getFuncVersion();
        if (funcVersion == null) {
            throw new AzureToolkitRuntimeException(message("function.run.error.runtimeNotFound"));
        }
        final ComparableVersion javaVersion = getJavaVersion();
        if (javaVersion == null) {
            processHandler.setText(message("function.run.error.getJavaVersionFailed"));
            return;
        }
        if (javaVersion.compareTo(JAVA_9) < 0) {
            // No need validate function host version within java 8 or earlier
            return;
        }
        final ComparableVersion minimumVersion = funcVersion.compareTo(FUNC_3) >= 0 ? MINIMUM_JAVA_9_SUPPORTED_VERSION : MINIMUM_JAVA_9_SUPPORTED_VERSION_V2;
        if (funcVersion.compareTo(minimumVersion) < 0) {
            throw new AzureToolkitRuntimeException(message("function.run.error.funcOutOfDate"));
        }
    } catch (IOException e) {
        throw new AzureToolkitRuntimeException(message("function.run.error.validateRuntimeFailed", e.getMessage()));
    }
}
Also used : AzureToolkitRuntimeException(com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException) IOException(java.io.IOException) ComparableVersion(org.apache.maven.artifact.versioning.ComparableVersion) AzureOperation(com.microsoft.azure.toolkit.lib.common.operation.AzureOperation)

Example 25 with AzureToolkitRuntimeException

use of com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException 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)

Aggregations

AzureToolkitRuntimeException (com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException)29 AzureOperation (com.microsoft.azure.toolkit.lib.common.operation.AzureOperation)13 IOException (java.io.IOException)13 AzureString (com.microsoft.azure.toolkit.lib.common.bundle.AzureString)9 File (java.io.File)5 AzureExecutionException (com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException)4 AzureTask (com.microsoft.azure.toolkit.lib.common.task.AzureTask)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 HashMap (java.util.HashMap)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)3 Operation (com.microsoft.azuretools.telemetrywrapper.Operation)3 Path (java.nio.file.Path)3 PsiMethod (com.intellij.psi.PsiMethod)2 LightVirtualFile (com.intellij.testFramework.LightVirtualFile)2 MsalClientException (com.microsoft.aad.msal4j.MsalClientException)2 AuthorizationLevel (com.microsoft.azure.functions.annotation.AuthorizationLevel)2 AppServiceFile (com.microsoft.azure.toolkit.lib.appservice.model.AppServiceFile)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)1