public void DeepObject() { var translated = _translator.ToJson(new Dictionary <string, string> { { "Foo/Bar/Baz", "4711" } }); Assert.IsType <JsonElement>(translated); Assert.IsType <JsonElement>(translated.GetProperty("Foo")); Assert.IsType <JsonElement>(translated.GetProperty("Foo").GetProperty("Bar")); Assert.IsType <JsonElement>(translated.GetProperty("Foo").GetProperty("Bar").GetProperty("Baz")); Assert.Equal("4711", translated.GetProperty("Foo").GetProperty("Bar").GetProperty("Baz").ToString()); }
public async Task <IActionResult> GetStructureJson([FromRoute] string name, [FromRoute] int structureVersion) { if (string.IsNullOrWhiteSpace(name)) { return(BadRequest("no name provided")); } if (structureVersion <= 0) { return(BadRequest($"invalid version provided '{structureVersion}'")); } var identifier = new StructureIdentifier(name, structureVersion); try { var result = await _store.Structures.GetKeys(identifier, QueryRange.All); if (result.IsError) { return(ProviderError(result)); } var json = _translator.ToJson(result.Data); if (json.ValueKind == JsonValueKind.Null) { return(StatusCode(HttpStatusCode.InternalServerError, "failed to translate keys to json")); } return(Ok(json)); } catch (Exception e) { Logger.LogError(e, $"failed to retrieve structure of ({nameof(name)}: {name}, {nameof(structureVersion)}: {structureVersion})"); return(StatusCode(HttpStatusCode.InternalServerError, "failed to retrieve structure")); } }
public async Task <IActionResult> GetKeysAsJson([FromRoute] string category, [FromRoute] string name, [FromQuery] string filter, [FromQuery] string preferExactMatch, [FromQuery] string root, [FromQuery] long targetVersion = -1) { try { var identifier = new EnvironmentIdentifier(category, name); var result = await _store.Environments.GetKeys(new EnvironmentKeyQueryParameters { Environment = identifier, Filter = filter, PreferExactMatch = preferExactMatch, Range = QueryRange.All, RemoveRoot = root, TargetVersion = targetVersion }); if (result.IsError) { return(ProviderError(result)); } var json = _translator.ToJson(result.Data); return(Ok(json)); } catch (Exception e) { KnownMetrics.Exception.WithLabels(e.GetType().Name).Inc(); Logger.LogError(e, "failed to retrieve Environment-Keys (" + $"{nameof(category)}: {category}; " + $"{nameof(name)}: {name}; " + $"{nameof(filter)}: {filter}; " + $"{nameof(preferExactMatch)}: {preferExactMatch}; " + $"{nameof(root)}: {root}; " + $"{nameof(targetVersion)}: {targetVersion})"); return(StatusCode(HttpStatusCode.InternalServerError, "failed to retrieve environment as json")); } }
public IActionResult DictionaryToJson([FromBody] Dictionary <string, string> dictionary, [FromQuery] string separator = null) { try { if (dictionary is null) { return(BadRequest("no dictionary received")); } var result = _translator.ToJson(dictionary, separator ?? JsonTranslatorDefaultSettings.Separator); KnownMetrics.Conversion.WithLabels("Map => Json").Inc(); return(Ok(result)); } catch (Exception e) { KnownMetrics.Exception.WithLabels(e.GetType().Name).Inc(); Logger.LogError(e, "failed to translate dictionary to json"); return(StatusCode(HttpStatusCode.InternalServerError, e.ToString())); } }
public async Task <IActionResult> AppendConfiguration([FromBody] JsonElement json) { var givenKeys = _translator.ToDictionary(json); IDictionary <string, string> currentKeys; try { if (System.IO.File.Exists(ConfigFileLocation)) { using var file = System.IO.File.OpenText(ConfigFileLocation); var currentJson = JsonSerializer.Deserialize <JsonElement>( await file.ReadToEndAsync(), new JsonSerializerOptions { WriteIndented = true, Converters = { new JsonStringEnumConverter(), new JsonIsoDateConverter() } }); currentKeys = _translator.ToDictionary(currentJson); } else { currentKeys = new Dictionary <string, string>(); } } catch (IOException e) { Logger.LogWarning(e, $"IO-Error while reading file '{ConfigFileLocation}'"); return(StatusCode(HttpStatusCode.InternalServerError, "internal error while reading configuration from disk")); } catch (JsonException e) { Logger.LogWarning(e, $"could not deserialize configuration from '{ConfigFileLocation}'"); return(StatusCode(HttpStatusCode.InternalServerError, "deserialization error while reading configuration, try overwriting it")); } catch (Exception e) { Logger.LogWarning(e, $"dump configuration from '{ConfigFileLocation}'"); return(StatusCode(HttpStatusCode.InternalServerError, "unidentified error occured")); } var resultKeys = currentKeys; foreach (var(key, value) in givenKeys) { resultKeys[key] = value; } var resultJson = _translator.ToJson(resultKeys); try { // create directory-structure if it doesn't already exist var fileInfo = new FileInfo(ConfigFileLocation); if (!Directory.Exists(fileInfo.DirectoryName)) { Directory.CreateDirectory(fileInfo.DirectoryName); } await System.IO.File.WriteAllBytesAsync( ConfigFileLocation, JsonSerializer.SerializeToUtf8Bytes(resultJson, new JsonSerializerOptions { WriteIndented = true, Converters = { new JsonStringEnumConverter(), new JsonIsoDateConverter() } })); return(Ok()); } catch (IOException e) { Logger.LogWarning(e, $"IO-Error while writing file '{ConfigFileLocation}'"); return(StatusCode(HttpStatusCode.InternalServerError, "could not write configuration back to disk")); } }
public async Task <IActionResult> PreviewConfiguration([FromRoute] string environmentCategory, [FromRoute] string environmentName, [FromRoute] string structureName, [FromRoute] int structureVersion) { var envId = new EnvironmentIdentifier(environmentCategory, environmentName); var structId = new StructureIdentifier(structureName, structureVersion); var structureKeyResult = await _store.Structures.GetKeys(structId, QueryRange.All); if (structureKeyResult.IsError) { return(ProviderError(structureKeyResult)); } var structureVariableResult = await _store.Structures.GetVariables(structId, QueryRange.All); if (structureVariableResult.IsError) { return(ProviderError(structureVariableResult)); } var environmentResult = await _store.Environments.GetKeys(new EnvironmentKeyQueryParameters { Environment = envId, Range = QueryRange.All }); if (environmentResult.IsError) { return(ProviderError(environmentResult)); } var structureSnapshot = structureKeyResult.Data; var variableSnapshot = structureVariableResult.Data; var environmentSnapshot = environmentResult.Data; var environmentInfo = new EnvironmentCompilationInfo { Name = $"{envId.Category}/{envId.Name}", Keys = environmentSnapshot }; var structureInfo = new StructureCompilationInfo { Name = $"{structId.Name}/{structId.Version}", Keys = structureSnapshot, Variables = variableSnapshot }; try { var compiled = _compiler.Compile(environmentInfo, structureInfo, _parser); var json = _translator.ToJson(compiled.CompiledConfiguration); return(Ok(json)); } catch (Exception e) { KnownMetrics.Exception.WithLabels(e.GetType().Name).Inc(); Logger.LogError(e, "failed to add new environment at (" + $"{nameof(environmentCategory)}: {environmentCategory}; " + $"{nameof(environmentName)}: {environmentName}; " + $"{nameof(structureName)}: {structureName}; " + $"{nameof(structureVersion)}: {structureVersion})"); return(Ok(JsonDocument.Parse("{}").RootElement)); } }
/// <summary> /// Compile the configuration that this object represents - subsequent calls will skip recompilation /// </summary> /// <param name="store"></param> /// <param name="compiler"></param> /// <param name="parser"></param> /// <param name="translator"></param> /// <param name="logger">optional logger to pass during the compilation-phase</param> /// <param name="assumeLatestVersion"> /// set to true, to use latest available versions of Environment and Structure instead of <see cref="DomainObject.CurrentVersion" /> /// </param> /// <returns></returns> public async Task <IResult> Compile(IDomainObjectStore store, IConfigurationCompiler compiler, IConfigurationParser parser, IJsonTranslator translator, ILogger logger = null, bool assumeLatestVersion = false) { if (Built) { return(Result.Success()); } CheckCompileParameters(store, compiler, parser, translator); var compilationVersion = assumeLatestVersion ? long.MaxValue : CurrentVersion; logger?.LogDebug($"version used during compilation: {compilationVersion} ({nameof(assumeLatestVersion)}: {assumeLatestVersion})"); var envResult = await store.ReplayObject(new ConfigEnvironment(Identifier.Environment), Identifier.Environment.ToString(), compilationVersion); if (envResult.IsError) { return(envResult); } var structResult = await store.ReplayObject(new ConfigStructure(Identifier.Structure), Identifier.Structure.ToString(), compilationVersion); if (structResult.IsError) { return(structResult); } var environment = envResult.Data; var structure = structResult.Data; try { var compilationResult = compiler.Compile( new EnvironmentCompilationInfo { Name = $"{Identifier.Environment.Category}/{Identifier.Environment.Name}", Keys = environment.GetKeysAsDictionary() }, new StructureCompilationInfo { Name = $"{Identifier.Structure.Name}/{Identifier.Structure.Version}", Keys = structure.Keys, Variables = structure.Variables }, parser); Keys = compilationResult.CompiledConfiguration; Json = translator.ToJson(Keys).ToString(); UsedKeys = compilationResult.GetUsedKeys().ToList(); Built = true; return(Result.Success()); } catch (Exception e) { logger?.LogWarning(e, "failed to compile configuration, see exception for more details"); return(Result.Error($"failed to compile configuration: {e.Message}", ErrorCode.InvalidData)); } }