diff --git a/.editorconfig b/.editorconfig index 5f097782..556e8335 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,23 +1,451 @@ -# EditorConfig is awesome: https://EditorConfig.org +# EditorConfig is awesome:http://EditorConfig.org # top-most EditorConfig file root = true +# Don't use tabs for indentation. [*] indent_style = space +# (Please don't specify an indent_size here; that has too many unintended consequences.) + +# Code files +[*.{cs,csx,vb,vbx}] +indent_size = 4 +insert_final_newline = true +charset = utf-8-bom + +[*.xaml] indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = false -insert_final_newline = false +[*.ps1] +indent_size = 2 + +# Xml project files +[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] +indent_size = 2 + +# Xml config files +[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] +indent_size = 2 + +# JSON files +[*.json] +indent_size = 2 + +[*.groovy] +indent_size = 2 + +# Dotnet code style settings: [*.{cs,vb}] -dotnet_naming_rule.private_members_with_underscore.symbols = private_fields -dotnet_naming_rule.private_members_with_underscore.style = prefix_underscore -dotnet_naming_rule.private_members_with_underscore.severity = suggestion - -dotnet_naming_symbols.private_fields.applicable_kinds = field -dotnet_naming_symbols.private_fields.applicable_accessibilities = private - -dotnet_naming_style.prefix_underscore.capitalization = camel_case -dotnet_naming_style.prefix_underscore.required_prefix = _ \ No newline at end of file +# Sort using and Import directives with System.* appearing first +dotnet_sort_system_directives_first = true +dotnet_style_require_accessibility_modifiers = always:warning + +# No blank line between System.* and Microsoft.* +dotnet_separate_import_directive_groups = false + +# Suggest more modern language features when available +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_coalesce_expression = true:error +dotnet_style_null_propagation = true:error +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = false +dotnet_style_prefer_conditional_expression_over_assignment = false +dotnet_style_prefer_auto_properties = false + +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:error +dotnet_style_qualification_for_property = false:error +dotnet_style_qualification_for_method = false:error +dotnet_style_qualification_for_event = false:error + +# Use language keywords instead of framework type names for type references +dotnet_style_predefined_type_for_locals_parameters_members = true:error +dotnet_style_predefined_type_for_member_access = true:error + +# Prefer read-only on fields +dotnet_style_readonly_field = true:warning + +# Naming Rules +dotnet_naming_rule.interfaces_must_be_pascal_cased_and_prefixed_with_I.symbols = interface_symbols +dotnet_naming_rule.interfaces_must_be_pascal_cased_and_prefixed_with_I.style = pascal_case_and_prefix_with_I_style +dotnet_naming_rule.interfaces_must_be_pascal_cased_and_prefixed_with_I.severity = warning + +dotnet_naming_rule.externally_visible_members_must_be_pascal_cased.symbols = externally_visible_symbols +dotnet_naming_rule.externally_visible_members_must_be_pascal_cased.style = pascal_case_style +dotnet_naming_rule.externally_visible_members_must_be_pascal_cased.severity = warning + +dotnet_naming_rule.parameters_must_be_camel_cased.symbols = parameter_symbols +dotnet_naming_rule.parameters_must_be_camel_cased.style = camel_case_style +dotnet_naming_rule.parameters_must_be_camel_cased.severity = warning + +dotnet_naming_rule.constants_must_be_pascal_cased.symbols = constant_symbols +dotnet_naming_rule.constants_must_be_pascal_cased.style = pascal_case_style +dotnet_naming_rule.constants_must_be_pascal_cased.severity = warning + +dotnet_naming_rule.private_static_fields_must_be_camel_cased_and_prefixed_with_s_underscore.symbols = private_static_field_symbols +dotnet_naming_rule.private_static_fields_must_be_camel_cased_and_prefixed_with_s_underscore.style = pascal_case_style +dotnet_naming_rule.private_static_fields_must_be_camel_cased_and_prefixed_with_s_underscore.severity = warning + +dotnet_naming_rule.private_instance_fields_must_be_camel_cased_and_prefixed_with_underscore.symbols = private_field_symbols +dotnet_naming_rule.private_instance_fields_must_be_camel_cased_and_prefixed_with_underscore.style = camel_case_and_prefix_with_underscore_style +dotnet_naming_rule.private_instance_fields_must_be_camel_cased_and_prefixed_with_underscore.severity = warning + +# Symbols +dotnet_naming_symbols.externally_visible_symbols.applicable_kinds = class,struct,interface,enum,property,method,field,event,delegate +dotnet_naming_symbols.externally_visible_symbols.applicable_accessibilities = public,internal,friend,protected,protected_internal,protected_friend,private_protected + +dotnet_naming_symbols.interface_symbols.applicable_kinds = interface +dotnet_naming_symbols.interface_symbols.applicable_accessibilities = * + +dotnet_naming_symbols.parameter_symbols.applicable_kinds = parameter +dotnet_naming_symbols.parameter_symbols.applicable_accessibilities = * + +dotnet_naming_symbols.constant_symbols.applicable_kinds = field +dotnet_naming_symbols.constant_symbols.required_modifiers = const +dotnet_naming_symbols.constant_symbols.applicable_accessibilities = * + +dotnet_naming_symbols.private_static_field_symbols.applicable_kinds = field +dotnet_naming_symbols.private_static_field_symbols.required_modifiers = static,shared +dotnet_naming_symbols.private_static_field_symbols.applicable_accessibilities = private + +dotnet_naming_symbols.private_field_symbols.applicable_kinds = field +dotnet_naming_symbols.private_field_symbols.applicable_accessibilities = private + +# Styles +dotnet_naming_style.camel_case_style.capitalization = camel_case + +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +dotnet_naming_style.camel_case_and_prefix_with_s_underscore_style.required_prefix = s_ +dotnet_naming_style.camel_case_and_prefix_with_s_underscore_style.capitalization = camel_case + +dotnet_naming_style.camel_case_and_prefix_with_underscore_style.required_prefix = _ +dotnet_naming_style.camel_case_and_prefix_with_underscore_style.capitalization = camel_case + +dotnet_naming_style.pascal_case_and_prefix_with_I_style.required_prefix = I +dotnet_naming_style.pascal_case_and_prefix_with_I_style.capitalization = pascal_case + +# CSharp code style settings: +[*.cs] + +# Prefer "var" only when the type is apparent +csharp_style_var_for_built_in_types = false:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = false:suggestion + +# Prefer method-like constructs to have a block body +csharp_style_expression_bodied_methods = false:none +csharp_style_expression_bodied_constructors = false:none +csharp_style_expression_bodied_operators = false:none + +# Prefer property-like constructs to have an expression-body +csharp_style_expression_bodied_properties = true:none +csharp_style_expression_bodied_indexers = true:none +csharp_style_expression_bodied_accessors = true:none + +# Use block body for local functions +csharp_style_expression_bodied_local_functions = when_on_single_line:silent + +# Suggest more modern language features when available +csharp_style_pattern_matching_over_is_with_cast_check = true:error +csharp_style_pattern_matching_over_as_with_null_check = true:error +csharp_style_inlined_variable_declaration = true:error +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion + +# Newline settings +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Identation options +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = no_change +csharp_indent_block_contents = true +csharp_indent_braces = false + +# Spacing options +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false +csharp_space_between_empty_square_brackets = false +csharp_space_before_open_square_brackets = false +csharp_space_around_declaration_statements = false +csharp_space_around_binary_operators = before_and_after +csharp_space_after_cast = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_before_dot = false +csharp_space_after_dot = false +csharp_space_before_comma = false +csharp_space_after_comma = true +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_semicolon_in_for_statement = true + +# Wrapping +csharp_preserve_single_line_statements = true +csharp_preserve_single_line_blocks = true + +# Code block +csharp_prefer_braces = false:none + +# Using statements +csharp_using_directive_placement = outside_namespace:error + +# Modifier settings +csharp_prefer_static_local_function = true:warning +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:warning + +# Dotnet code analysis settings: +[*.{cs,vb}] + +# Microsoft.Analyzers.ManagedCodeAnalysis +dotnet_diagnostic.CA1801.severity = none +dotnet_diagnostic.CA1804.severity = none +dotnet_diagnostic.CA1806.severity = none +dotnet_diagnostic.CA1821.severity = none +dotnet_diagnostic.CA1823.severity = none +dotnet_diagnostic.CA1824.severity = none +dotnet_diagnostic.CA2200.severity = none + +# Microsoft.NetCore.Analyzers +dotnet_diagnostic.CA2000.severity = none # Dispose objects before losing scope (Noisy - replaced with IDE0067, IDE0068, IDE0069) +dotnet_diagnostic.CA1820.severity = warning +dotnet_diagnostic.CA5360.severity = none # https://github.com/dotnet/roslyn-analyzers/issues/2683 + +# Microsoft.CodeQuality.Analyzers +dotnet_diagnostic.CA1000.severity = none +dotnet_diagnostic.CA1001.severity = none +dotnet_diagnostic.CA1010.severity = none +dotnet_diagnostic.CA1016.severity = none +dotnet_diagnostic.CA1018.severity = none +dotnet_diagnostic.CA1028.severity = none +dotnet_diagnostic.CA1030.severity = none +dotnet_diagnostic.CA1032.severity = none +dotnet_diagnostic.CA1033.severity = none # Interface methods should be callable by child types +dotnet_diagnostic.CA1034.severity = none +dotnet_diagnostic.CA1036.severity = warning # Override methods on comparable types +dotnet_diagnostic.CA1040.severity = none +dotnet_diagnostic.CA1041.severity = none +dotnet_diagnostic.CA1043.severity = none +dotnet_diagnostic.CA1051.severity = none +dotnet_diagnostic.CA1052.severity = none +dotnet_diagnostic.CA1054.severity = none +dotnet_diagnostic.CA1055.severity = none +dotnet_diagnostic.CA1056.severity = none +dotnet_diagnostic.CA1060.severity = none # Move P/Invokes to NativeMethods class +dotnet_diagnostic.CA1062.severity = none +dotnet_diagnostic.CA1063.severity = warning +dotnet_diagnostic.CA1064.severity = none +dotnet_diagnostic.CA1065.severity = none +dotnet_diagnostic.CA1066.severity = none +dotnet_diagnostic.CA1067.severity = warning +dotnet_diagnostic.CA1068.severity = warning +dotnet_diagnostic.CA1031.severity = none # Do not catch general exception types +dotnet_diagnostic.CA1303.severity = none +dotnet_diagnostic.CA1304.severity = none +dotnet_diagnostic.CA1707.severity = none +dotnet_diagnostic.CA1710.severity = none +dotnet_diagnostic.CA1714.severity = none +dotnet_diagnostic.CA1715.severity = none +dotnet_diagnostic.CA1716.severity = none +dotnet_diagnostic.CA1717.severity = none +dotnet_diagnostic.CA1720.severity = none +dotnet_diagnostic.CA1721.severity = none +dotnet_diagnostic.CA1724.severity = none +dotnet_diagnostic.CA1815.severity = none +dotnet_diagnostic.CA2007.severity = none +dotnet_diagnostic.CA2211.severity = none +dotnet_diagnostic.CA2213.severity = none # https://github.com/dotnet/roslyn-analyzers/issues/1796 +dotnet_diagnostic.CA2218.severity = none +dotnet_diagnostic.CA2222.severity = none +dotnet_diagnostic.CA2224.severity = none +dotnet_diagnostic.CA2225.severity = none +dotnet_diagnostic.CA2227.severity = none +dotnet_diagnostic.CA2231.severity = none +dotnet_diagnostic.CA2234.severity = none + +# Microsoft.NetFramework.Analyzers +dotnet_diagnostic.CA2153.severity = warning # Do not catch CorruptedStateExceptions +dotnet_diagnostic.CA2235.severity = warning +dotnet_diagnostic.CA3075.severity = warning + +# Microsoft.CodeAnalysis.Analyzers +# These diagnostics apply to the source code of analyzers themselves. +# We do not have any analyzers in this repository, so disable these. +dotnet_diagnostic.RS1001.severity = none +dotnet_diagnostic.RS1002.severity = none +dotnet_diagnostic.RS1003.severity = none +dotnet_diagnostic.RS1004.severity = none +dotnet_diagnostic.RS1005.severity = none +dotnet_diagnostic.RS1006.severity = none +dotnet_diagnostic.RS1008.severity = none +dotnet_diagnostic.RS1009.severity = none +dotnet_diagnostic.RS1010.severity = none +dotnet_diagnostic.RS1011.severity = none +dotnet_diagnostic.RS1012.severity = none +dotnet_diagnostic.RS1013.severity = none +dotnet_diagnostic.RS1014.severity = warning # DoNotIgnoreReturnValueOnImmutableObjectMethodInvocation +dotnet_diagnostic.RS1015.severity = none +dotnet_diagnostic.RS1016.severity = none +dotnet_diagnostic.RS1017.severity = none +dotnet_diagnostic.RS1018.severity = none +dotnet_diagnostic.RS1019.severity = none +dotnet_diagnostic.RS1020.severity = none +dotnet_diagnostic.RS1021.severity = none +dotnet_diagnostic.RS1022.severity = none +dotnet_diagnostic.RS1023.severity = none + +# Microsoft.Composition.Analyzers +dotnet_diagnostic.RS0006.severity = error # Do not mixing MEF versions +dotnet_diagnostic.RS0023.severity = error # MEF2 components must be shared + +# Roslyn.Core +dotnet_diagnostic.AD0001.severity = warning # Analyzer exception + +# Roslyn.Diagnostic.Analyzers +dotnet_diagnostic.RS0001.severity = warning # Use 'SpecializedCollections.EmptyEnumerable()' +dotnet_diagnostic.RS0002.severity = warning # Use 'SpecializedCollections.SingletonEnumerable()' +dotnet_diagnostic.RS0005.severity = warning # Do not use generic 'CodeAction.Create' to create 'CodeAction' +dotnet_diagnostic.RS0016.severity = warning # Do not have undeclared API +dotnet_diagnostic.RS0017.severity = warning # API is declared but not public +dotnet_diagnostic.RS0022.severity = warning # Constructor make noninheritable base class inheritable +dotnet_diagnostic.RS0024.severity = warning # The contents of the public API files are invalid: +dotnet_diagnostic.RS0025.severity = warning # Do not duplicate symbols in public API files +dotnet_diagnostic.RS0026.severity = warning # Do not add multiple public overloads with optional parameters +dotnet_diagnostic.RS0027.severity = warning # Public API with optional parameter(s) should have the most parameters amongst its public overloads. +dotnet_diagnostic.RS0030.severity = warning # Do not use banned APIs +dotnet_diagnostic.RS0031.severity = warning # The list of banned symbols contains a duplicate +dotnet_diagnostic.RS0033.severity = none # Importing constructor should be [Obsolete] +dotnet_diagnostic.RS0034.severity = none # Style rule that enforces public MEF constructor marked with [ImportingConstructor] + +# System.Collections.Immutable.Analyzers +dotnet_diagnostic.RS0012.severity = warning + +# System.Runtime.Analyzers +dotnet_diagnostic.CA1305.severity = none +dotnet_diagnostic.CA1307.severity = none +dotnet_diagnostic.CA1308.severity = none +dotnet_diagnostic.CA1810.severity = none +dotnet_diagnostic.CA1816.severity = none +dotnet_diagnostic.CA1825.severity = warning +dotnet_diagnostic.CA2002.severity = none +dotnet_diagnostic.CA2207.severity = none +dotnet_diagnostic.CA2208.severity = none +dotnet_diagnostic.CA2216.severity = none +dotnet_diagnostic.CA2219.severity = none +dotnet_diagnostic.CA2241.severity = none +dotnet_diagnostic.CA2242.severity = none +dotnet_diagnostic.RS0014.severity = warning + +# System.Runtime.InteropServices.Analyzers +dotnet_diagnostic.CA1401.severity = none +dotnet_diagnostic.CA2101.severity = none +dotnet_diagnostic.RS0015.severity = warning + +# System.Threading.Tasks.Analyzers +dotnet_diagnostic.RS0018.severity = warning + +# XmlDocumentationComments.Analyzers +dotnet_diagnostic.RS0010.severity = warning + +# Microsoft.CodeAnalysis.CSharp.Features +# Prefix local calls with this + # Name: Before: After: +dotnet_diagnostic.IDE0001.severity = warning # Simplify names System.Version version; Version version; +dotnet_diagnostic.IDE0002.severity = warning # Simplify (member access) System.Version.Equals("1", "2"); Version.Equals("1", "2"); +dotnet_diagnostic.IDE0005.severity = warning # Using directive is unnecessary using System.Text; +dotnet_diagnostic.IDE0030.severity = warning # Use coalesce expression (nullable) int? y = x.HasValue ? x.Value : 0 int? y = x ?? 0; +dotnet_diagnostic.IDE0030WithoutSuggestion.severity = error +dotnet_diagnostic.IDE0038.severity = warning # Use pattern matching if (x is string) if (x is string s) +dotnet_diagnostic.IDE0079.severity = warning # Unused suppresion +dotnet_diagnostic.IDE0083.severity = warning # Use pattern matching +dotnet_diagnostic.IDE0084.severity = warning # Use IsNot +dotnet_diagnostic.IDE0090.severity = warning # Use new(...) +dotnet_diagnostic.IDE1006.severity = warning # Naming styles Task Open() Task OpenAsync() +dotnet_diagnostic.IDE1006WithoutSuggestion.severity = suggestion + + +# Microsoft.VisualStudio.Threading.Analyzers +dotnet_diagnostic.VSTHRD200.severity = error # Naming styles Task Open() Task OpenAsync() +dotnet_diagnostic.VSTHRD010.severity = none # Visual Studio service should be used on main thread explicitly. +dotnet_diagnostic.VSTHRD103.severity = none # Call async methods when in an async method. +dotnet_diagnostic.VSTHRD108.severity = none # Thread affinity checks should be unconditional. +dotnet_diagnostic.VSTHRD003.severity = none # Avoid awaiting or returning a Task representing work that was not started within your context as that can lead to deadlocks +dotnet_diagnostic.VSTHRD111.severity = none # Use ConfigureAwait(true). + +# Microsoft.VisualStudio.SDK.Analyzers +dotnet_diagnostic.VSSDK006.severity = none # Check whether the result of GetService calls is null + +# Microsoft.CodeAnalysis.VisualBasic.CodeStyle/Microsoft.CodeAnalysis.CSharp.CodeStyle +dotnet_diagnostic.IDE0073.severity = warning # Enforce file header + +file_header_template = Copyright (c) by Terradue Srl. All Rights Reserved.\nLicense under the AGPL, Version 3.0.\nFile Name: {fileName} + +# Microsoft.CodeAnalysis.CSharp.CodeStyle +dotnet_diagnostic.SA1005.severity = warning # Single line comments should begin with single space +dotnet_diagnostic.SA1028.severity = warning # Code should not contain trailing whitespace +dotnet_diagnostic.SA1101.severity = warning # Prefix local calls with this +dotnet_diagnostic.SA1107.severity = warning # Code should not contain multiple statements on one line +dotnet_diagnostic.SA1111.severity = warning # Closing parenthesis should be on line of last parameter +dotnet_diagnostic.SA1115.severity = warning # Parameter should follow comma +dotnet_diagnostic.SA1116.severity = warning # Split parameters should start on line after declaration +dotnet_diagnostic.SA1119.severity = warning # Statement must not use unnecessary parenthesis +dotnet_diagnostic.SA1122.severity = warning # Use string.Empty for empty strings +dotnet_diagnostic.SA1124.severity = warning # Do not use regions +dotnet_diagnostic.SA1127.severity = warning # Generic type constraints must be on their own line or share line with previous +dotnet_diagnostic.SA1128.severity = warning # Put constructor initializers on their own line +dotnet_diagnostic.SA1129.severity = warning # Do not use default value type constructor +dotnet_diagnostic.SA1132.severity = warning # Do not combine fields +dotnet_diagnostic.SA1137.severity = warning # Elements should have the same indentation +dotnet_diagnostic.SA1201.severity = warning # Elements must appear in the correct order +dotnet_diagnostic.SA1202.severity = warning # Elements must be ordered by access +dotnet_diagnostic.SA1204.severity = warning # Static elements must appear before instance elements +dotnet_diagnostic.SA1214.severity = warning # Readonly fields must appear before non-readonly fields +dotnet_diagnostic.SA1306.severity = none # Field names must begin with lower-case letter +dotnet_diagnostic.SA1311.severity = warning # Static readonly fields must begin with upper-case letter +dotnet_diagnostic.SA1407.severity = warning # Arithmetic expressions must declare precedence +dotnet_diagnostic.SA1412.severity = warning # Store files as UTF-8 with byte order mark +dotnet_diagnostic.SA1413.severity = warning # Use trailing comma in multi-line initializers +dotnet_diagnostic.SA1500.severity = warning # Braces for multi-line statements must not share line +dotnet_diagnostic.SA1501.severity = warning # Braces must not be omitted +dotnet_diagnostic.SA1503.severity = warning # Braces must not be omitted +dotnet_diagnostic.SA1504.severity = warning # All accessors must be single-line or multi-line +dotnet_diagnostic.SA1505.severity = warning # An opening brace must not be followed by a blank line +dotnet_diagnostic.SA1506.severity = warning # Element documentation header must not be preceded by blank line +dotnet_diagnostic.SA1507.severity = warning # Code should not contain multiple blank lines in a row +dotnet_diagnostic.SA1508.severity = warning # A closing brace must not be preceded by a blank line +dotnet_diagnostic.SA1513.severity = warning # Closing brace must be followed by blank line +dotnet_diagnostic.SA1514.severity = warning # Element documentation header must be preceded by blank line +dotnet_diagnostic.SA1515.severity = warning # Single-line comment must be preceded by blank line +dotnet_diagnostic.SA1516.severity = warning # Elements must be separated by blank line +dotnet_diagnostic.SA1518.severity = warning # Code should end with a newline +dotnet_diagnostic.SA1519.severity = warning # Braces should not be omitted from multi-line child statement +dotnet_diagnostic.SA1520.severity = warning # Use braces consistently +dotnet_diagnostic.SA1623.severity = warning # Property summary documentation must match accessors +dotnet_diagnostic.SA1626.severity = warning # Single-line comments must not use documentation style slashes +dotnet_diagnostic.SA1636.severity = none # Disable file header matching +dotnet_diagnostic.SA1642.severity = warning # Constructor summary documentation must begin with standard text +dotnet_diagnostic.SA1649.severity = warning # File name must match first type name +dotnet_diagnostic.SA1651.severity = warning # Do not use placeholders in summaries +dotnet_diagnostic.SX1309.severity = warning # Field names should begin with underscore \ No newline at end of file diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index bbb13d4e..029684bc 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -42,3 +42,7 @@ jobs: path: TestResults # Use always() to always run this step to publish test results when there are test failures if: ${{ always() }} + - name: Install dotnet format + run: dotnet tool update -g dotnet-format + - name: Check Format + run: dotnet format --verify-no-changes --severity error src/ diff --git a/src/Stars.Console.Tests/BaseCommandLineTests.cs b/src/Stars.Console.Tests/BaseCommandLineTests.cs index 6ba12ae5..ebd5dd57 100644 --- a/src/Stars.Console.Tests/BaseCommandLineTests.cs +++ b/src/Stars.Console.Tests/BaseCommandLineTests.cs @@ -1,6 +1,4 @@ -using System; -using McMaster.Extensions.CommandLineUtils; -using Terradue.Stars.Console; +using Terradue.Stars.Console; using Xunit; using Xunit.Abstractions; diff --git a/src/Stars.Console.Tests/Utilities/CommandLineParser.cs b/src/Stars.Console.Tests/Utilities/CommandLineParser.cs index 34ee7682..c173f4a8 100644 --- a/src/Stars.Console.Tests/Utilities/CommandLineParser.cs +++ b/src/Stars.Console.Tests/Utilities/CommandLineParser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Nate McMaster. +// Copyright (c) Nate McMaster. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; @@ -27,4 +27,4 @@ private static T ParseArgsImpl(IConsole console, string[] args) where T : cla return app.Model; } } -} \ No newline at end of file +} diff --git a/src/Stars.Console.Tests/Utilities/ConventionTestBase.cs b/src/Stars.Console.Tests/Utilities/ConventionTestBase.cs index ffd7ce8b..ce87bd57 100644 --- a/src/Stars.Console.Tests/Utilities/ConventionTestBase.cs +++ b/src/Stars.Console.Tests/Utilities/ConventionTestBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Nate McMaster. +// Copyright (c) Nate McMaster. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using McMaster.Extensions.CommandLineUtils; @@ -25,4 +25,4 @@ protected CommandLineApplication Create() return app; } } -} \ No newline at end of file +} diff --git a/src/Stars.Console.Tests/Utilities/TestConsole.cs b/src/Stars.Console.Tests/Utilities/TestConsole.cs index d145011f..ceb7a82d 100644 --- a/src/Stars.Console.Tests/Utilities/TestConsole.cs +++ b/src/Stars.Console.Tests/Utilities/TestConsole.cs @@ -1,9 +1,9 @@ -using System; +using System; using System.IO; using System.Linq; using System.Reflection; -using Xunit.Abstractions; using McMaster.Extensions.CommandLineUtils; +using Xunit.Abstractions; using Xunit.Sdk; namespace Stars.Console.Tests diff --git a/src/Stars.Console.Tests/Utilities/XunitTextWriter.cs b/src/Stars.Console.Tests/Utilities/XunitTextWriter.cs index 6bb4970b..d2308658 100644 --- a/src/Stars.Console.Tests/Utilities/XunitTextWriter.cs +++ b/src/Stars.Console.Tests/Utilities/XunitTextWriter.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Text; using Xunit.Abstractions; diff --git a/src/Stars.Console/ConsoleCredentialsManager.cs b/src/Stars.Console/ConsoleCredentialsManager.cs index 0c096d6d..fc778177 100644 --- a/src/Stars.Console/ConsoleCredentialsManager.cs +++ b/src/Stars.Console/ConsoleCredentialsManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net; using McMaster.Extensions.CommandLineUtils; using Microsoft.Extensions.Logging; @@ -66,7 +66,7 @@ private void PromptSaveCredentials(ICredentials cred, Uri uri, string authType) private void SaveCredentials(ICredentials cred, Uri uri, string authType) { CredentialsConfigurationSection credConfigSection = cred.ToCredentialsConfigurationSection(uri, authType); - consoleUserSettings.AddOrUpdateSetting("Credentials:" + Guid.NewGuid().ToString(), credConfigSection); + consoleUserSettings.AddOrUpdateSetting("Credentials:" + Guid.NewGuid().ToString(), credConfigSection); } private NetworkCredential PromptCredentials(Uri uri, string authType) @@ -119,4 +119,4 @@ private NetworkCredential PromptCredentials(Uri uri, string authType) return new NetworkCredential(username, pass); } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/ConsoleUserSettings.cs b/src/Stars.Console/ConsoleUserSettings.cs index 55f934cf..112ebed7 100644 --- a/src/Stars.Console/ConsoleUserSettings.cs +++ b/src/Stars.Console/ConsoleUserSettings.cs @@ -1,15 +1,14 @@ -using System; +using System; using System.IO; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Terradue.Stars.Console { internal class ConsoleUserSettings { - private readonly string userSettingsFilePath = Path.Join(System.Environment.GetEnvironmentVariable("HOME"), ".config", "Stars" , "usersettings.json"); + private readonly string userSettingsFilePath = Path.Join(System.Environment.GetEnvironmentVariable("HOME"), ".config", "Stars", "usersettings.json"); private readonly ILogger logger; private readonly IConfigurationRoot configuration; @@ -75,4 +74,4 @@ private void SetValueRecursively(string sectionPathKey, dynamic jsonObj, T va } } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/Operations/BaseOperation.cs b/src/Stars.Console/Operations/BaseOperation.cs index dc721e17..abd032d6 100644 --- a/src/Stars.Console/Operations/BaseOperation.cs +++ b/src/Stars.Console/Operations/BaseOperation.cs @@ -1,19 +1,18 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; +using System.Diagnostics; using System.IO; +using System.Linq; using System.Net; +using System.Reflection; using System.Runtime.Loader; +using System.Threading; using System.Threading.Tasks; using McMaster.Extensions.CommandLineUtils; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Terradue.Stars.Services; -using Microsoft.Extensions.Configuration.EnvironmentVariables; -using System.Diagnostics; -using System.Linq; -using System.Reflection; -using System.Threading; namespace Terradue.Stars.Console.Operations { @@ -38,7 +37,7 @@ internal abstract class BaseOperation public BaseOperation(IConsole console) { - this._console = console; + _console = console; } protected IServiceProvider ServiceProvider { get; private set; } @@ -57,7 +56,7 @@ private string GetBasePath() { using var processModule = Process.GetCurrentProcess().MainModule; - return Path.GetDirectoryName(processModule?.FileName); + return Path.GetDirectoryName(processModule?.FileName); } public async Task OnExecuteAsync(CancellationToken ct) @@ -107,7 +106,7 @@ private ServiceCollection RegisterServices() // tell the builder to look for the appsettings.json file builder.AddNewtonsoftJsonFile("/etc/Stars/appsettings.json", optional: true); foreach (var jsonFilename in Directory.EnumerateFiles(GetBasePath(), "stars-*.json", SearchOption.TopDirectoryOnly)) - builder.AddNewtonsoftJsonFile(jsonFilename); + builder.AddNewtonsoftJsonFile(jsonFilename); if (Directory.Exists("/etc/Stars/conf.d")) { @@ -120,7 +119,7 @@ private ServiceCollection RegisterServices() //only add secrets in development if (isDevelopment) { - var binPath = Path.GetDirectoryName((new System.Uri(Assembly.GetExecutingAssembly().Location)).AbsolutePath); + var binPath = Path.GetDirectoryName((new Uri(Assembly.GetExecutingAssembly().Location)).AbsolutePath); foreach (var jsonFilename in Directory.EnumerateFiles(binPath, "stars-*.json", SearchOption.TopDirectoryOnly)) builder.AddNewtonsoftJsonFile(jsonFilename); builder.AddNewtonsoftJsonFile("appsettings.Development.json", optional: true); @@ -143,10 +142,10 @@ private ServiceCollection RegisterServices() - collection.AddSingleton(Configuration); + collection.AddSingleton(Configuration); // Add the command line services - collection.AddSingleton(_console); + collection.AddSingleton(_console); collection.AddSingleton(logger); // Add Stars Services @@ -172,10 +171,10 @@ private ServiceCollection RegisterServices() private int GetVerbosityLevel() { int verbosity = 0; - if ( Verbose ) - verbosity ++; - - if ( Trace ) + if (Verbose) + verbosity++; + + if (Trace) verbosity = 2; return verbosity; @@ -190,12 +189,12 @@ private static void DisposeServices(IServiceProvider serviceProvider) return; } - if (serviceProvider is IDisposable) + if (serviceProvider is IDisposable disposable) { - ((IDisposable)serviceProvider).Dispose(); + disposable.Dispose(); } } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/Operations/CopyOperation.cs b/src/Stars.Console/Operations/CopyOperation.cs index 61d31a92..f1dba14f 100644 --- a/src/Stars.Console/Operations/CopyOperation.cs +++ b/src/Stars.Console/Operations/CopyOperation.cs @@ -1,30 +1,27 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; using McMaster.Extensions.CommandLineUtils; using Microsoft.Extensions.DependencyInjection; +using Newtonsoft.Json; +using Stac; +using Terradue.Stars.Interface; +using Terradue.Stars.Interface.Processing; using Terradue.Stars.Interface.Router; -using Terradue.Stars.Interface.Router.Translator; using Terradue.Stars.Interface.Supplier; using Terradue.Stars.Interface.Supplier.Destination; +using Terradue.Stars.Services; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Services.Router; +using Terradue.Stars.Services.Plugins; using Terradue.Stars.Services.Processing; +using Terradue.Stars.Services.Router; +using Terradue.Stars.Services.Store; +using Terradue.Stars.Services.Supplier; using Terradue.Stars.Services.Supplier.Carrier; using Terradue.Stars.Services.Translator; -using Terradue.Stars.Services.Supplier; -using Terradue.Stars.Interface.Processing; -using Terradue.Stars.Interface; -using Terradue.Stars.Services; -using Terradue.Stars.Services.Store; -using System.Net; -using Newtonsoft.Json; -using System.Text.RegularExpressions; -using Terradue.Stars.Services.Plugins; -using Stac; -using System.Threading; namespace Terradue.Stars.Console.Operations { @@ -340,16 +337,16 @@ private PluginList InitSuppliersEnumerator(IResource route, SupplierF protected override async Task ExecuteAsync(CancellationToken ct) { - this.routingService = ServiceProvider.GetService(); - this.carrierManager = ServiceProvider.GetService(); - this.processingManager = ServiceProvider.GetService(); - this.storeService = ServiceProvider.GetService(); - this.translatorManager = ServiceProvider.GetService(); - this.supplierManager = ServiceProvider.GetService(); - this.stacLinkTranslator = ServiceProvider.GetService(); - this.resourceServiceProvider = ServiceProvider.GetService(); + routingService = ServiceProvider.GetService(); + carrierManager = ServiceProvider.GetService(); + processingManager = ServiceProvider.GetService(); + storeService = ServiceProvider.GetService(); + translatorManager = ServiceProvider.GetService(); + supplierManager = ServiceProvider.GetService(); + stacLinkTranslator = ServiceProvider.GetService(); + resourceServiceProvider = ServiceProvider.GetService(); var stacRouter = ServiceProvider.GetService(); - await this.storeService.InitAsync(ct, !AppendCatalog); + await storeService.InitAsync(ct, !AppendCatalog); InitRoutingTask(); await PrepareNewRouteAsync(null, storeService.RootCatalogNode, null, null, ct); routingService.OnRoutingException((res, router, ex, state, ct) => Task.FromResult(OnRoutingException(res, router, ex, state, ct))); @@ -372,7 +369,7 @@ protected override async Task ExecuteAsync(CancellationToken ct) CopyOperationState copyState = state as CopyOperationState; stacNodes.Add(copyState.CurrentStacObject); } - storeService.RootCatalogNode.StacCatalog.UpdateLinks(stacNodes.SelectMany(sn => + storeService.RootCatalogNode.StacCatalog.UpdateLinks(stacNodes.SelectMany(sn => { if (sn is StacItemNode) return new IResource[] { sn }; if (sn is StacCatalogNode) return sn.GetRoutes(stacRouter); @@ -435,4 +432,4 @@ protected override void RegisterOperationServices(ServiceCollection collection) } } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/Operations/CopyOperationState.cs b/src/Stars.Console/Operations/CopyOperationState.cs index c8c01882..46a34516 100644 --- a/src/Stars.Console/Operations/CopyOperationState.cs +++ b/src/Stars.Console/Operations/CopyOperationState.cs @@ -1,8 +1,4 @@ -using System.Collections.Generic; -using Terradue.Stars.Interface; -using Terradue.Stars.Interface.Router; - -using Terradue.Stars.Interface.Supplier.Destination; +using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services.Store; @@ -22,4 +18,4 @@ public CopyOperationState(int depth, StacStoreService storeService, IDestination public StacNode CurrentStacObject { get; internal set; } public StacStoreService StoreService { get; internal set; } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/Operations/ListOperation.cs b/src/Stars.Console/Operations/ListOperation.cs index d563ee9e..ad758603 100644 --- a/src/Stars.Console/Operations/ListOperation.cs +++ b/src/Stars.Console/Operations/ListOperation.cs @@ -1,19 +1,15 @@ -using System; +using System; using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; using McMaster.Extensions.CommandLineUtils; -using Microsoft.Extensions.Logging; -using Terradue.Stars.Interface.Router; - -using Terradue.Stars.Services.Router; -using Terradue.Stars.Services; -using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.DependencyInjection; -using System.Net; using Terradue.Stars.Interface; -using System.IO; -using System.Threading; +using Terradue.Stars.Interface.Router; +using Terradue.Stars.Services; +using Terradue.Stars.Services.Router; namespace Terradue.Stars.Console.Operations { @@ -34,7 +30,7 @@ internal class ListOperation : BaseOperation private int recursivity = 1; private string[] inputs = new string[0]; - public ListOperation(IConsole console): base(console) + public ListOperation(IConsole console) : base(console) { } @@ -52,12 +48,12 @@ private void InitRoutingTask() routingService.OnBranching((parentRoute, route, siblings, state, ct) => PrepareNewRoute(parentRoute, route, siblings, state, ct)); } - private Task PrepareNewRoute(IResource parentRoute, IResource route, IEnumerable siblings, object state, System.Threading.CancellationToken ct) + private Task PrepareNewRoute(IResource parentRoute, IResource route, IEnumerable siblings, object state, CancellationToken ct) { if (state == null) return Task.FromResult(new ListOperationState("", 1)); ListOperationState operationState = state as ListOperationState; - if (operationState.Depth == 0) return Task.FromResult(state); + if (operationState.Depth == 0) return Task.FromResult(state); string newPrefix = operationState.Prefix.Replace('─', ' ').Replace('└', ' '); int i = siblings.ToList().IndexOf(route); @@ -70,20 +66,20 @@ private Task PrepareNewRoute(IResource parentRoute, IResource route, IEn return Task.FromResult(new ListOperationState(newPrefix, operationState.Depth + 1)); } - private async Task PrintItem(IItem node, IRouter router, object state, System.Threading.CancellationToken ct) + private async Task PrintItem(IItem node, IRouter router, object state, CancellationToken ct) { ListOperationState operationState = state as ListOperationState; string resourcePrefix1 = operationState.Prefix; if (router != null) resourcePrefix1 = string.Format("[{0}] {1}", router.Label, operationState.Prefix); _console.ForegroundColor = GetColorFromType(node.ResourceType); - await _console.Out.WriteLineAsync(String.Format("{0,-80} {1,40}", (resourcePrefix1 + node.Title).Truncate(99), node.ContentType)); + await _console.Out.WriteLineAsync(string.Format("{0,-80} {1,40}", (resourcePrefix1 + node.Title).Truncate(99), node.ContentType)); _console.ForegroundColor = ConsoleColor.White; await PrintAssets(node, router, operationState.Prefix); return state; } - private async Task PrintBranchingNode(ICatalog node, IRouter router, object state, System.Threading.CancellationToken ct) + private async Task PrintBranchingNode(ICatalog node, IRouter router, object state, CancellationToken ct) { _console.ForegroundColor = GetColorFromType(node.ResourceType); // Print the information about the resource @@ -91,24 +87,24 @@ private async Task PrintBranchingNode(ICatalog node, IRouter router, obj string resourcePrefix1 = operationState.Prefix; if (router != null) resourcePrefix1 = string.Format("[{0}] {1}", router.Label, operationState.Prefix); - await _console.Out.WriteLineAsync(String.Format("{0,-80} {1,40}", (resourcePrefix1 + node.Title).Truncate(99), node.ContentType)); + await _console.Out.WriteLineAsync(string.Format("{0,-80} {1,40}", (resourcePrefix1 + node.Title).Truncate(99), node.ContentType)); // await PrintAssets(node, router, operationState.Prefix); return state; } - private async Task PrintRouteInfo(IResource route, IRouter router, Exception exception, object state, System.Threading.CancellationToken ct) + private async Task PrintRouteInfo(IResource route, IRouter router, Exception exception, object state, CancellationToken ct) { ListOperationState operationState = state as ListOperationState; string resourcePrefix1 = operationState.Prefix; if (router != null) resourcePrefix1 = string.Format("[{0}] {1}", router.Label, operationState.Prefix); _console.ForegroundColor = GetColorFromType(route.ResourceType); - await _console.Out.WriteAsync(String.Format("{0,-80} {1,40}", (resourcePrefix1 + route.Uri).Truncate(99), route.ContentType)); + await _console.Out.WriteAsync(string.Format("{0,-80} {1,40}", (resourcePrefix1 + route.Uri).Truncate(99), route.ContentType)); if (exception != null) { _console.ForegroundColor = ConsoleColor.Red; - await _console.Out.WriteLineAsync(String.Format(" -> {0}", exception.Message.Truncate(99))); + await _console.Out.WriteLineAsync(string.Format(" -> {0}", exception.Message.Truncate(99))); } else await _console.Out.WriteLineAsync(); @@ -118,8 +114,8 @@ private async Task PrintRouteInfo(IResource route, IRouter router, Excep protected override async Task ExecuteAsync(CancellationToken ct) { - this.routingService = ServiceProvider.GetService(); - this.resourceServiceProvider = ServiceProvider.GetService(); + routingService = ServiceProvider.GetService(); + resourceServiceProvider = ServiceProvider.GetService(); InitRoutingTask(); var tasks = Inputs.Select(input => resourceServiceProvider.CreateStreamResourceAsync(new GenericResource(new Uri(input)), ct)); List routes = (await Task.WhenAll(tasks)).Cast().ToList(); @@ -135,9 +131,9 @@ protected override async Task ExecuteAsync(CancellationToken ct) private async Task PrintAssets(IItem resource, IRouter router, string prefix) { // List assets - if (!SkippAssets && resource is IAssetsContainer) + if (!SkippAssets && resource is IAssetsContainer container) { - IReadOnlyDictionary assets = ((IAssetsContainer)resource).Assets; + IReadOnlyDictionary assets = container.Assets; for (int i = 0; i < assets.Count(); i++) { string newPrefix = prefix.Replace('─', ' ').Replace('└', ' '); @@ -154,10 +150,10 @@ private async Task PrintAssets(IItem resource, IRouter router, string prefix) assetPrefix = string.Format("[{0}] {1}", router.Label, assetPrefix); var asset = assets.ElementAt(i).Value; string title = asset.Title; - if ( string.IsNullOrEmpty(title) ) + if (string.IsNullOrEmpty(title)) title = Path.GetFileName(asset.Uri.ToString()); title = string.Format("[{0}] {1}", assets.ElementAt(i).Key, title); - await _console.Out.WriteLineAsync(String.Format("{0,-80} {1,40}", (assetPrefix + title).Truncate(99), asset.ContentType)); + await _console.Out.WriteLineAsync(string.Format("{0,-80} {1,40}", (assetPrefix + title).Truncate(99), asset.ContentType)); _console.ForegroundColor = ConsoleColor.White; } } @@ -184,4 +180,4 @@ protected override void RegisterOperationServices(ServiceCollection collection) { } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/Operations/ListOperationState.cs b/src/Stars.Console/Operations/ListOperationState.cs index af73bad5..5f2a6d66 100644 --- a/src/Stars.Console/Operations/ListOperationState.cs +++ b/src/Stars.Console/Operations/ListOperationState.cs @@ -1,4 +1,4 @@ -namespace Terradue.Stars.Console.Operations +namespace Terradue.Stars.Console.Operations { internal class ListOperationState { @@ -11,4 +11,4 @@ public ListOperationState(string prefix, int depth) public string Prefix { get; internal set; } public int Depth { get; internal set; } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/Operations/PluginsOperation.cs b/src/Stars.Console/Operations/PluginsOperation.cs index 829fe6b7..0f6bd92d 100644 --- a/src/Stars.Console/Operations/PluginsOperation.cs +++ b/src/Stars.Console/Operations/PluginsOperation.cs @@ -1,22 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using System.Linq; +using System.Threading; using System.Threading.Tasks; using McMaster.Extensions.CommandLineUtils; -using Microsoft.Extensions.Logging; -using Terradue.Stars.Interface.Router; - -using Terradue.Stars.Services.Router; -using Terradue.Stars.Services; -using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.DependencyInjection; -using System.Net; -using Terradue.Stars.Interface; -using System.IO; -using Terradue.Stars.Services.Supplier; using Terradue.Stars.Services.Processing; +using Terradue.Stars.Services.Router; +using Terradue.Stars.Services.Supplier; using Terradue.Stars.Services.Translator; -using System.Threading; namespace Terradue.Stars.Console.Operations { @@ -25,7 +15,7 @@ internal class PluginsOperation : BaseOperation { private readonly CommandLineApplication app; - public PluginsOperation(IConsole console, CommandLineApplication app): base(console) + public PluginsOperation(IConsole console, CommandLineApplication app) : base(console) { this.app = app; } @@ -39,25 +29,25 @@ protected override async Task ExecuteAsync(CancellationToken ct) _console.Out.WriteLine($"* Routers:"); routersManager.GetPlugins().ToList().ForEach(p => { - _console.Out.WriteLine($" * [{p.Key}] {p.Value.Label}"); + _console.Out.WriteLine($" * [{p.Key}] {p.Value.Label}"); }); var suppliersManager = ServiceProvider.GetService(); _console.Out.WriteLine($"* Suppliers:"); suppliersManager.GetPlugins().ToList().ForEach(p => { - _console.Out.WriteLine($" * [{p.Key}] {p.Value.Label}"); + _console.Out.WriteLine($" * [{p.Key}] {p.Value.Label}"); }); var translatorManager = ServiceProvider.GetService(); _console.Out.WriteLine($"* Translators:"); translatorManager.GetPlugins().ToList().ForEach(p => { - _console.Out.WriteLine($" * [{p.Key}] {p.Value.Label}"); + _console.Out.WriteLine($" * [{p.Key}] {p.Value.Label}"); }); var processingManager = ServiceProvider.GetService(); _console.Out.WriteLine($"* Processings:"); processingManager.GetPlugins().ToList().ForEach(p => { - _console.Out.WriteLine($" * [{p.Key}] {p.Value.Label}"); + _console.Out.WriteLine($" * [{p.Key}] {p.Value.Label}"); }); } @@ -65,4 +55,4 @@ protected override void RegisterOperationServices(ServiceCollection collection) { } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/PluginLoadContext.cs b/src/Stars.Console/PluginLoadContext.cs index 17ba0516..f9bfe330 100644 --- a/src/Stars.Console/PluginLoadContext.cs +++ b/src/Stars.Console/PluginLoadContext.cs @@ -1,8 +1,6 @@ -using System; -using System.IO; +using System; using System.Reflection; using System.Runtime.Loader; -using McMaster.Extensions.CommandLineUtils; namespace Terradue.Stars.Console { @@ -62,4 +60,4 @@ protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) return IntPtr.Zero; } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/Stars.cs b/src/Stars.Console/Stars.cs index cbd7faf8..7109f5ea 100644 --- a/src/Stars.Console/Stars.cs +++ b/src/Stars.Console/Stars.cs @@ -1,11 +1,9 @@ -using System.Threading.Tasks; +using System; +using System.ComponentModel.DataAnnotations; +using System.Reflection; using McMaster.Extensions.CommandLineUtils; using Microsoft.Extensions.Configuration; using Terradue.Stars.Console.Operations; -using System.ComponentModel.DataAnnotations; -using System; -using System.Net; -using System.Reflection; namespace Terradue.Stars.Console { diff --git a/src/Stars.Console/StarsConsoleLoggerProvider.cs b/src/Stars.Console/StarsConsoleLoggerProvider.cs index 93c44dd1..e9961a22 100644 --- a/src/Stars.Console/StarsConsoleLoggerProvider.cs +++ b/src/Stars.Console/StarsConsoleLoggerProvider.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Concurrent; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; +using System.Collections.Concurrent; using McMaster.Extensions.CommandLineUtils; -using McMaster.Extensions.CommandLineUtils.Abstractions; using Microsoft.Extensions.Logging; namespace Terradue.Stars.Console @@ -31,4 +26,4 @@ public void Dispose() _loggers.Clear(); } } -} \ No newline at end of file +} diff --git a/src/Stars.Console/StarsConsoleReporter.cs b/src/Stars.Console/StarsConsoleReporter.cs index 688b61a7..085d2cdc 100644 --- a/src/Stars.Console/StarsConsoleReporter.cs +++ b/src/Stars.Console/StarsConsoleReporter.cs @@ -1,9 +1,5 @@ -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; +using System; using McMaster.Extensions.CommandLineUtils; -using McMaster.Extensions.CommandLineUtils.Abstractions; using Microsoft.Extensions.Logging; namespace Terradue.Stars.Console @@ -42,7 +38,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except { string message = formatter(state, exception); - if ( logLevel == LogLevel.Trace && verbose <= 1 ) + if (logLevel == LogLevel.Trace && verbose <= 1) return; switch (logLevel) @@ -64,4 +60,4 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except } } } -} \ No newline at end of file +} diff --git a/src/Stars.Data.Tests/DefaultReasourceServiceProvider.cs b/src/Stars.Data.Tests/DefaultReasourceServiceProvider.cs index e69de29b..5f282702 100644 --- a/src/Stars.Data.Tests/DefaultReasourceServiceProvider.cs +++ b/src/Stars.Data.Tests/DefaultReasourceServiceProvider.cs @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/Stars.Data.Tests/Harvesters/MetadataExtractorsData.cs b/src/Stars.Data.Tests/Harvesters/MetadataExtractorsData.cs index d377cd52..84ac326f 100644 --- a/src/Stars.Data.Tests/Harvesters/MetadataExtractorsData.cs +++ b/src/Stars.Data.Tests/Harvesters/MetadataExtractorsData.cs @@ -1,13 +1,10 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections; +using System.Collections; using System.Collections.Generic; -using Terradue.Stars.Data.Model.Metadata; -using System.Reflection; -using Terradue.Stars.Interface.Processing; -using Xunit.Abstractions; using System.IO; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Terradue.Stars.Data.Model.Metadata; +using Terradue.Stars.Interface.Processing; namespace Terradue.Data.Tests.Harvesters { diff --git a/src/Stars.Data.Tests/Harvesters/MetadataExtractorsTests.cs b/src/Stars.Data.Tests/Harvesters/MetadataExtractorsTests.cs index bdc06096..8b442ecb 100644 --- a/src/Stars.Data.Tests/Harvesters/MetadataExtractorsTests.cs +++ b/src/Stars.Data.Tests/Harvesters/MetadataExtractorsTests.cs @@ -1,23 +1,22 @@ -using System; +using System; +using System.Collections.Generic; using System.IO; using System.IO.Abstractions; -using System.Collections.Generic; using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; -using Xunit; -using Xunit.Abstractions; -using Terradue.Stars.Services; -using Terradue.Stars.Services.Supplier; -using Terradue.Stars.Services.Model.Stac; using Stac; using Terradue.Stars.Data.Model.Metadata; +using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; +using Terradue.Stars.Services; +using Terradue.Stars.Services.Model.Stac; +using Terradue.Stars.Services.Supplier; using Terradue.Stars.Services.Supplier.Destination; -using Terradue.Stars.Interface; -using Terradue.Stars.Services.Store; -using System.Threading; -using System.Text.RegularExpressions; +using Xunit; +using Xunit.Abstractions; namespace Terradue.Data.Tests.Harvesters { @@ -27,7 +26,7 @@ public class MetadataExtractorsTests : TestBase public MetadataExtractorsTests(ITestOutputHelper outputHelper) : base(outputHelper) { - this.fileSystem = ServiceProvider.GetService(); + fileSystem = ServiceProvider.GetService(); } public static IEnumerable TestData @@ -69,7 +68,7 @@ public async void TestExtractors(string key, string datadir, MetadataExtraction stacItemNode.MakeAssetUriRelative(); RemoveAssetUriTmp(stacItemNode); CheckAssetLocalPath(stacItem, key); - var actualJson = StacConvert.Serialize(stacItem, new Newtonsoft.Json.JsonSerializerSettings() + var actualJson = StacConvert.Serialize(stacItem, new JsonSerializerSettings() { Formatting = Formatting.Indented }); @@ -77,7 +76,7 @@ public async void TestExtractors(string key, string datadir, MetadataExtraction { stacValidator.ValidateJson(actualJson); } - catch (System.Exception) + catch (Exception) { System.Console.WriteLine(actualJson); throw; @@ -89,7 +88,7 @@ public async void TestExtractors(string key, string datadir, MetadataExtraction { expectedJson = GetJson(Path.Join(datadir, "../.."), stacItem.Id); } - catch (System.Exception) + catch (Exception) { System.Console.WriteLine(actualJson); throw; @@ -100,7 +99,7 @@ public async void TestExtractors(string key, string datadir, MetadataExtraction { JsonAssert.AreEqual(expectedJson, actualJson); } - catch (System.Exception) + catch (Exception) { System.Console.WriteLine(actualJson); throw; diff --git a/src/Stars.Data.Tests/JsonAssert.cs b/src/Stars.Data.Tests/JsonAssert.cs index 0093269b..712bbc22 100644 --- a/src/Stars.Data.Tests/JsonAssert.cs +++ b/src/Stars.Data.Tests/JsonAssert.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using Newtonsoft.Json.Linq; using Xunit; @@ -46,18 +46,15 @@ private static JObject SortProperties(this JObject jObject) foreach (var property in jObject.Properties().OrderBy(p => p.Name)) { - var value = property.Value as JObject; - - if (value != null) + if (property.Value is JObject value) { value = value.SortProperties(); result.Add(property.Name, value); continue; } - var avalues = property.Value as JArray; - if (avalues != null) + if (property.Value is JArray avalues) { avalues = avalues.SortProperties(); result.Add(property.Name, avalues); @@ -76,9 +73,7 @@ private static JArray SortProperties(this JArray jArray) foreach (var item in jArray) { - var value = item as JObject; - - if (value != null) + if (item is JObject value) { value = value.SortProperties(); result.Add(value); @@ -92,4 +87,4 @@ private static JArray SortProperties(this JArray jArray) return result; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data.Tests/Suppliers/SearchExpressionSupplierTests.cs b/src/Stars.Data.Tests/Suppliers/SearchExpressionSupplierTests.cs index ee824746..ea75553a 100644 --- a/src/Stars.Data.Tests/Suppliers/SearchExpressionSupplierTests.cs +++ b/src/Stars.Data.Tests/Suppliers/SearchExpressionSupplierTests.cs @@ -1,32 +1,15 @@ -using System.Linq; -using Newtonsoft.Json; -using Xunit; -using Stac.Extensions.Projection; -using Terradue.Stars.Data.Translators; -using Stac; -using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Services.Model.Atom; -using System.Threading; -using System.Xml; -using Terradue.ServiceModel.Ogc.Owc.AtomEncoding; -using System; -using Terradue.Metadata.EarthObservation.OpenSearch.Extensions; -using Terradue.Metadata.EarthObservation.Ogc.Extensions; +using System; using System.Collections.Generic; -using Terradue.Stars.Interface.Supplier; using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using Stac.Api.Converters; using Stac.Api.Models.Cql2; +using Terradue.Stars.Interface.Supplier; +using Xunit; using Xunit.Abstractions; -using Stac.Api.Converters; -using Amazon.Runtime.Internal.Util; -using Terradue.Stars.Data.Suppliers; -using Microsoft.Extensions.DependencyInjection; -using Terradue.Stars.Services.Translator; -using Microsoft.Extensions.Logging; -using System.Threading.Tasks; -using Google.Apis.Bigquery.v2.Data; -using Xunit.Sdk; namespace Terradue.Data.Tests.Suppliers { diff --git a/src/Stars.Data.Tests/Suppliers/SuppliersTestsData.cs b/src/Stars.Data.Tests/Suppliers/SuppliersTestsData.cs index b749a85a..93ae8a7a 100644 --- a/src/Stars.Data.Tests/Suppliers/SuppliersTestsData.cs +++ b/src/Stars.Data.Tests/Suppliers/SuppliersTestsData.cs @@ -1,16 +1,11 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections; +using System.Collections; using System.Collections.Generic; -using Terradue.Stars.Data.Model.Metadata; -using System.Reflection; -using Terradue.Stars.Interface.Processing; -using Xunit.Abstractions; using System.IO; using Microsoft.Extensions.Configuration; -using Terradue.Stars.Interface.Supplier; -using Terradue.Stars.Data.Suppliers; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Terradue.Stars.Data.Suppliers; +using Terradue.Stars.Interface.Supplier; using Terradue.Stars.Services.Translator; namespace Terradue.Data.Tests.Suppliers diff --git a/src/Stars.Data.Tests/TestBase.cs b/src/Stars.Data.Tests/TestBase.cs index ef1d4460..50b86b5e 100644 --- a/src/Stars.Data.Tests/TestBase.cs +++ b/src/Stars.Data.Tests/TestBase.cs @@ -1,11 +1,10 @@ -using System; -using System.Collections.Generic; +using System; using System.IO; using System.IO.Abstractions; +using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Loader; -using System.Net; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -93,7 +92,7 @@ private void LoadPlugins() pluginManager.LoadPlugins(Collection, s => AssemblyLoadContext.Default); } - + public static string AssemblyDirectory { @@ -155,4 +154,4 @@ public bool ValidateJson(string jsonstr) public IConfigurationRoot Configuration { get => configuration; } public ITestOutputHelper OutputHelper { get; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data.Tests/TestFileAsset.cs b/src/Stars.Data.Tests/TestFileAsset.cs index e96eec6e..6620a2f6 100644 --- a/src/Stars.Data.Tests/TestFileAsset.cs +++ b/src/Stars.Data.Tests/TestFileAsset.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -6,9 +6,6 @@ using System.Threading; using System.Threading.Tasks; using Terradue.Stars.Interface; -using Terradue.Stars.Interface.Router; -using Terradue.Stars.Interface.Supplier; -using Terradue.Stars.Services.Router; namespace Terradue.Data.Tests { @@ -72,4 +69,4 @@ public Task GetStreamAsync(long start, CancellationToken ct, long end = throw new NotImplementedException(); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data.Tests/TestNode.cs b/src/Stars.Data.Tests/TestNode.cs index a269a830..7cac705a 100644 --- a/src/Stars.Data.Tests/TestNode.cs +++ b/src/Stars.Data.Tests/TestNode.cs @@ -1,15 +1,12 @@ -using System; +using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Net.Mime; using System.Threading; using System.Threading.Tasks; using GeoJSON.Net.Geometry; using Itenso.TimePeriod; using Terradue.Stars.Interface; -using Terradue.Stars.Interface.Router; -using Terradue.Stars.Interface.Supplier; namespace Terradue.Data.Tests { @@ -19,7 +16,7 @@ internal class TestItem : IItem public TestItem(string folderPath) { - this.directory = new DirectoryInfo(folderPath); + directory = new DirectoryInfo(folderPath); } public string Title => directory.FullName; @@ -77,4 +74,4 @@ public Task GetStreamAsync(long start, CancellationToken ct, long end = throw new NotImplementedException(); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data.Tests/TestVectorService.cs b/src/Stars.Data.Tests/TestVectorService.cs index ee63a9a5..098aa9bd 100644 --- a/src/Stars.Data.Tests/TestVectorService.cs +++ b/src/Stars.Data.Tests/TestVectorService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -22,10 +22,10 @@ public IDictionary SelectVectorAssets(StacItem stacItem) Dictionary vectorAssets = stacItem.Assets .Where(a => a.Value.Roles.Contains("visual")) .OrderBy(a => a.Value.GetProperty("size")) - .Where(a => a.Value.MediaType.MediaType.Contains("application/flatgeobuf") + .Where(a => a.Value.MediaType.MediaType.Contains("application/flatgeobuf") || a.Value.MediaType.MediaType.Contains("application/geo+json")) .ToDictionary(a => a.Key, a => a.Value); return vectorAssets; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data.Tests/Translators/StacCollectionToAtomItemTests.cs b/src/Stars.Data.Tests/Translators/StacCollectionToAtomItemTests.cs index 021ee187..32bf86fb 100644 --- a/src/Stars.Data.Tests/Translators/StacCollectionToAtomItemTests.cs +++ b/src/Stars.Data.Tests/Translators/StacCollectionToAtomItemTests.cs @@ -1,18 +1,15 @@ +using System; +using System.IO; using System.Linq; -using Newtonsoft.Json; -using Xunit; -using Stac.Extensions.Projection; -using Terradue.Stars.Data.Translators; -using Stac; -using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Services.Model.Atom; using System.Threading; -using System.Xml; +using Stac; using Terradue.ServiceModel.Ogc.Owc.AtomEncoding; -using System; -using System.IO; -using Terradue.Stars.Services.Supplier; +using Terradue.Stars.Data.Translators; using Terradue.Stars.Services; +using Terradue.Stars.Services.Model.Atom; +using Terradue.Stars.Services.Model.Stac; +using Terradue.Stars.Services.Supplier; +using Xunit; namespace Terradue.Data.Tests.Translators { @@ -29,7 +26,7 @@ public async System.Threading.Tasks.Task EGMS() StacCollectionToAtomItemTranslator stacCollectionToAtomItemTranslator = new StacCollectionToAtomItemTranslator(ServiceProvider); - StacCollectionNode stacItemNode = new StacCollectionNode(stacCollection, new System.Uri("https://localhost:5001/api/ns/emathot/cs/0000024-220301000006171-oozie-oozi-W")); + StacCollectionNode stacItemNode = new StacCollectionNode(stacCollection, new Uri("https://localhost:5001/api/ns/emathot/cs/0000024-220301000006171-oozie-oozi-W")); AtomItemNode atomItemNode = await stacCollectionToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -40,19 +37,19 @@ public async System.Threading.Tasks.Task EGMS() bool egmsIsPresent = false; bool wmsIsPresent = false; if (atomItemNode.AtomItem.ElementExtensions != null && atomItemNode.AtomItem.ElementExtensions.Count > 0) - { + { var offerings = atomItemNode.AtomItem.ElementExtensions.ReadElementExtensions("offering", OwcNamespaces.Owc, new System.Xml.Serialization.XmlSerializer(typeof(OwcOffering))); - foreach (var offering in offerings) - { - if(offering != null && offering.Code == "http://www.terradue.com/egms") egmsIsPresent = true; - if(offering != null && offering.Code == "http://www.opengis.net/spec/owc-atom/1.0/req/wms") wmsIsPresent = true; + foreach (var offering in offerings) + { + if (offering != null && offering.Code == "http://www.terradue.com/egms") egmsIsPresent = true; + if (offering != null && offering.Code == "http://www.opengis.net/spec/owc-atom/1.0/req/wms") wmsIsPresent = true; } - + } - Assert.True(egmsIsPresent); - Assert.True(wmsIsPresent); + Assert.True(egmsIsPresent); + Assert.True(wmsIsPresent); } [Fact] @@ -66,7 +63,7 @@ public async System.Threading.Tasks.Task EGMS_2018_2022() StacCollectionToAtomItemTranslator stacCollectionToAtomItemTranslator = new StacCollectionToAtomItemTranslator(ServiceProvider); - StacCollectionNode stacCollectionNode = new StacCollectionNode(stacCollection, new System.Uri("https://api.terradue.com/timeseries/v1/ns/gep-egms/cs/EGMS-2018-2022")); + StacCollectionNode stacCollectionNode = new StacCollectionNode(stacCollection, new Uri("https://api.terradue.com/timeseries/v1/ns/gep-egms/cs/EGMS-2018-2022")); // Filter assets to remove the timeseries assets AssetFilters assetFilters = AssetFilters.CreateAssetFilters( @@ -79,22 +76,22 @@ public async System.Threading.Tasks.Task EGMS_2018_2022() StacCollection stacCollection1 = new StacCollection(stacCollection); stacCollection1.Assets.Clear(); stacCollection1.Assets.AddRange(filteredAssetContainer.Assets.ToDictionary(asset => asset.Key, asset => (asset.Value as StacAssetAsset).StacAsset)); - StacCollectionNode stacCollectionNode1 = new StacCollectionNode(stacCollection1, new System.Uri("https://api.terradue.com/timeseries/v1/ns/gep-egms/cs/EGMS-2018-2022")); + StacCollectionNode stacCollectionNode1 = new StacCollectionNode(stacCollection1, new Uri("https://api.terradue.com/timeseries/v1/ns/gep-egms/cs/EGMS-2018-2022")); AtomItemNode atomItemNode = await stacCollectionToAtomItemTranslator.TranslateAsync(stacCollectionNode1, CancellationToken.None); bool egmsIsPresent = false; if (atomItemNode.AtomItem.ElementExtensions != null && atomItemNode.AtomItem.ElementExtensions.Count > 0) - { + { var offerings = atomItemNode.AtomItem.ElementExtensions.ReadElementExtensions("offering", OwcNamespaces.Owc, new System.Xml.Serialization.XmlSerializer(typeof(OwcOffering))); - foreach (var offering in offerings) - { - if(offering != null && offering.Code == "http://www.terradue.com/egms") egmsIsPresent = true; + foreach (var offering in offerings) + { + if (offering != null && offering.Code == "http://www.terradue.com/egms") egmsIsPresent = true; } } - Assert.True(egmsIsPresent); + Assert.True(egmsIsPresent); // Check that there is no link with the relationship type "enclosure" Assert.DoesNotContain(atomItemNode.AtomItem.Links, diff --git a/src/Stars.Data.Tests/Translators/StacItemToAtomItemTests.cs b/src/Stars.Data.Tests/Translators/StacItemToAtomItemTests.cs index 65f53c59..73ff68cf 100644 --- a/src/Stars.Data.Tests/Translators/StacItemToAtomItemTests.cs +++ b/src/Stars.Data.Tests/Translators/StacItemToAtomItemTests.cs @@ -1,17 +1,15 @@ +using System; using System.Linq; -using Newtonsoft.Json; -using Xunit; -using Stac.Extensions.Projection; -using Terradue.Stars.Data.Translators; -using Stac; -using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Services.Model.Atom; using System.Threading; using System.Xml; -using Terradue.ServiceModel.Ogc.Owc.AtomEncoding; -using System; -using Terradue.Metadata.EarthObservation.OpenSearch.Extensions; +using Stac; using Terradue.Metadata.EarthObservation.Ogc.Extensions; +using Terradue.Metadata.EarthObservation.OpenSearch.Extensions; +using Terradue.ServiceModel.Ogc.Owc.AtomEncoding; +using Terradue.Stars.Data.Translators; +using Terradue.Stars.Services.Model.Atom; +using Terradue.Stars.Services.Model.Stac; +using Xunit; namespace Terradue.Data.Tests.Translators { @@ -28,7 +26,7 @@ public async System.Threading.Tasks.Task S2A_MSIL2A_20191216T004701_N0213_R102_T StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("s3://eoepca-ades/wf-d0534740-b97b-11eb-82cf-0a580a830350/S2A_MSIL2A_20191216T004701_N0213_R102_T53HPA_20191216T024808/S2A_MSIL2A_20191216T004701_N0213_R102_T53HPA_20191216T024808.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("s3://eoepca-ades/wf-d0534740-b97b-11eb-82cf-0a580a830350/S2A_MSIL2A_20191216T004701_N0213_R102_T53HPA_20191216T024808/S2A_MSIL2A_20191216T004701_N0213_R102_T53HPA_20191216T024808.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -52,7 +50,7 @@ public async System.Threading.Tasks.Task S1A_OPER_SAR_EOSSP__CORE_L1A_OLF_202111 StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("s3://dc-development-catalog/calls/call-969/calibratedDatasets/S1A_OPER_SAR_EOSSP__CORE_L1A_OLF_20211117T174240-calibrated/S1A_OPER_SAR_EOSSP__CORE_L1A_OLF_20211117T174240-calibrated.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("s3://dc-development-catalog/calls/call-969/calibratedDatasets/S1A_OPER_SAR_EOSSP__CORE_L1A_OLF_20211117T174240-calibrated/S1A_OPER_SAR_EOSSP__CORE_L1A_OLF_20211117T174240-calibrated.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -80,7 +78,7 @@ public async System.Threading.Tasks.Task VectorResults() StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("s3://eoepca-ades/wf-test/test.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("s3://eoepca-ades/wf-test/test.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -107,11 +105,11 @@ public async System.Threading.Tasks.Task LegendTest() StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("s3://eoepca-ades/wf-test/test.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("s3://eoepca-ades/wf-test/test.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); - Terradue.ServiceModel.Syndication.SyndicationLink legendLink = atomItemNode.AtomItem.Links.FirstOrDefault(r => r.RelationshipType == "legend"); + ServiceModel.Syndication.SyndicationLink legendLink = atomItemNode.AtomItem.Links.FirstOrDefault(r => r.RelationshipType == "legend"); Assert.NotNull(legendLink); Assert.Equal("https://test.com/legend.png", legendLink.Uri.AbsoluteUri); @@ -128,7 +126,7 @@ public async System.Threading.Tasks.Task TWMTest() StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("s3://eoepca-ades/wf-test/test.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("s3://eoepca-ades/wf-test/test.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -151,7 +149,7 @@ public async System.Threading.Tasks.Task HANDTest() StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("s3://dc-acceptance-catalog/calls/call-969/calibratedDatasets/act-813_Auxiliary_Dataset_HAND-calibrated/act-813_Auxiliary_Dataset_HAND-calibrated.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("s3://dc-acceptance-catalog/calls/call-969/calibratedDatasets/act-813_Auxiliary_Dataset_HAND-calibrated/act-813_Auxiliary_Dataset_HAND-calibrated.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -174,7 +172,7 @@ public async System.Threading.Tasks.Task NEWSAT20240320041309SN24L1SRTest() StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("s3://cpe-operations-catalog/calls/call-997/datasets/20240320_041309_SN24_L1_SR/20240320_041309_SN24_L1_SR.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("s3://cpe-operations-catalog/calls/call-997/datasets/20240320_041309_SN24_L1_SR/20240320_041309_SN24_L1_SR.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -189,7 +187,7 @@ public async System.Threading.Tasks.Task S2A_MSIL2A_20221221T100431_N0509_R122_T StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("s3://cpe-operations-catalog/calls/call-6/calibratedDatasets/S2A_MSIL2A_20221221T100431_N0509_R122_T33TWM_20221221T141957-calibrated/S2A_MSIL2A_20221221T100431_N0509_R122_T33TWM_20221221T141957/S2A_MSIL2A_20221221T100431_N0509_R122_T33TWM_20221221T141957.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("s3://cpe-operations-catalog/calls/call-6/calibratedDatasets/S2A_MSIL2A_20221221T100431_N0509_R122_T33TWM_20221221T141957-calibrated/S2A_MSIL2A_20221221T100431_N0509_R122_T33TWM_20221221T141957/S2A_MSIL2A_20221221T100431_N0509_R122_T33TWM_20221221T141957.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -226,7 +224,7 @@ public async System.Threading.Tasks.Task S1A_IW_GRDH_1SDV_20220903T165054_202209 StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("s3://cpe-operations-catalog/calls/call-6/calibratedDatasets/S1A_IW_GRDH_1SDV_20220903T165054_20220903T165119_044843_055B06_B33A-calibrated/S1A_IW_GRDH_1SDV_20220903T165054_20220903T165119_044843_055B06_B33A/S1A_IW_GRDH_1SDV_20220903T165054_20220903T165119_044843_055B06_B33A.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("s3://cpe-operations-catalog/calls/call-6/calibratedDatasets/S1A_IW_GRDH_1SDV_20220903T165054_20220903T165119_044843_055B06_B33A-calibrated/S1A_IW_GRDH_1SDV_20220903T165054_20220903T165119_044843_055B06_B33A/S1A_IW_GRDH_1SDV_20220903T165054_20220903T165119_044843_055B06_B33A.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -259,7 +257,7 @@ public async System.Threading.Tasks.Task VAPTest() StacItemToAtomItemTranslator stacItemToAtomItemTranslator = new StacItemToAtomItemTranslator(ServiceProvider); - StacItemNode stacItemNode = new StacItemNode(stacItem, new System.Uri("https://supervisor.disasterscharter.org/api/activations/act-874/vaps/act-874-vap-1002-6/items/act-874-vap-1002-6.json")); + StacItemNode stacItemNode = new StacItemNode(stacItem, new Uri("https://supervisor.disasterscharter.org/api/activations/act-874/vaps/act-874-vap-1002-6/items/act-874-vap-1002-6.json")); AtomItemNode atomItemNode = await stacItemToAtomItemTranslator.TranslateAsync(stacItemNode, CancellationToken.None); @@ -277,7 +275,7 @@ public async System.Threading.Tasks.Task VAPTest() } - + } } diff --git a/src/Stars.Data/Log4Net2LoggerAppender.cs b/src/Stars.Data/Log4Net2LoggerAppender.cs index 6332477c..4ef20ad9 100644 --- a/src/Stars.Data/Log4Net2LoggerAppender.cs +++ b/src/Stars.Data/Log4Net2LoggerAppender.cs @@ -1,4 +1,4 @@ - + using log4net.Appender; using log4net.Core; using Microsoft.Extensions.Logging; @@ -16,11 +16,12 @@ public Log4Net2LoggerAppender(Microsoft.Extensions.Logging.ILogger logger) protected override void Append(LoggingEvent loggingEvent) { - switch(loggingEvent.Level.Name){ + switch (loggingEvent.Level.Name) + { case "DEBUG": logger.LogDebug(loggingEvent.RenderedMessage); break; } } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Logger4Net.cs b/src/Stars.Data/Logger4Net.cs index 97289b65..c0bbf7dd 100644 --- a/src/Stars.Data/Logger4Net.cs +++ b/src/Stars.Data/Logger4Net.cs @@ -1,9 +1,7 @@ +using System.Reflection; using log4net; -using log4net.Repository.Hierarchy; using log4net.Core; -using log4net.Appender; -using log4net.Layout; -using System.Reflection; +using log4net.Repository.Hierarchy; namespace Terradue.Stars.Data { @@ -13,7 +11,7 @@ public class Logger4Net public static void Setup(Microsoft.Extensions.Logging.ILogger logger) { - if ( Configured ) return; + if (Configured) return; Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetAssembly(typeof(Logger4Net))); @@ -27,4 +25,4 @@ public static void Setup(Microsoft.Extensions.Logging.ILogger logger) Configured = true; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Atom/StarsAtomItem.cs b/src/Stars.Data/Model/Atom/StarsAtomItem.cs index 61a2b719..b501d26c 100644 --- a/src/Stars.Data/Model/Atom/StarsAtomItem.cs +++ b/src/Stars.Data/Model/Atom/StarsAtomItem.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Mime; @@ -7,20 +7,17 @@ using Humanizer; using Markdig; using Stac; +using Stac.Extensions.Eo; +using Stac.Extensions.File; using Stac.Extensions.Projection; -using Terradue.Stars.Data.ThirdParty.Geosquare; using Terradue.OpenSearch.Result; using Terradue.ServiceModel.Ogc.Eop21; using Terradue.ServiceModel.Ogc.Owc.AtomEncoding; using Terradue.ServiceModel.Syndication; using Terradue.Stars.Geometry.Wkt; -using Terradue.Stars.Services.Store; -using Terradue.Stars.Services.ThirdParty.Titiler; -using Stac.Extensions.File; using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services.ThirdParty.Egms; -using Terradue.Stars.Interface; -using Stac.Extensions.Eo; +using Terradue.Stars.Services.ThirdParty.Titiler; namespace Terradue.Stars.Data.Model.Atom { @@ -518,7 +515,7 @@ public async Task CreateOpenSearchLinks(Func "Airbus missions (Pleiades, SPOT, VOL) DIMAP based product metadata extractor"; @@ -37,12 +36,11 @@ public AirbusMetadataExtractor(ILogger logger, IResourc public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IDictionary metadataAssets = GetMetadataAssets(item); - Schemas.Dimap_Document metadata = ReadMetadata(metadataAssets.First().Value).GetAwaiter().GetResult(); + Dimap_Document metadata = ReadMetadata(metadataAssets.First().Value).GetAwaiter().GetResult(); var dimapProfiler = GetProfiler(metadata); return dimapProfiler != null; } @@ -101,8 +99,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi } // Merge MS (multispectral) assets into P (pan-chromatic) STAC item - StacItemNode baseNode = stacItemNodes.FirstOrDefault(n => n.StacItem.Assets.ContainsKey("P-metadata") || n.StacItem.Assets.ContainsKey("metadata-P")); - if (baseNode == null) baseNode = stacItemNodes[0]; + StacItemNode baseNode = stacItemNodes.FirstOrDefault(n => n.StacItem.Assets.ContainsKey("P-metadata") || n.StacItem.Assets.ContainsKey("metadata-P")) ?? stacItemNodes[0]; //StacItem mergedStacItem = baseNode.StacItem; List spectralMode = new List(); @@ -111,7 +108,8 @@ protected override async Task ExtractMetadata(IItem item, string suffi foreach (StacItemNode n in stacItemNodes.FindAll(n => n != baseNode)) { baseNode.StacItem.Assets.AddRange(n.StacItem.Assets); - if (n.StacItem.Properties.ContainsKey("spectral_mode")) { + if (n.StacItem.Properties.ContainsKey("spectral_mode")) + { string[] itemSpectralMode = n.StacItem.GetProperty("spectral_mode"); foreach (string sm in itemSpectralMode) { @@ -170,15 +168,15 @@ protected override async Task ExtractMetadata(IItem item, string suffi private string GetPNEOTitle(List profilers, StacItemNode baseNode) { // from each item, get the spectral processing and put it in a list - var spectralProcesses = profilers.Select(profiler => profiler.Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING.ToUpper()) - .ToList(); + var spectralProcesses = profilers.Select(profiler => profiler.Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING.ToUpper()) + .ToList(); - // check if PAN is present and move it to the first position - spectralProcesses.Remove("PAN"); - spectralProcesses.Insert(0, "PAN"); + // check if PAN is present and move it to the first position + spectralProcesses.Remove("PAN"); + spectralProcesses.Insert(0, "PAN"); - // join the list into a string - string spectralProcessesString = string.Join(" ", spectralProcesses); + // join the list into a string + string spectralProcessesString = string.Join(" ", spectralProcesses); CultureInfo culture = new CultureInfo("fr-FR"); return string.Format("{0} {1} {2} {3}", @@ -205,7 +203,8 @@ private void AddEoBandPropertyInItem(StacItem stacItem) eo.Bands = stacItem.Assets.Values.Where(a => a.EoExtension().Bands != null).SelectMany(a => a.EoExtension().Bands).ToArray(); } - internal virtual StacItem CreateStacItem(AirbusProfiler dimapProfiler) { + internal virtual StacItem CreateStacItem(AirbusProfiler dimapProfiler) + { StacItem stacItem = new StacItem(dimapProfiler.GetId(), GetGeometry(dimapProfiler), @@ -341,7 +340,7 @@ private void FillDateTimeProperties(AirbusProfiler dimapProfiler, Dictionary properties) + private void FillBasicsProperties(AirbusProfiler dimapProfiler, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -358,32 +357,33 @@ private void AddOtherProperties(AirbusProfiler dimapProfiler, IDictionary positions = new List(); + List positions = new List(); foreach (var vertex in dimapProfiler.Dimap.Dataset_Content.Dataset_Extent.Vertex) { - positions.Add(new GeoJSON.Net.Geometry.Position( + positions.Add(new Position( vertex.LAT, vertex.LON ) ); } positions.Add(positions.First()); - GeoJSON.Net.Geometry.LineString lineString = new GeoJSON.Net.Geometry.LineString( + LineString lineString = new LineString( positions.ToArray() ); - return new GeoJSON.Net.Geometry.Polygon(new GeoJSON.Net.Geometry.LineString[] { lineString }).NormalizePolygon(); + return new Polygon(new LineString[] { lineString }).NormalizePolygon(); } - protected void AddAssets(StacItem stacItem, IItem item, IAsset metadataAsset, AirbusProfiler dimapProfiler) { + protected void AddAssets(StacItem stacItem, IItem item, IAsset metadataAsset, AirbusProfiler dimapProfiler) + { - foreach (var dataFiles in dimapProfiler.Dimap.Raster_Data.Data_Access.Data_Files){ - foreach (var dataFile in dataFiles.Data_File) { - IAsset productAsset = FindFirstAssetFromFileNameRegex(item, dataFile.DATA_FILE_PATH.Href + "$"); - if (productAsset == null) - throw new FileNotFoundException(string.Format("No product found '{0}'", + foreach (var dataFiles in dimapProfiler.Dimap.Raster_Data.Data_Access.Data_Files) + { + foreach (var dataFile in dataFiles.Data_File) + { + IAsset productAsset = FindFirstAssetFromFileNameRegex(item, dataFile.DATA_FILE_PATH.Href + "$") ?? throw new FileNotFoundException(string.Format("No product found '{0}'", dataFile.DATA_FILE_PATH.Href)); var bandStacAsset = GetBandAsset(productAsset, dimapProfiler, dataFile, stacItem); if (Path.GetExtension(bandStacAsset.Value.Uri.ToString()) @@ -393,7 +393,8 @@ protected void AddAssets(StacItem stacItem, IItem item, IAsset metadataAsset, Ai stacItem.Assets.Add(bandStacAsset.Key, bandStacAsset.Value); var productWorldFileAsset = FindFirstAssetFromFileNameRegex(item, dataFile.DATA_FILE_PATH.Href.Replace("JP2", "J2W") + "$"); - if (productWorldFileAsset != null) { + if (productWorldFileAsset != null) + { var dataAsset = StacAsset.CreateDataAsset(stacItem, productWorldFileAsset.Uri, new ContentType( MimeTypes.GetMimeType(Path.GetFileName(productWorldFileAsset.Uri.ToString())))); @@ -413,7 +414,8 @@ protected void AddAssets(StacItem stacItem, IItem item, IAsset metadataAsset, Ai .Properties.AddRange(metadataAsset.Properties); var overviewAsset = FindFirstAssetFromFilePathRegex(item, @".*" + dimapProfiler.Dimap.Dataset_Identification.DATASET_QL_PATH?.Href); - if (overviewAsset != null) { + if (overviewAsset != null) + { stacItem.Assets.Add( "overview-" + dimapProfiler.Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING, StacAsset.CreateOverviewAsset(stacItem, overviewAsset.Uri, @@ -423,10 +425,12 @@ protected void AddAssets(StacItem stacItem, IItem item, IAsset metadataAsset, Ai .Properties.AddRange(overviewAsset.Properties); } - if (dimapProfiler.Dimap.Dataset_Identification.DATASET_TN_PATH != null) { + if (dimapProfiler.Dimap.Dataset_Identification.DATASET_TN_PATH != null) + { var thumbnailAsset = FindFirstAssetFromFilePathRegex(item, @".*" + dimapProfiler.Dimap.Dataset_Identification.DATASET_TN_PATH?.Href); - if (thumbnailAsset != null) { + if (thumbnailAsset != null) + { stacItem.Assets.Add( "thumbnail-" + dimapProfiler.Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING, StacAsset.CreateThumbnailAsset(stacItem, thumbnailAsset.Uri, @@ -464,11 +468,11 @@ protected virtual IDictionary GetMetadataAssets(IItem item, bool manifestAsset = FindAllAssetsFromFileNameRegex(item, @"^DIM.*\.XML$"); } if (manifestAsset == null) - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); + throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); return manifestAsset; } - public virtual async Task ReadMetadata(IAsset manifestAsset) + public virtual async Task ReadMetadata(IAsset manifestAsset) { logger.LogDebug("Opening Manifest {0}", manifestAsset.Uri); @@ -477,7 +481,7 @@ protected virtual IDictionary GetMetadataAssets(IItem item, bool var reader = XmlReader.Create(stream); logger.LogDebug("Deserializing Manifest {0}", manifestAsset.Uri); - return (Schemas.Dimap_Document)AirbusDimapSerializer.Deserialize(reader); + return (Dimap_Document)AirbusDimapSerializer.Deserialize(reader); } } @@ -489,4 +493,4 @@ protected KeyValuePair CreateManifestAsset(IStacObject stacOb return new KeyValuePair("manifest", stacAsset); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Airbus/AirbusProfiler.cs b/src/Stars.Data/Model/Metadata/Airbus/AirbusProfiler.cs index c4236a02..986b45ff 100644 --- a/src/Stars.Data/Model/Metadata/Airbus/AirbusProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Airbus/AirbusProfiler.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -15,18 +15,19 @@ namespace Terradue.Stars.Data.Model.Metadata.Airbus { public abstract class AirbusProfiler { - public Schemas.Dimap_Document Dimap { get; protected set; } + public Dimap_Document Dimap { get; protected set; } public AirbusProfiler(Dimap_Document dimap) { Dimap = dimap; } - internal virtual string GetId() { + internal virtual string GetId() + { return Dimap.Dataset_Identification.DATASET_NAME.Text; } - - internal Schemas.Source_Identification GetSourceIdentification() + + internal Source_Identification GetSourceIdentification() { return Dimap.Dataset_Sources.Source_Identification .Where(ds => ds.Strip_Source != null) @@ -100,7 +101,7 @@ public virtual string[] GetSpectralMode() { return null; } - + internal int? GetAbsoluteOrbit() { return null; @@ -123,12 +124,15 @@ internal void AddProcessingSoftware(IDictionary software) internal int GetEpsgProjectionCode() { - try { - if (Dimap.Coordinate_Reference_System.Projected_CRS.PROJECTED_CRS_CODE.Contains("EPSG")) { + try + { + if (Dimap.Coordinate_Reference_System.Projected_CRS.PROJECTED_CRS_CODE.Contains("EPSG")) + { const string pattern = @"\d+$"; var match = Regex.Match(Dimap.Coordinate_Reference_System.Projected_CRS.PROJECTED_CRS_CODE, pattern); - if (match.Success) { + if (match.Success) + { var numberStr = match.Value; return int.Parse(numberStr); } @@ -284,16 +288,16 @@ protected virtual List GetEoBandObjects(StacAsset stacAsset, return eoBandObjects.OrderBy(eob => BandOrders[eob.CommonName]).ToList(); } - protected List GetRasterBandObjects(Schemas.Band_Measurement_List spectralBandInfos, Radiometric_Settings radiometric_Settings,List filterBands = null) + protected List GetRasterBandObjects(Band_Measurement_List spectralBandInfos, Radiometric_Settings radiometric_Settings, List filterBands = null) { List rasterBandObjects = new List(); for (int i = 0; i < spectralBandInfos.Band_Radiance.Count(); i++) { var bandInfo = spectralBandInfos.Band_Radiance[i]; - - if(filterBands!= null && filterBands.Any() && !filterBands.Any(b => b.BAND_ID.Equals(bandInfo.BAND_ID))) + + if (filterBands != null && filterBands.Any() && !filterBands.Any(b => b.BAND_ID.Equals(bandInfo.BAND_ID))) continue; - + var bandSolarIrradiance = spectralBandInfos.Band_Solar_Irradiance[i]; rasterBandObjects.Add(GetRasterBandObject(bandInfo, bandSolarIrradiance, radiometric_Settings)); } @@ -305,7 +309,7 @@ protected List GetRasterBandObjects(Schemas.Band_Measurement_List sp protected abstract IDictionary BandOrders { get; } - protected virtual EoBandObject GetEoBandRadianceObject(Schemas.Band_Measurement_List spectralBandInfos, int index) + protected virtual EoBandObject GetEoBandRadianceObject(Band_Measurement_List spectralBandInfos, int index) { var bandInfo = spectralBandInfos.Band_Radiance[index]; var bandSolarIrradiance = spectralBandInfos.Band_Solar_Irradiance[index]; @@ -315,7 +319,7 @@ protected virtual EoBandObject GetEoBandRadianceObject(Schemas.Band_Measurement_ GetEoCommonName(bandInfo)); eoBandObject.Description = bandInfo.MEASURE_DESC; eoBandObject.SolarIllumination = double.Parse(bandSolarIrradiance.VALUE); - if (Double.TryParse(bandSpectralRange.MIN, out double min) && Double.TryParse(bandSpectralRange.MAX, out double max)) + if (double.TryParse(bandSpectralRange.MIN, out double min) && double.TryParse(bandSpectralRange.MAX, out double max)) { eoBandObject.CenterWavelength = (min + max) / 2; eoBandObject.FullWidthHalfMax = Math.Round((max - min) / 2, 3); @@ -324,7 +328,7 @@ protected virtual EoBandObject GetEoBandRadianceObject(Schemas.Band_Measurement_ return eoBandObject; } //TODO probably to override for PNEO - protected virtual RasterBand GetRasterBandObject(Schemas.Band_Radiance bandInfo, Schemas.Band_Solar_Irradiance bandSolarIrradiance, Radiometric_Settings radiometric_Settings) + protected virtual RasterBand GetRasterBandObject(Band_Radiance bandInfo, Band_Solar_Irradiance bandSolarIrradiance, Radiometric_Settings radiometric_Settings) { RasterBand rasterBand = new RasterBand(); rasterBand.Statistics = new Stac.Common.Statistics(0, 4096, null, null, null); @@ -354,14 +358,15 @@ protected virtual RasterBand GetRasterBandObject(Schemas.Band_Radiance bandInfo, rasterBand.SetProperty("bcn", GetEoCommonName(bandInfo)); return rasterBand; } - + private EoBandCommonName GetEoCommonName(Band_Radiance bandInfo) { // check if bandinfo is null if (bandInfo == null) return default(EoBandCommonName); - - switch (bandInfo.BAND_ID) { + + switch (bandInfo.BAND_ID) + { case "R": return EoBandCommonName.red; case "G": @@ -405,16 +410,19 @@ internal virtual string GetAssetKey(IAsset bandAsset, Data_File dataFile) string key = Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING; string type = ""; - if (key == "MS-FS" || key == "PMS-FS") { - if (bandAsset.Uri.ToString().Contains("NED")) { + if (key == "MS-FS" || key == "PMS-FS") + { + if (bandAsset.Uri.ToString().Contains("NED")) + { type = "-NED"; } - else if (bandAsset.Uri.ToString().Contains("RGB")) { + else if (bandAsset.Uri.ToString().Contains("RGB")) + { type = "-RGB"; } } - - if (!String.IsNullOrEmpty(dataFile.Tile_R) && !String.IsNullOrEmpty(dataFile.Tile_C)) key += type + "-R" + dataFile.Tile_R + "C" + dataFile.Tile_C; + + if (!string.IsNullOrEmpty(dataFile.Tile_R) && !string.IsNullOrEmpty(dataFile.Tile_C)) key += type + "-R" + dataFile.Tile_R + "C" + dataFile.Tile_C; return key; } @@ -435,4 +443,4 @@ internal virtual StacProvider[] GetStacProviders() return null; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Airbus/PerusatDimapProfiler.cs b/src/Stars.Data/Model/Metadata/Airbus/PerusatDimapProfiler.cs index 9ff12f7e..84a40355 100644 --- a/src/Stars.Data/Model/Metadata/Airbus/PerusatDimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Airbus/PerusatDimapProfiler.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -27,13 +27,13 @@ internal override string GetMission() public override string[] GetSpectralMode() { - string[] possibleModes = new string[] {"P", "MS", "PMS"}; + string[] possibleModes = new string[] { "P", "MS", "PMS" }; List presentModes = new List(); foreach (var dataFiles in Dimap.Raster_Data.Data_Access.Data_Files) { foreach (var dataFile in dataFiles.Data_File) { - string[] parts = dataFile.DATA_FILE_PATH.Href.Split(new char[]{'_', '.'}); + string[] parts = dataFile.DATA_FILE_PATH.Href.Split(new char[] { '_', '.' }); if (parts.Length > 4) { foreach (string m in possibleModes) @@ -50,7 +50,7 @@ public override string[] GetSpectralMode() return presentModes.ToArray(); } - + protected override IDictionary BandOrders { get @@ -80,7 +80,7 @@ internal override string GetProductType() { string pt = GetProcessingLevel(); string rp = Dimap.Processing_Information.Product_Settings.Radiometric_Settings.RADIOMETRIC_PROCESSING; - if (!String.IsNullOrEmpty(rp)) pt += String.Format("/{0}", rp); + if (!string.IsNullOrEmpty(rp)) pt += string.Format("/{0}", rp); return pt; } @@ -91,13 +91,12 @@ internal override string GetProcessingLevel() public override string GetTitle(IDictionary properties) { - string[] spectralMode = GetSpectralMode(); - if (spectralMode == null) spectralMode = new string[0]; + string[] spectralMode = GetSpectralMode() ?? (new string[0]); CultureInfo culture = new CultureInfo("fr-FR"); - return String.Format("{0} {1} {2} {3}", + return string.Format("{0} {1} {2} {3}", properties.GetProperty("platform").ToUpper(), GetProcessingLevel(), - properties.ContainsKey("spectral_mode") ? String.Join(" ", properties.GetProperty("spectral_mode")) : String.Empty, + properties.ContainsKey("spectral_mode") ? string.Join(" ", properties.GetProperty("spectral_mode")) : string.Empty, properties.GetProperty("datetime").ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", culture) ); } @@ -107,7 +106,7 @@ public override double GetResolution() Located_Geometric_Values gv = Dimap.Geometric_Data.Use_Area.Located_Geometric_Values.FirstOrDefault(l => l.LOCATION_TYPE.Equals("center", StringComparison.InvariantCultureIgnoreCase)); if (gv == null) return 0; - if (Double.TryParse(gv.Ground_Sample_Distance.GSD_ACROSS_TRACK, out double across) && Double.TryParse(gv.Ground_Sample_Distance.GSD_ALONG_TRACK, out double along)) + if (double.TryParse(gv.Ground_Sample_Distance.GSD_ACROSS_TRACK, out double across) && double.TryParse(gv.Ground_Sample_Distance.GSD_ALONG_TRACK, out double along)) { return (across + along) / 2; } @@ -123,7 +122,7 @@ internal override StacProvider[] GetStacProviders() return new[] { provider }; } - + internal override string GetAssetKey(IAsset bandAsset, Data_File dataFile) { string key = base.GetAssetKey(bandAsset, dataFile); @@ -134,9 +133,9 @@ internal override string GetAssetKey(IAsset bandAsset, Data_File dataFile) internal override string GetAssetTitle(IAsset bandAsset, Data_File dataFile) { - string title = String.Format("{0} {1}", GetProcessingLevel(), Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING); + string title = string.Format("{0} {1}", GetProcessingLevel(), Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING); return title; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Airbus/PleiadesDimapProfiler.cs b/src/Stars.Data/Model/Metadata/Airbus/PleiadesDimapProfiler.cs index 1eed5565..5e594858 100644 --- a/src/Stars.Data/Model/Metadata/Airbus/PleiadesDimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Airbus/PleiadesDimapProfiler.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Stac; using Stac.Extensions.Eo; @@ -57,4 +57,4 @@ internal override StacProvider[] GetStacProviders() return new[] { provider }; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Airbus/PleiadesNEODimapProfiler.cs b/src/Stars.Data/Model/Metadata/Airbus/PleiadesNEODimapProfiler.cs index f5741ced..5390fe62 100644 --- a/src/Stars.Data/Model/Metadata/Airbus/PleiadesNEODimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Airbus/PleiadesNEODimapProfiler.cs @@ -1,8 +1,7 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Runtime.InteropServices; using Stac; using Stac.Extensions.Eo; using Stac.Extensions.Projection; @@ -32,12 +31,14 @@ internal override string GetMission() get { Dictionary bandOrders = new Dictionary(); - if (Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING == "PMS-X") { + if (Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING == "PMS-X") + { bandOrders.Add(EoBandCommonName.green, 0); bandOrders.Add(EoBandCommonName.red, 1); bandOrders.Add(EoBandCommonName.nir, 2); } - else { + else + { bandOrders.Add(EoBandCommonName.red, 0); bandOrders.Add(EoBandCommonName.green, 1); bandOrders.Add(EoBandCommonName.blue, 2); @@ -56,18 +57,18 @@ public override string GetPlatformInternationalDesignator() //string mission = GetMission().ToLower(); //switch (mission) //{ - //TODO check rational to distinguish the mission vs designator - //case "pleiades-3": - // return "2021-034A"; - //case "pleiades-4": - return "2021-073E"; + //TODO check rational to distinguish the mission vs designator + //case "pleiades-3": + // return "2021-034A"; + //case "pleiades-4": + return "2021-073E"; //} } - + internal override string GetPlatform() { return Dimap.Dataset_Sources.Source_Identification.First().Strip_Source.MISSION - +Dimap.Dataset_Sources.Source_Identification.First().Strip_Source.MISSION_INDEX; + + Dimap.Dataset_Sources.Source_Identification.First().Strip_Source.MISSION_INDEX; } internal override StacProvider[] GetStacProviders() @@ -75,22 +76,23 @@ internal override StacProvider[] GetStacProviders() StacProvider provider1 = new StacProvider("Airbus", new[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }); provider1.Description = "Pléiades Neo is the most advanced optical constellation of Airbus, with two identical 30 cm resolution satellites and optimum reactivity. Pleiades Neo allows users to unleash the potential of geospatial applications and analytics."; provider1.Uri = new Uri("https://www.intelligence-airbusds.com/imagery/constellation/pleiades-neo/"); - + StacProvider provider2 = new StacProvider("CNES", new[] { StacProviderRole.licensor }); - + return new[] { provider1, provider2 }; } public override string[] GetInstruments() { - return new string[1] { "pneo-imager"}; + return new string[1] { "pneo-imager" }; } - - - + + + public override double GetResolution() { - try { + try + { var value1 = double.Parse(Dimap.Geometric_Data.Use_Area.Located_Geometric_Values .FirstOrDefault(l => l.LOCATION_TYPE.Equals("center", StringComparison.InvariantCultureIgnoreCase)) @@ -100,7 +102,7 @@ public override double GetResolution() .FirstOrDefault(l => l.LOCATION_TYPE.Equals("center", StringComparison.InvariantCultureIgnoreCase)) .Ground_Sample_Distance.GSD_ALONG_TRACK); - + // make mean of the two values and round to 2 decimals return Math.Round((value1 + value2) / 2, 2); } @@ -110,44 +112,46 @@ public override double GetResolution() } } - + internal override string GetProcessingLevel() { return Dimap.Processing_Information.Product_Settings.PROCESSING_LEVEL; } - - + + internal override void CompleteAsset(StacAsset stacAsset, StacItem stacItem) { // FOR MS-FS and PMS-FS spectalProcess - + // if the TIF is a NED // return only the bands NIR, REDEDGE, DEEP BLUE - + // if the TIF is a RGB // return only the bands R, G, B Data_Files dataFiles = null; List filterBands = new List(); - if(Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING == "PMS-FS" || Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING == "MS-FS"){ + if (Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING == "PMS-FS" || Dimap.Processing_Information.Product_Settings.SPECTRAL_PROCESSING == "MS-FS") + { // check to what dataFiles the TIF belongs ( NED or RGB ) dataFiles = Dimap.Raster_Data.Data_Access.Data_Files.FirstOrDefault(dfs => dfs.Data_File.FirstOrDefault(df => df.DATA_FILE_PATH.Href.Equals(System.IO.Path.GetFileName(stacAsset.Uri.ToString()), StringComparison.InvariantCultureIgnoreCase)) != null); - if (dataFiles != null) { + if (dataFiles != null) + { filterBands = dataFiles.Raster_Display.Raster_Index_List.Raster_Index; } } - + List eoBandObjects = GetEoBandObjects(stacAsset, Dimap.Radiometric_Data.Radiometric_Calibration.Instrument_Calibration.Band_Measurement_List, - Dimap.Processing_Information.Product_Settings.Radiometric_Settings,filterBands); + Dimap.Processing_Information.Product_Settings.Radiometric_Settings, filterBands); if (eoBandObjects.Count > 0) { stacAsset.EoExtension().Bands = eoBandObjects.ToArray(); } List rasterBandObjects = GetRasterBandObjects(Dimap.Radiometric_Data.Radiometric_Calibration.Instrument_Calibration.Band_Measurement_List, - Dimap.Processing_Information.Product_Settings.Radiometric_Settings,filterBands); + Dimap.Processing_Information.Product_Settings.Radiometric_Settings, filterBands); if (rasterBandObjects.Count > 0) stacAsset.RasterExtension().Bands = rasterBandObjects.ToArray(); @@ -175,44 +179,44 @@ internal override void CompleteAsset(StacAsset stacAsset, StacItem stacItem) { } } - - - - + + + + protected override List GetEoBandObjects(StacAsset stacAsset, Band_Measurement_List spectralBandInfos, Radiometric_Settings radiometricSettings, List filterBands = null) { // FOR MS-FS spectalProcess - + // if the TIF is a NED // return only the bands NIR, REDEDGE, DEEP BLUE - + // if the TIF is a RGB // return only the bands R, G, B - + List eoBandObjects = new List(); for (int i = 0; i < spectralBandInfos.Band_Radiance.Count(); i++) { - + var bandInfo = spectralBandInfos.Band_Radiance[i]; // check if bandInfo is in filterBands - if(filterBands.Any() && !filterBands.Any(b => b.BAND_ID.Equals(bandInfo.BAND_ID))) + if (filterBands.Any() && !filterBands.Any(b => b.BAND_ID.Equals(bandInfo.BAND_ID))) continue; - + var bandSolarIrradiance = spectralBandInfos.Band_Solar_Irradiance[i]; var fwhm = spectralBandInfos.Band_Spectral_Range.FirstOrDefault(b => b.BAND_ID.Equals(bandInfo.BAND_ID)).FWHM; // center_wavelength - double centerWavelength = (fwhm.FWHM_MIN + fwhm.FWHM_MAX) / 2/1000; + double centerWavelength = (fwhm.FWHM_MIN + fwhm.FWHM_MAX) / 2 / 1000; // full_width_half_max - double fullWidthHalfMax = (fwhm.FWHM_MAX - fwhm.FWHM_MIN)/1000; + double fullWidthHalfMax = (fwhm.FWHM_MAX - fwhm.FWHM_MIN) / 1000; EoBandObject eoBandObject = GetEoBandRadianceObject(spectralBandInfos, i); eoBandObject.Properties.Add("full_width_half_max", fullWidthHalfMax); eoBandObject.CenterWavelength = centerWavelength; - + string commonName = eoBandObject.CommonName.ToString(); // commonName with first letter to upper case commonName = eoBandObject.Name = $"{commonName.Substring(0, 1).ToUpper()}{commonName.Substring(1)}"; @@ -220,18 +224,20 @@ protected override List GetEoBandObjects(StacAsset stacAsset, string bandNumber = ""; if (filterBands.Any()) { - bandNumber= $"-B{filterBands.FirstOrDefault(b => b.BAND_ID.Equals(bandInfo.BAND_ID)).BAND_INDEX}"; + bandNumber = $"-B{filterBands.FirstOrDefault(b => b.BAND_ID.Equals(bandInfo.BAND_ID)).BAND_INDEX}"; } // type string type = ""; - if (stacAsset.Uri.ToString().Contains("NED")) { + if (stacAsset.Uri.ToString().Contains("NED")) + { type = "NED"; } - else if (stacAsset.Uri.ToString().Contains("RGB")) { + else if (stacAsset.Uri.ToString().Contains("RGB")) + { type = "RGB"; } - + eoBandObject.Name = $"{type}{bandNumber} {commonName}"; eoBandObjects.Add(eoBandObject); } @@ -239,16 +245,17 @@ protected override List GetEoBandObjects(StacAsset stacAsset, } - internal override string GetId() { + internal override string GetId() + { List bandModes = Dimap.Dataset_Sources.Source_Identification.Select(identification => identification.Strip_Source.BAND_MODE).ToList(); var bandModesString = string.Join("_", bandModes); CultureInfo culture = new CultureInfo("fr-FR"); - var datetime = GetAcquisitionTime().ToUniversalTime().ToString("yyyyMMddHHmmss",culture);; + var datetime = GetAcquisitionTime().ToUniversalTime().ToString("yyyyMMddHHmmss", culture); ; return $"{GetPlatform()}_{datetime}_{bandModesString}_{GetProcessingLevel()}_{Dimap.Product_Information.Delivery_Identification.JOB_ID}_{Dimap.Product_Information.Delivery_Identification.PRODUCT_CODE}"; } - - + + public override string GetTitle(IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); @@ -258,6 +265,6 @@ public override string GetTitle(IDictionary properties) GetProcessingLevel(), properties.GetProperty("datetime").ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", culture)); } - + } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Airbus/SpotDimapProfiler.cs b/src/Stars.Data/Model/Metadata/Airbus/SpotDimapProfiler.cs index db731088..de3941f6 100644 --- a/src/Stars.Data/Model/Metadata/Airbus/SpotDimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Airbus/SpotDimapProfiler.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Stac; using Stac.Extensions.Eo; @@ -56,4 +56,4 @@ internal override StacProvider[] GetStacProviders() return new[] { provider }; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Airbus/VolumeDimapProfiler.cs b/src/Stars.Data/Model/Metadata/Airbus/VolumeDimapProfiler.cs index 59f9ce5a..ecfbb4e4 100644 --- a/src/Stars.Data/Model/Metadata/Airbus/VolumeDimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Airbus/VolumeDimapProfiler.cs @@ -1,13 +1,9 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using System.Xml; -using System.Xml.Serialization; -using Stac; using Stac.Extensions.Eo; using Terradue.Stars.Data.Model.Metadata.Airbus.Schemas; -using Terradue.Stars.Data.Utils; using Terradue.Stars.Interface; using Terradue.Stars.Services.Model.Stac; @@ -17,7 +13,7 @@ internal class VolumeDimapProfiler : AirbusProfiler { private readonly AirbusMetadataExtractor airbusMetadataExtractor; - public VolumeDimapProfiler(Schemas.Dimap_Document dimap, AirbusMetadataExtractor airbusMetadataExtractor) : base(dimap) + public VolumeDimapProfiler(Dimap_Document dimap, AirbusMetadataExtractor airbusMetadataExtractor) : base(dimap) { this.airbusMetadataExtractor = airbusMetadataExtractor; } @@ -50,4 +46,4 @@ internal async Task> GetDatasets(IItem item, string su } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Alos2/Alos2MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Alos2/Alos2MetadataExtractor.cs index b039e948..622128b0 100644 --- a/src/Stars.Data/Model/Metadata/Alos2/Alos2MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Alos2/Alos2MetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -13,10 +13,10 @@ using Stac.Extensions.Sar; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Alos2 { @@ -31,8 +31,7 @@ public Alos2MetadataExtractor(ILogger logger, IResourceS public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset metadataAsset = GetMetadataAsset(item); @@ -123,7 +122,7 @@ private void AddProcessingStacExtension(Alos2Metadata metadata, StacItem stacIte private string GetProcessingLevel(Alos2Metadata metadata) { - return String.Format("L{0}", metadata.GetString("Lbi_ProcessLevel")); + return string.Format("L{0}", metadata.GetString("Lbi_ProcessLevel")); } private IDictionary GetCommonMetadata(Alos2Metadata metadata) @@ -180,11 +179,11 @@ private void FillInstrument(Alos2Metadata metadata, Dictionary p } - private void FillBasicsProperties(Alos2Metadata metadata, IDictionary properties) + private void FillBasicsProperties(Alos2Metadata metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title - properties["title"] = String.Format("ALOS-2 PALSAR-2 {0} L{1} {2} {3}", + properties["title"] = string.Format("ALOS-2 PALSAR-2 {0} L{1} {2} {3}", metadata.GetString("Ext_ObservationMode"), metadata.GetString("Lbi_ProcessLevel"), metadata.GetString("Ext_Polarizations"), @@ -199,7 +198,7 @@ private void AddOtherProperties(Alos2Metadata metadata, StacItem stacItem) { AddSingleProvider( stacItem.Properties, - "JAXA", + "JAXA", "The Advanced Land Observing Satellite-2 is a follow-on mission from the ALOS. ALOS has contributed to cartography, regional observation, disaster monitoring, and resource surveys, since its launch in 2006. ALOS-2 will succeed this mission with enhanced capabilities.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.eorc.jaxa.jp/ALOS/en/alos-2/a2_about_e.htm") @@ -247,20 +246,18 @@ protected void AddAssets(StacItem stacItem, IItem item, Alos2Metadata metadata) foreach (var fileName in metadata.Assets) { - IAsset dataAsset = FindFirstAssetFromFileNameRegex(item, String.Format("{0}$", fileName.Replace(".", "\\."))); - if (dataAsset == null) - throw new FileNotFoundException(string.Format("Data file '{0}' declared in summary, but not present", fileName)); + IAsset dataAsset = FindFirstAssetFromFileNameRegex(item, string.Format("{0}$", fileName.Replace(".", "\\."))) ?? throw new FileNotFoundException(string.Format("Data file '{0}' declared in summary, but not present", fileName)); string polarization = fileName.Substring(4, 2); string key, contentType, title; if (fileName.EndsWith(".tif")) // (IMG_*.tif) { - key = String.Format("amplitude-{0}", polarization.ToLower()); + key = string.Format("amplitude-{0}", polarization.ToLower()); contentType = "image/tiff; application=geotiff"; title = "GeoTIFF data file"; } else // (LUT_*.txt) { - key = String.Format("lut-{0}", polarization.ToLower()); + key = string.Format("lut-{0}", polarization.ToLower()); contentType = "text/plain"; title = "Pixel value to Sigma Naught Conversion factors"; } @@ -292,12 +289,7 @@ private double GetGroundSampleDistance(string mode) protected virtual IAsset GetMetadataAsset(IItem item) { - IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"summary\.txt$"); - //Console.WriteLine("SUMMARY: {0}", manifestAsset == null ? "NULL" : manifestAsset.Title); - if (manifestAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the summary file asset")); - } + IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"summary\.txt$") ?? throw new FileNotFoundException(string.Format("Unable to find the summary file asset")); return manifestAsset; } @@ -343,7 +335,7 @@ public class Alos2Metadata public Alos2Metadata(IAsset summaryAsset) { this.summaryAsset = summaryAsset; - this.properties = new Dictionary(); + properties = new Dictionary(); Assets = new List(); } @@ -386,7 +378,7 @@ public async Task ReadMetadata(IResourceServiceProvider resourceServiceProvider) } } - properties["Ext_Identifier"] = String.Format("{0}-{1}", properties["Scs_SceneID"], properties["Pds_ProductID"]); + properties["Ext_Identifier"] = string.Format("{0}-{1}", properties["Scs_SceneID"], properties["Pds_ProductID"]); Match identifierMatch = identifierRegex.Match(properties["Ext_Identifier"]); if (!identifierMatch.Success) @@ -407,7 +399,7 @@ public async Task ReadMetadata(IResourceServiceProvider resourceServiceProvider) properties["Ext_OrbitDirection"] = identifierMatch.Groups["orbitdir"].Value == "A" ? "ASCENDING" : "DESCENDING"; // Polarization(s), combined by slash(es) if multiple - properties["Ext_Polarizations"] = String.Join("/", polarizations); + properties["Ext_Polarizations"] = string.Join("/", polarizations); Match siteMatch = siteRegex.Match(properties["Odi_SiteDateTime"]); if (siteMatch.Success) @@ -433,7 +425,7 @@ public string GetString(string key, bool throwIfMissing = true) { return properties[key]; } - if (throwIfMissing) throw new Exception(String.Format("No value for key '{0}'", key)); + if (throwIfMissing) throw new Exception(string.Format("No value for key '{0}'", key)); return null; } @@ -441,12 +433,12 @@ public int GetInt32(string key, bool throwIfMissing = true) { if (properties.ContainsKey(key)) { - if (Int32.TryParse(properties[key], out int value)) + if (int.TryParse(properties[key], out int value)) return value; else - throw new FormatException(String.Format("Invalid value for key '{0}' (not an int)", key)); + throw new FormatException(string.Format("Invalid value for key '{0}' (not an int)", key)); } - if (throwIfMissing) throw new Exception(String.Format("No value for key '{0}'", key)); + if (throwIfMissing) throw new Exception(string.Format("No value for key '{0}'", key)); return 0; } @@ -454,12 +446,12 @@ public long GetInt64(string key, bool throwIfMissing = true) { if (properties.ContainsKey(key)) { - if (Int64.TryParse(properties[key], out long value)) + if (long.TryParse(properties[key], out long value)) return value; else - throw new FormatException(String.Format("Invalid value for key '{0}' (not a long)", key)); + throw new FormatException(string.Format("Invalid value for key '{0}' (not a long)", key)); } - if (throwIfMissing) throw new Exception(String.Format("No value for key '{0}'", key)); + if (throwIfMissing) throw new Exception(string.Format("No value for key '{0}'", key)); return 0; } @@ -467,12 +459,12 @@ public double GetDouble(string key, bool throwIfMissing = true) { if (properties.ContainsKey(key)) { - if (Double.TryParse(properties[key], out double value)) + if (double.TryParse(properties[key], out double value)) return value; else - throw new FormatException(String.Format("Invalid value for key '{0}' (not a double)", key)); + throw new FormatException(string.Format("Invalid value for key '{0}' (not a double)", key)); } - if (throwIfMissing) throw new Exception(String.Format("No value for key '{0}'", key)); + if (throwIfMissing) throw new Exception(string.Format("No value for key '{0}'", key)); return 0; } @@ -488,7 +480,7 @@ public DateTime GetDateTime(string key, int[] positions = null, bool throwIfMiss } else if (positions.Length >= 3) { - input = String.Format("{0}-{1}-{2}T{3}:{4}:{5}Z", + input = string.Format("{0}-{1}-{2}T{3}:{4}:{5}Z", raw.Substring(positions[0], 4), raw.Substring(positions[1], 2), raw.Substring(positions[2], 2), @@ -499,14 +491,14 @@ public DateTime GetDateTime(string key, int[] positions = null, bool throwIfMiss } else { - throw new FormatException(String.Format("Invalid format expectation for key '{0}' (not a date/time)", key)); + throw new FormatException(string.Format("Invalid format expectation for key '{0}' (not a date/time)", key)); } if (DateTime.TryParse(input, null, DateTimeStyles.AssumeUniversal, out DateTime value)) return value; else - throw new FormatException(String.Format("Invalid value for key '{0}' (not a date/time)", key)); + throw new FormatException(string.Format("Invalid value for key '{0}' (not a date/time)", key)); } - if (throwIfMissing) throw new Exception(String.Format("No value for key '{0}'", key)); + if (throwIfMissing) throw new Exception(string.Format("No value for key '{0}'", key)); return DateTime.MinValue; } } diff --git a/src/Stars.Data/Model/Metadata/Bka/BkaMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Bka/BkaMetadataExtractor.cs index eb0e2c2c..0cb72fb2 100644 --- a/src/Stars.Data/Model/Metadata/Bka/BkaMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Bka/BkaMetadataExtractor.cs @@ -3,27 +3,26 @@ using System.Globalization; using System.IO; using System.IO.Abstractions; -using System.Linq; using System.Net.Mime; using System.Threading.Tasks; +using System.Xml; +using System.Xml.Serialization; using GeoJSON.Net.Geometry; using Microsoft.Extensions.Logging; using Stac; using Stac.Extensions.Eo; using Stac.Extensions.Processing; using Stac.Extensions.Projection; +using Stac.Extensions.Raster; +using Stac.Extensions.Sat; +using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Services.Processing; using Terradue.Stars.Services.Supplier.Carrier; using Terradue.Stars.Services.Supplier.Destination; -using System.Xml; -using System.Xml.Serialization; -using Stac.Extensions.Sat; -using Stac.Extensions.View; -using Stac.Extensions.Raster; @@ -47,8 +46,7 @@ public BkaMetadataExtractor(ILogger logger, IResourceServi public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset[] metadataAssets = GetMetadataAssets(item); @@ -86,7 +84,8 @@ protected override async Task ExtractMetadata(IItem item, string suffi ZipArchiveAsset productZipArchiveAsset = new ZipArchiveAsset(productZipAsset, logger, resourceServiceProvider, _fileSystem); var tmpDestination2 = LocalFileDestination.Create(_fileSystem.Directory.CreateDirectory(Path.GetDirectoryName(productZipArchiveAsset.Uri.AbsolutePath)), item, true); IAssetsContainer productZipAssets = await productZipArchiveAsset.ExtractToDestinationAsync(tmpDestination2, _carrierManager, System.Threading.CancellationToken.None); - if (productZipAssets != null) { + if (productZipAssets != null) + { IEnumerable innerZipAssets = GetInnerZipAssets(productZipAssets); if (innerZipAssets != null) { @@ -104,13 +103,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi } - IAsset[] metadataAssets = GetMetadataAssets(item, innerZipAssetContainers); - - if (metadataAssets == null) - { - throw new Exception("No metadata assets found"); - } - + IAsset[] metadataAssets = GetMetadataAssets(item, innerZipAssetContainers) ?? throw new Exception("No metadata assets found"); BkaMetadata[] metadata = await ReadMetadata(metadataAssets); StacItem stacItem = CreateStacItem(metadata); @@ -124,7 +117,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi internal virtual StacItem CreateStacItem(BkaMetadata[] metadata) { bool multipleProducts = metadata.Length > 1; - string identifier = metadata[0].Processing.Scene01FileName.Replace(".tif", String.Empty); + string identifier = metadata[0].Processing.Scene01FileName.Replace(".tif", string.Empty); if (multipleProducts) { identifier = identifier.Replace("-MUL-", "-").Replace("-PAN-", "-"); @@ -219,7 +212,7 @@ private string GetProcessingLevel(BkaMetadata[] metadata) { if (metadata[0].Processing?.Level != null) { - return String.Format("L1{0}", metadata[0].Processing.Level); + return string.Format("L1{0}", metadata[0].Processing.Level); } return null; } @@ -236,7 +229,7 @@ private string GetSpectralMode(BkaMetadata[] metadata) { if (m.Processing?.Instrument != null) { - if (spectralMode == null) spectralMode = String.Empty; + if (spectralMode == null) spectralMode = string.Empty; else spectralMode += "/"; spectralMode += m.Processing.Instrument; } @@ -256,7 +249,7 @@ private IDictionary GetCommonMetadata(BkaMetadata[] metadata) return properties; } - private void FillBasicsProperties(BkaMetadata[] metadata, IDictionary properties) + private void FillBasicsProperties(BkaMetadata[] metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -272,7 +265,7 @@ private void FillBasicsProperties(BkaMetadata[] metadata, IDictionary properties = item.Properties; + IDictionary properties = item.Properties; if (IncludeProviderProperty) { AddSingleProvider( @@ -315,14 +308,16 @@ private void FillDateTimeProperties(BkaMetadata[] metadata, Dictionary SE or SE -> NW @@ -371,16 +366,16 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometry(BkaMetadata[] metadata) } - List positions = new List + List positions = new List { - new GeoJSON.Net.Geometry.Position(swLat, swLon), - new GeoJSON.Net.Geometry.Position(seLat, seLon), - new GeoJSON.Net.Geometry.Position(neLat, neLon), - new GeoJSON.Net.Geometry.Position(nwLat, nwLon), - new GeoJSON.Net.Geometry.Position(swLat, swLon) + new Position(swLat, swLon), + new Position(seLat, seLon), + new Position(neLat, neLon), + new Position(nwLat, nwLon), + new Position(swLat, swLon) }; - GeoJSON.Net.Geometry.LineString lineString = new GeoJSON.Net.Geometry.LineString(positions.ToArray()); - return new GeoJSON.Net.Geometry.Polygon(new GeoJSON.Net.Geometry.LineString[] { lineString }).NormalizePolygon(); + LineString lineString = new LineString(positions.ToArray()); + return new Polygon(new LineString[] { lineString }).NormalizePolygon(); } @@ -408,7 +403,7 @@ protected void AddAssets(StacItem stacItem, IItem item, IAssetsContainer[] asset StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, imageAsset.Uri, new ContentType("image/tiff; application=geotiff")); stacAsset.Roles.Add("dn"); - string key = String.Format("{0}_{1}", + string key = string.Format("{0}_{1}", GetProcessingLevel(metadata), subProductMetadata.Processing?.Instrument ); @@ -425,11 +420,11 @@ protected void AddAssets(StacItem stacItem, IItem item, IAssetsContainer[] asset stacItem.Assets.Add(key, stacAsset); } - string suffix = (assetContainers.Length == 1) ? String.Empty : String.Format("_{0}", subProductMetadata.Processing?.Instrument); + string suffix = (assetContainers.Length == 1) ? string.Empty : string.Format("_{0}", subProductMetadata.Processing?.Instrument); if (metadataAsset != null) { StacAsset stacAsset = StacAsset.CreateMetadataAsset(stacItem, metadataAsset.Uri, new ContentType(MimeTypes.GetMimeType(metadataAsset.Uri.ToString()))); - stacItem.Assets.Add(String.Format("metadata{0}", suffix), stacAsset); + stacItem.Assets.Add(string.Format("metadata{0}", suffix), stacAsset); stacAsset.Properties.AddRange(metadataAsset.Properties); } @@ -438,7 +433,7 @@ protected void AddAssets(StacItem stacItem, IItem item, IAssetsContainer[] asset { StacAsset stacAsset = StacAsset.CreateOverviewAsset(stacItem, overviewAsset.Uri, new ContentType(MimeTypes.GetMimeType(overviewAsset.Uri.ToString()))); stacAsset.Properties.AddRange(overviewAsset.Properties); - stacItem.Assets.Add(String.Format("overview{0}", suffix), stacAsset); + stacItem.Assets.Add(string.Format("overview{0}", suffix), stacAsset); } } } @@ -562,7 +557,7 @@ protected virtual IAsset GetProductZipAsset(IAsset topAsset, IAssetsContainer co protected virtual IEnumerable GetInnerZipAssets(IAssetsContainer container) { - IEnumerable zipAssets = this.FindAssetsFromFileNameRegex(container, @".*\.zip"); + IEnumerable zipAssets = FindAssetsFromFileNameRegex(container, @".*\.zip"); return zipAssets; } @@ -586,4 +581,4 @@ public virtual async Task ReadMetadata(IEnumerable metada return metadata.ToArray(); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Bka/Schema.cs b/src/Stars.Data/Model/Metadata/Bka/Schema.cs index 6565042b..f9e24fa8 100644 --- a/src/Stars.Data/Model/Metadata/Bka/Schema.cs +++ b/src/Stars.Data/Model/Metadata/Bka/Schema.cs @@ -1,4 +1,4 @@ -using System.Xml.Serialization; +using System.Xml.Serialization; namespace Terradue.Stars.Data.Model.Metadata.Bka { @@ -20,16 +20,16 @@ public class BkaMetadata public BkaProcessing Processing { get; set; } [XmlElement(ElementName = "Satellite_Data")] - public BkaSatelliteData SatelliteData { get; set; } + public BkaSatelliteData SatelliteData { get; set; } [XmlElement(ElementName = "Radiometry")] - public BkaRadiometry Radiometry { get; set; } + public BkaRadiometry Radiometry { get; set; } [XmlElement(ElementName = "Geo_Reference")] - public BkaGeoReference GeoReference { get; set; } + public BkaGeoReference GeoReference { get; set; } [XmlElement(ElementName = "Image_Info")] - public BkaImageInfo ImageInfo { get; set; } + public BkaImageInfo ImageInfo { get; set; } } [XmlRoot(ElementName = "Production")] @@ -394,6 +394,6 @@ public class BkaImageResample { [XmlElement(ElementName = "Method")] public string Method { get; set; } - } + } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/BlackSkyGlobal/BlackSkyGlobalMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/BlackSkyGlobal/BlackSkyGlobalMetadataExtractor.cs index 18901233..b4e62672 100644 --- a/src/Stars.Data/Model/Metadata/BlackSkyGlobal/BlackSkyGlobalMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/BlackSkyGlobal/BlackSkyGlobalMetadataExtractor.cs @@ -1,27 +1,24 @@ -using System; +using System; using System.Collections.Generic; -using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Mime; using System.Text.RegularExpressions; using System.Threading.Tasks; -using System.Xml; using System.Xml.Serialization; using Microsoft.Extensions.Logging; -using ProjNet.CoordinateSystems; +using Newtonsoft.Json; using Stac; +using Stac.Extensions.Eo; using Stac.Extensions.Processing; using Stac.Extensions.Projection; -using Stac.Extensions.Eo; +using Stac.Extensions.Raster; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -using Stac.Extensions.Raster; -using Newtonsoft.Json; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.BlackSkyGlobal { @@ -50,7 +47,7 @@ public class BlackSkyGlobalMetadataExtractor : MetadataExtraction private static Regex satNumberRegex = new Regex(@".+?(?'n'\d+)$"); public static XmlSerializer metadataSerializer = new XmlSerializer(typeof(Schemas.Metadata)); - + public override string Label => "COSMO SkyMed (ASI) mission product metadata extractor"; public BlackSkyGlobalMetadataExtractor(ILogger logger, IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) @@ -59,10 +56,9 @@ public BlackSkyGlobalMetadataExtractor(ILogger public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try - { + { IAsset metadataAsset = GetMetadataAsset(item); Schemas.Metadata metadata = ReadMetadata(metadataAsset).GetAwaiter().GetResult(); @@ -96,14 +92,10 @@ protected override async Task ExtractMetadata(IItem item, string suffi protected virtual IAsset GetMetadataAsset(IItem item) { - IAsset metadataAsset = FindFirstAssetFromFileNameRegex(item, @"BSG.*\.json$"); - if (metadataAsset == null) - { - metadataAsset = FindFirstAssetFromFileNameRegex(item, @"BS.*\.txt$"); - } + IAsset metadataAsset = FindFirstAssetFromFileNameRegex(item, @"BSG.*\.json$") ?? FindFirstAssetFromFileNameRegex(item, @"BS.*\.txt$"); if (metadataAsset == null) { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); + throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); } return metadataAsset; } @@ -136,7 +128,7 @@ protected virtual IAsset GetMetadataAsset(IItem item) internal virtual StacItem CreateStacItem(Schemas.Metadata metadata, IItem item) { - string suffix = String.Empty; + string suffix = string.Empty; if (!metadata.id.Contains("ortho")) { suffix = GetProcessingLevel(metadata, item); @@ -144,7 +136,7 @@ internal virtual StacItem CreateStacItem(Schemas.Metadata metadata, IItem item) else suffix = "_non-ortho"; } - string identifier = String.Format("{0}{1}", metadata.id, suffix); + string identifier = string.Format("{0}{1}", metadata.id, suffix); Dictionary properties = new Dictionary(); FillDateTimeProperties(properties, metadata); @@ -152,7 +144,7 @@ internal virtual StacItem CreateStacItem(Schemas.Metadata metadata, IItem item) FillBasicsProperties(properties, metadata, item); StacItem stacItem = new StacItem(identifier, GetGeometry(metadata), properties); - + return stacItem; } @@ -166,7 +158,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat stacItem.Assets["metadata"].Properties.AddRange(metadataAsset.Properties); // Overview/browse - IAsset browseAsset = FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_browse\.png$", metadata.id)); + IAsset browseAsset = FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_browse\.png$", metadata.id)); if (browseAsset != null) { stacItem.Assets.Add("overview", StacAsset.CreateOverviewAsset(stacItem, browseAsset.Uri, new ContentType("image/png"), "Browse image")); @@ -174,7 +166,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat } // RGB TIFF (ortho) - IAsset imageAsset = metadata.IsFromText && metadata.id.EndsWith("_ortho") ? FindFirstAssetFromFileNameRegex(item, @".*\.tif") : FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_ortho\.tif$", metadata.id)); + IAsset imageAsset = metadata.IsFromText && metadata.id.EndsWith("_ortho") ? FindFirstAssetFromFileNameRegex(item, @".*\.tif") : FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_ortho\.tif$", metadata.id)); if (imageAsset != null) { @@ -195,7 +187,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat } // PAN TIFF (ortho) - IAsset imageAssetPan = metadata.IsFromText && metadata.id.EndsWith("_ortho-pan") ? FindFirstAssetFromFileNameRegex(item, @".*\.tif") : FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_ortho-pan\.tif$", metadata.id)); + IAsset imageAssetPan = metadata.IsFromText && metadata.id.EndsWith("_ortho-pan") ? FindFirstAssetFromFileNameRegex(item, @".*\.tif") : FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_ortho-pan\.tif$", metadata.id)); if (imageAssetPan != null) { StacAsset stacAssetPan = StacAsset.CreateDataAsset(stacItem, imageAssetPan.Uri, new ContentType("image/tiff; application=geotiff"), "PAN image"); @@ -211,7 +203,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat } // RGB TIFF (non-ortho) - imageAsset = metadata.IsFromText && metadata.id.EndsWith("_georeferenced") ? FindFirstAssetFromFileNameRegex(item, @".*\.tif") : FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_georeferenced\.tif$", metadata.id)); + imageAsset = metadata.IsFromText && metadata.id.EndsWith("_georeferenced") ? FindFirstAssetFromFileNameRegex(item, @".*\.tif") : FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_georeferenced\.tif$", metadata.id)); if (imageAsset != null) { StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, imageAsset.Uri, new ContentType("image/tiff; application=geotiff"), "RGB image"); @@ -231,7 +223,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat } // PAN TIFF (non-ortho) - imageAssetPan = metadata.IsFromText && metadata.id.EndsWith("_georeferenced-pan") ? FindFirstAssetFromFileNameRegex(item, @".*\.tif") : FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_georeferenced-pan\.tif$", metadata.id)); + imageAssetPan = metadata.IsFromText && metadata.id.EndsWith("_georeferenced-pan") ? FindFirstAssetFromFileNameRegex(item, @".*\.tif") : FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_georeferenced-pan\.tif$", metadata.id)); if (imageAssetPan != null) { StacAsset stacAssetPan = StacAsset.CreateDataAsset(stacItem, imageAssetPan.Uri, new ContentType("image/tiff; application=geotiff"), "PAN image"); @@ -247,7 +239,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat } // Mask TIFF (non-ortho) - IAsset imageAssetMask = FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_mask\.tif$", metadata.id)); + IAsset imageAssetMask = FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_mask\.tif$", metadata.id)); if (imageAssetMask != null) { StacAsset stacAssetMask = StacAsset.CreateDataAsset(stacItem, imageAssetMask.Uri, new ContentType("image/tiff; application=geotiff"), "Mask file"); @@ -257,7 +249,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat } // RGB RPC (non-ortho) - IAsset rpcAsset = FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_georeferenced_rpc\.txt$", metadata.id)); + IAsset rpcAsset = FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_georeferenced_rpc\.txt$", metadata.id)); if (rpcAsset != null) { StacAsset stacAssetRpc = StacAsset.CreateMetadataAsset(stacItem, rpcAsset.Uri, new ContentType("text/plain"), "RPC (RGB)"); @@ -266,7 +258,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat } // PAN RPC (non-ortho) - rpcAsset = FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_georeferenced-pan_rpc\.txt$", metadata.id)); + rpcAsset = FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_georeferenced-pan_rpc\.txt$", metadata.id)); if (rpcAsset != null) { StacAsset stacAssetRpc = StacAsset.CreateMetadataAsset(stacItem, rpcAsset.Uri, new ContentType("text/plain"), "RPC (PAN)"); @@ -275,7 +267,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat } // Mask RPC (non-ortho) - rpcAsset = FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_mask_rpc\.txt$", metadata.id)); + rpcAsset = FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_mask_rpc\.txt$", metadata.id)); if (rpcAsset != null) { StacAsset stacAssetRpc = StacAsset.CreateMetadataAsset(stacItem, rpcAsset.Uri, new ContentType("text/plain"), "RPC (mask)"); @@ -299,7 +291,7 @@ private void FillDateTimeProperties(Dictionary properties, Schem private void FillInstrument(Dictionary properties, Schemas.Metadata metadata, IItem item) { // platform & constellation - + properties["agency"] = "BlackSky"; properties["platform"] = metadata.sensorName.ToLower(); properties["constellation"] = "blacksky-global"; @@ -320,26 +312,26 @@ private string GetSpectralMode(Schemas.Metadata metadata, IItem item) if (metadata.spectralMode == "MS") return "MS"; if (metadata.spectralMode.Contains("MS") && metadata.spectralMode.Contains("MS")) return "PAN/MS"; } - - bool pan = FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_ortho-pan\.tif$", metadata.id)) != null || FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_georeferenced-pan\.tif$", metadata.id)) != null; - bool ms = FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_ortho\.tif$", metadata.id)) != null || FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_georeferenced\.tif$", metadata.id)) != null; - return String.Format("{0}{1}{2}", pan ? "PAN" : String.Empty, pan && ms ? "/": String.Empty, ms ? "MS" : String.Empty); + bool pan = FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_ortho-pan\.tif$", metadata.id)) != null || FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_georeferenced-pan\.tif$", metadata.id)) != null; + bool ms = FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_ortho\.tif$", metadata.id)) != null || FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_georeferenced\.tif$", metadata.id)) != null; + + return string.Format("{0}{1}{2}", pan ? "PAN" : string.Empty, pan && ms ? "/" : string.Empty, ms ? "MS" : string.Empty); } - private void FillBasicsProperties(IDictionary properties, Schemas.Metadata metadata, IItem item) + private void FillBasicsProperties(IDictionary properties, Schemas.Metadata metadata, IItem item) { DateTime? acquisitionDate = GetAcquisitionDateTime(metadata); - string dateStr = (acquisitionDate != null ? String.Format(" {0:yyyy-MM-dd HH:mm:ss}", acquisitionDate.Value.ToUniversalTime()) : String.Empty); + string dateStr = (acquisitionDate != null ? string.Format(" {0:yyyy-MM-dd HH:mm:ss}", acquisitionDate.Value.ToUniversalTime()) : string.Empty); CultureInfo culture = new CultureInfo("fr-FR"); string processingLevel = GetProcessingLevel(metadata, item); - if (processingLevel == null) processingLevel = String.Empty; - else processingLevel = String.Format(" {0}", processingLevel); + if (processingLevel == null) processingLevel = string.Empty; + else processingLevel = string.Format(" {0}", processingLevel); string spectralMode = GetSpectralMode(metadata, item); - if (spectralMode == null) spectralMode = String.Empty; - else spectralMode = String.Format(" {0}", spectralMode.Replace("/", " ")); - properties["title"] = String.Format("BLACKSY {0}{1}{2}", + if (spectralMode == null) spectralMode = string.Empty; + else spectralMode = string.Format(" {0}", spectralMode.Replace("/", " ")); + properties["title"] = string.Format("BLACKSY {0}{1}{2}", metadata.sensorName.ToUpper(), processingLevel, spectralMode, @@ -353,7 +345,7 @@ private void AddOtherProperties(StacItem stacItem, Schemas.Metadata metadata) { AddSingleProvider( stacItem.Properties, - "BlackSky", + "BlackSky", "BlackSky Constellation is a commercially owned and operated constellation of 60 high resolution imaging microsatellites developed by BlackSky Global. The constellation aims to provide higher temporal resolution and lower cost Earth imaging, and currently contains 17 operational microsatellites, each with an expected lifetime of 4 years.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.blacksky.com") @@ -365,15 +357,15 @@ private void AddOtherProperties(StacItem stacItem, Schemas.Metadata metadata) private void AddSatStacExtension(StacItem stacItem, Schemas.Metadata metadata) { var sat = new SatStacExtension(stacItem); - if (!String.IsNullOrEmpty("")) + if (!string.IsNullOrEmpty("")) { Match match = satNumberRegex.Match(""); - if (match != null && Int32.TryParse(match.Groups["n"].Value, out int n) && platformDesignators.ContainsKey(n)) + if (match != null && int.TryParse(match.Groups["n"].Value, out int n) && platformDesignators.ContainsKey(n)) { sat.PlatformInternationalDesignator = platformDesignators[n]; } } - + } @@ -459,8 +451,8 @@ private string GetProcessingLevel(Schemas.Metadata metadata, IItem item) if (metadata.processLevel == "O") return "ORTHO"; if (metadata.processLevel == "G") return "GEO"; } - if (FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_ortho\.tif$", metadata.id)) != null) return "ORTHO"; - if (FindFirstAssetFromFileNameRegex(item, String.Format(@"{0}_georeferenced\.tif$", metadata.id)) != null) return "GEO"; + if (FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_ortho\.tif$", metadata.id)) != null) return "ORTHO"; + if (FindFirstAssetFromFileNameRegex(item, string.Format(@"{0}_georeferenced\.tif$", metadata.id)) != null) return "GEO"; return null; } diff --git a/src/Stars.Data/Model/Metadata/BlackSkyGlobal/Schemas/Metadata.cs b/src/Stars.Data/Model/Metadata/BlackSkyGlobal/Schemas/Metadata.cs index ed2f150d..d123f357 100644 --- a/src/Stars.Data/Model/Metadata/BlackSkyGlobal/Schemas/Metadata.cs +++ b/src/Stars.Data/Model/Metadata/BlackSkyGlobal/Schemas/Metadata.cs @@ -1,12 +1,13 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; -namespace Terradue.Stars.Data.Model.Metadata.BlackSkyGlobal.Schemas { +namespace Terradue.Stars.Data.Model.Metadata.BlackSkyGlobal.Schemas +{ - public partial class Metadata { + public partial class Metadata + { private bool isFromText = false; @@ -15,7 +16,8 @@ public partial class Metadata { "LL_LONG", "LL_LAT", "LR_LONG", "LR_LAT", "UR_LONG", "UR_LAT", "UL_LONG", "UL_LAT" }; - public bool IsFromText { + public bool IsFromText + { get { return isFromText; } set { isFromText = value; } } @@ -78,30 +80,30 @@ public static Metadata FromTextFile(StreamReader reader) string fileName = GetStringValue(textMetadata, "ENTITY_ID"); if (fileName != null && fileName.StartsWith("BS")) platformNumber = fileName.Substring(2, 2).TrimStart('0'); } - metadata.sensorName = String.Format("Global-{0}", platformNumber); + metadata.sensorName = string.Format("Global-{0}", platformNumber); metadata.spectralMode = GetStringValue(textMetadata, "SENSOR_TYPE"); string acquisitionDate = GetStringValue(textMetadata, "ACQUISITION_DATE"); - if (!String.IsNullOrEmpty(acquisitionDate)) + if (!string.IsNullOrEmpty(acquisitionDate)) { - if (acquisitionDate.Length == 8) acquisitionDate = String.Format("{0}-{1}-{2}", acquisitionDate.Substring(0, 4), acquisitionDate.Substring(4, 2), acquisitionDate.Substring(6, 2)); + if (acquisitionDate.Length == 8) acquisitionDate = string.Format("{0}-{1}-{2}", acquisitionDate.Substring(0, 4), acquisitionDate.Substring(4, 2), acquisitionDate.Substring(6, 2)); string acquisitionTime = GetStringValue(textMetadata, "ACQUISITION_TIME"); - if (String.IsNullOrEmpty(acquisitionTime)) + if (string.IsNullOrEmpty(acquisitionTime)) { acquisitionTime = "00:00:00"; } else { - if (acquisitionTime.Length == 6) acquisitionTime = String.Format("{0}:{1}:{2}", acquisitionTime.Substring(0, 2), acquisitionTime.Substring(2, 2), acquisitionTime.Substring(4, 2)); + if (acquisitionTime.Length == 6) acquisitionTime = string.Format("{0}:{1}:{2}", acquisitionTime.Substring(0, 2), acquisitionTime.Substring(2, 2), acquisitionTime.Substring(4, 2)); } acquisitionTime = acquisitionTime.Replace("Z", ""); - metadata.acquisitionDate = String.Format("{0}T{1}Z", acquisitionDate, acquisitionTime); + metadata.acquisitionDate = string.Format("{0}T{1}Z", acquisitionDate, acquisitionTime); } metadata.gsd = 1; // hardcoded List coordinates = new List(); foreach (string name in cornerCoordinateNames) { - if (Double.TryParse(GetStringValue(textMetadata, name), out double value)) coordinates.Add(value); + if (double.TryParse(GetStringValue(textMetadata, name), out double value)) coordinates.Add(value); } if (coordinates.Count == 8) { @@ -122,7 +124,7 @@ public static Metadata FromTextFile(StreamReader reader) metadata.sunElevation = GetDoubleValue(textMetadata, "SUN_ELEVATION"); metadata.sunAzimuth = GetDoubleValue(textMetadata, "SUN_AZIMUTH"); metadata.satelliteElevation = GetDoubleValue(textMetadata, "SAT_ELEVATION"); - metadata.satelliteAzimuth= GetDoubleValue(textMetadata, "SAT_AZIMUTH"); + metadata.satelliteAzimuth = GetDoubleValue(textMetadata, "SAT_AZIMUTH"); //metadata.georeferenced= ""; //metadata.orthorectified= ""; //metadata.width= ""; @@ -152,7 +154,7 @@ public static string GetStringValue(Dictionary dict, string key) { if (dict.ContainsKey(key)) { - if (Double.TryParse(dict[key], out double value)) return value; + if (double.TryParse(dict[key], out double value)) return value; } return null; } @@ -160,7 +162,8 @@ public static string GetStringValue(Dictionary dict, string key) } - public partial class GeminiType { + public partial class GeminiType + { public string catalogImageId { get; set; } public string imageId { get; set; } } diff --git a/src/Stars.Data/Model/Metadata/CosmoSkymed/CosmoSkymedMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/CosmoSkymed/CosmoSkymedMetadataExtractor.cs index 94a42c31..295f6dca 100644 --- a/src/Stars.Data/Model/Metadata/CosmoSkymed/CosmoSkymedMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/CosmoSkymed/CosmoSkymedMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -10,16 +10,15 @@ using System.Xml.Serialization; using Microsoft.Extensions.Logging; using Stac; -using Stac.Extensions.Sar; using Stac.Extensions.Processing; using Stac.Extensions.Projection; +using Stac.Extensions.Sar; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; -using Stac.Extensions.Raster; namespace Terradue.Stars.Data.Model.Metadata.CosmoSkymed { @@ -32,7 +31,7 @@ public class CosmoSkymedMetadataExtractor : MetadataExtraction private static Regex h5dumpValueRegex = new Regex(@".*\(0\): *(?'value'.*)"); public static XmlSerializer metadataSerializer = new XmlSerializer(typeof(Schemas.Metadata)); - + public override string Label => "COSMO SkyMed (ASI) mission product metadata extractor"; public CosmoSkymedMetadataExtractor(ILogger logger, IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) @@ -41,10 +40,9 @@ public CosmoSkymedMetadataExtractor(ILogger logger public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try - { + { IAsset dataAsset = GetDataAsset(item); return true; } @@ -65,7 +63,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi Match identifierMatch = identifierRegex.Match(imageFileName); if (!identifierMatch.Success) { - throw new InvalidOperationException(String.Format("Identifier not recognised from image file name: {0}", imageFileName)); + throw new InvalidOperationException(string.Format("Identifier not recognised from image file name: {0}", imageFileName)); } StacItem stacItem = CreateStacItem(hdfAttributes, metadata, identifierMatch); @@ -88,7 +86,7 @@ internal virtual StacItem CreateStacItem(Dictionary hdfAttribute string identifier = identifierMatch.Groups["id"].Value; StacItem stacItem = new StacItem(identifier, GetGeometry(hdfAttributes, metadata), GetCommonMetadata(hdfAttributes, metadata)); - + return stacItem; } @@ -136,12 +134,12 @@ private double[] GetCoordinates(string input) Match coordinateMatch = coordinateRegex.Match(input); if (!coordinateMatch.Success) { - throw new InvalidOperationException(String.Format("Invalid coordinate input: {0}", input)); + throw new InvalidOperationException(string.Format("Invalid coordinate input: {0}", input)); } - if (!Double.TryParse(coordinateMatch.Groups["lat"].Value, out double lat) || !Double.TryParse(coordinateMatch.Groups["lon"].Value, out double lon)) + if (!double.TryParse(coordinateMatch.Groups["lat"].Value, out double lat) || !double.TryParse(coordinateMatch.Groups["lon"].Value, out double lon)) { - throw new InvalidOperationException(String.Format("Invalid coordinate value: {0}", input)); + throw new InvalidOperationException(string.Format("Invalid coordinate value: {0}", input)); } return new double[] { lat, lon }; @@ -157,11 +155,7 @@ protected virtual IAsset GetMetadataAsset(IItem item) protected virtual IAsset GetDataAsset(IItem item) { - IAsset dataAsset = FindFirstAssetFromFileNameRegex(item, @".*\.h5$"); - if (dataAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the HDF5 file asset")); - } + IAsset dataAsset = FindFirstAssetFromFileNameRegex(item, @".*\.h5$") ?? throw new FileNotFoundException(string.Format("Unable to find the HDF5 file asset")); return dataAsset; } @@ -179,7 +173,7 @@ protected virtual IAsset GetDataAsset(IItem item) { XmlReaderSettings settings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore }; var reader = XmlReader.Create(stream, settings); - + logger.LogDebug("Deserializing metadata file {0}", metadataAsset.Uri); return (Schemas.Metadata)metadataSerializer.Deserialize(reader); @@ -232,7 +226,7 @@ public virtual async Task> ReadHdfMetadata(IAsset dat { string value = GetHdf5Value(hdf5File, attributeName); if (value == null) continue; - + attributes.Add(attributeName, value); } @@ -257,7 +251,7 @@ private IDictionary GetCommonMetadata(Dictionary private void FillDateTimeProperties(Dictionary properties, Dictionary hdfAttributes, Schemas.Metadata metadata) { CultureInfo provider = CultureInfo.InvariantCulture; - + bool complete = true; DateTime startDate = DateTime.MinValue; DateTime endDate = startDate; @@ -314,14 +308,14 @@ private void FillInstrument(Dictionary properties, Dictionary properties, Dictionary hdfAttributes, Schemas.Metadata metadata) + private void FillBasicsProperties(IDictionary properties, Dictionary hdfAttributes, Schemas.Metadata metadata) { CultureInfo culture = new CultureInfo("fr-FR"); bool complete = true; @@ -334,20 +328,20 @@ private void FillBasicsProperties(IDictionary properties, Dictio platform = metadata.ProductDefinitionData.SatelliteId; processingLevel = metadata.ProcessingInfo.ProcessingLevel; } - properties["title"] = String.Format("{0} {1} {2}", + properties["title"] = string.Format("{0} {1} {2}", platform, processingLevel, properties.GetProperty("datetime").ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", culture) ); } - private void AddOtherProperties(IDictionary properties, Dictionary hdfAttributes, Schemas.Metadata metadata) + private void AddOtherProperties(IDictionary properties, Dictionary hdfAttributes, Schemas.Metadata metadata) { if (IncludeProviderProperty) { AddSingleProvider( properties, - "ASI", + "ASI", "COSMO-SkyMed (Constellation of Small Satellites for Mediterranean basin Observation) is a 4 spacecraft constellation. Each of the 4 satellites is equipped with the SAR-2000 Synthetic Aperture Radar, which observes in the X-band to provide global observation under all weather and visibility conditions.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.asi.it/en/earth-science/cosmo-skymed/") @@ -355,7 +349,8 @@ private void AddOtherProperties(IDictionary properties, Dictiona } } - private void FillAdditionalSarProperties(IDictionary properties, Dictionary hdfAttributes, Schemas.Metadata metadata, Match identifierMatch) { + private void FillAdditionalSarProperties(IDictionary properties, Dictionary hdfAttributes, Schemas.Metadata metadata, Match identifierMatch) + { int? multiLookSpacingRange = null; switch (identifierMatch.Groups["mode"].Value) @@ -392,10 +387,10 @@ private void AddSatStacExtension(StacItem stacItem, Dictionary h else if (metadata != null) orbitDirection = (identifierMatch.Groups["dir"].Value == "A" ? "ascending" : "descending"); sat.OrbitState = orbitDirection; - if (hdfAttributes.TryGetValue("Orbit Number", out string orbitNumberStr) && Int32.TryParse(orbitNumberStr, out int orbitNumber)) + if (hdfAttributes.TryGetValue("Orbit Number", out string orbitNumberStr) && int.TryParse(orbitNumberStr, out int orbitNumber)) { sat.AbsoluteOrbit = orbitNumber; - sat.RelativeOrbit = Int32.Parse(identifierMatch.Groups["i"].Value) * 1000 + orbitNumber % 237; + sat.RelativeOrbit = int.Parse(identifierMatch.Groups["i"].Value) * 1000 + orbitNumber % 237; } } @@ -431,7 +426,7 @@ private void AddViewStacExtension(StacItem stacItem, Dictionary if (nearAngleStr != null && farAngleStr != null) { - if (Double.TryParse(nearAngleStr, out double nearAngle) && Double.TryParse(farAngleStr, out double farAngle)) + if (double.TryParse(nearAngleStr, out double nearAngle) && double.TryParse(farAngleStr, out double farAngle)) { view.IncidenceAngle = Math.Abs((nearAngle + farAngle) / 2); } @@ -466,10 +461,10 @@ private void AddSarStacExtension(StacItem stacItem, Dictionary h instrumentMode = metadata.ProductDefinitionData.AcquisitionMode; } sar.InstrumentMode = instrumentMode; - + sar.FrequencyBand = SarCommonFrequencyBandName.X; - - if (hdfAttributes.TryGetValue("Radar Frequency", out string radarFrequencyStr) && Double.TryParse(radarFrequencyStr, out double radarFrequency)) + + if (hdfAttributes.TryGetValue("Radar Frequency", out string radarFrequencyStr) && double.TryParse(radarFrequencyStr, out double radarFrequency)) { sar.CenterFrequency = radarFrequency / 1000000000; } @@ -501,7 +496,7 @@ private void AddSarStacExtension(StacItem stacItem, Dictionary h resolutionAzimuthStr = metadata.ProductCharacteristics.AzimuthGeometricResolution; } - if (Double.TryParse(resolutionRangeStr, out double resolutionRange) && Double.TryParse(resolutionAzimuthStr, out double resolutionAzimuth)) + if (double.TryParse(resolutionRangeStr, out double resolutionRange) && double.TryParse(resolutionAzimuthStr, out double resolutionAzimuth)) { sar.ResolutionRange = resolutionRange; sar.ResolutionAzimuth = resolutionAzimuth; @@ -522,15 +517,15 @@ private void AddSarStacExtension(StacItem stacItem, Dictionary h looksEquivalentNumberStr = GetTagValue(metadata.Algorithms.Tag, "Equivalent Number of Looks"); } - if (Double.TryParse(looksRangeStr, out double looksRange)) + if (double.TryParse(looksRangeStr, out double looksRange)) { sar.LooksRange = looksRange; } - if (Double.TryParse(looksAzimuthStr, out double looksAzimuth)) + if (double.TryParse(looksAzimuthStr, out double looksAzimuth)) { sar.LooksAzimuth = looksAzimuth; } - if (Double.TryParse(looksEquivalentNumberStr, out double looksEquivalentNumber)) + if (double.TryParse(looksEquivalentNumberStr, out double looksEquivalentNumber)) { sar.LooksEquivalentNumber = looksEquivalentNumber; } @@ -545,7 +540,8 @@ private void AddProcessingStacExtension(StacItem stacItem, Dictionary hdfAttributes) { - string[] possibleLevels = new string[] {"L0", "L1A", "L1B", "L1C", "L1D"}; + string[] possibleLevels = new string[] { "L0", "L1A", "L1B", "L1C", "L1D" }; string processingLevel = null; foreach (string level in possibleLevels) { - if (hdfAttributes.TryGetValue(String.Format("{0} Software Version", level), out string version) && version != null) + if (hdfAttributes.TryGetValue(string.Format("{0} Software Version", level), out string version) && version != null) { processingLevel = level; } @@ -585,13 +581,13 @@ private string GetTagValue(Schemas.Tag[] tags, string tagName) protected void AddAssets(StacItem stacItem, IItem item, Dictionary hdfAttributes, Schemas.Metadata metadata, Match identifierMatch) { IAsset imageAsset = GetDataAsset(item); - + stacItem.Assets.Add("image", StacAsset.CreateDataAsset(stacItem, imageAsset.Uri, new ContentType("application/x-hdf5"), "Image file")); stacItem.Assets["image"].Properties.AddRange(imageAsset.Properties); stacItem.Assets["image"].Properties["sar:polarizations"] = new string[] { identifierMatch.Groups["pol"].Value }; - + IAsset metadataAsset = GetMetadataAsset(item); if (metadataAsset != null) { @@ -608,7 +604,8 @@ protected void AddAssets(StacItem stacItem, IItem item, Dictionary 0 & !h5dumpProcess.HasExited) { + if (exitCode > 0 & !h5dumpProcess.HasExited) + { h5dumpProcess.Kill(); } diff --git a/src/Stars.Data/Model/Metadata/Dimap/DMC/Alsat1BDimapProfiler.cs b/src/Stars.Data/Model/Metadata/Dimap/DMC/Alsat1BDimapProfiler.cs index d93292c1..0f2584a5 100644 --- a/src/Stars.Data/Model/Metadata/Dimap/DMC/Alsat1BDimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Dimap/DMC/Alsat1BDimapProfiler.cs @@ -1,9 +1,8 @@ -using System; +using System; using System.Collections.Generic; -using Stac.Extensions.Eo; using Stac; +using Stac.Extensions.Eo; using Terradue.Stars.Data.Model.Metadata.Dimap.Schemas; -using Terradue.Stars.Interface; namespace Terradue.Stars.Data.Model.Metadata.Dimap.DMC @@ -19,7 +18,7 @@ public Alsat1BDimapProfiler(IEnumerable dimaps) : base(dimaps) { } - protected override EoBandObject GetEoBandObject(Schemas.t_Spectral_Band_Info bandInfo, string description) + protected override EoBandObject GetEoBandObject(t_Spectral_Band_Info bandInfo, string description) { var eoBandObject = base.GetEoBandObject(bandInfo, description); //// @@ -75,4 +74,4 @@ internal override StacProvider GetStacProvider() return provider; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Dimap/DMC/DmcDimapProfiler.cs b/src/Stars.Data/Model/Metadata/Dimap/DMC/DmcDimapProfiler.cs index f0562e1b..b37c88d1 100644 --- a/src/Stars.Data/Model/Metadata/Dimap/DMC/DmcDimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Dimap/DMC/DmcDimapProfiler.cs @@ -1,11 +1,9 @@ -using System; +using System; using System.Collections.Generic; -using System.Globalization; using Stac; using Stac.Extensions.Eo; -using Terradue.Stars.Data.Model.Metadata.Dimap.Schemas; -using Terradue.Stars.Interface; using Stac.Extensions.Raster; +using Terradue.Stars.Data.Model.Metadata.Dimap.Schemas; namespace Terradue.Stars.Data.Model.Metadata.Dimap.DMC { @@ -20,7 +18,7 @@ public DmcDimapProfiler(IEnumerable dimaps) : base(dimaps) { } - protected override RasterBand GetRasterBandObject(Schemas.t_Spectral_Band_Info bandInfo, Schemas.t_Raster_Encoding raster_Encoding) + protected override RasterBand GetRasterBandObject(t_Spectral_Band_Info bandInfo, t_Raster_Encoding raster_Encoding) { RasterBand rasterBand = base.GetRasterBandObject(bandInfo, raster_Encoding); if (bandInfo.PHYSICAL_GAINSpecified) @@ -31,7 +29,7 @@ protected override RasterBand GetRasterBandObject(Schemas.t_Spectral_Band_Info b return rasterBand; } - protected override EoBandObject GetEoBandObject(Schemas.t_Spectral_Band_Info bandInfo, string description) + protected override EoBandObject GetEoBandObject(t_Spectral_Band_Info bandInfo, string description) { EoBandObject eoBandObject = base.GetEoBandObject(bandInfo, description); @@ -117,4 +115,4 @@ internal override StacProvider GetStacProvider() return null; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Dimap/DMC/Vision1DimapProfiler.cs b/src/Stars.Data/Model/Metadata/Dimap/DMC/Vision1DimapProfiler.cs index 685f4482..488edbbe 100644 --- a/src/Stars.Data/Model/Metadata/Dimap/DMC/Vision1DimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Dimap/DMC/Vision1DimapProfiler.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using Stac; @@ -28,7 +28,7 @@ internal override string GetProcessingLevel() return null; } - protected override EoBandObject GetEoBandObject(Schemas.t_Spectral_Band_Info bandInfo, string description) + protected override EoBandObject GetEoBandObject(t_Spectral_Band_Info bandInfo, string description) { var eoBandObject = base.GetEoBandObject(bandInfo, description); //// @@ -70,17 +70,17 @@ internal override string GetMission() return "Vision-1"; } - public override string GetSpectralProcessing(Schemas.DimapDocument dimap = null) + public override string GetSpectralProcessing(DimapDocument dimap = null) { List spectralProcessings = new List(); - Schemas.DimapDocument[] dimaps = dimap == null ? Dimaps : new Schemas.DimapDocument[] {dimap}; - foreach (Schemas.DimapDocument d in dimaps) + DimapDocument[] dimaps = dimap == null ? Dimaps : new DimapDocument[] { dimap }; + foreach (DimapDocument d in dimaps) { string[] identifierParts = d.Dataset_Id.DATASET_NAME.Split('_'); if (identifierParts.Length >= 2) spectralProcessings.Add(identifierParts[1]); } spectralProcessings.Sort(); - return String.Join(",", spectralProcessings); + return string.Join(",", spectralProcessings); } @@ -102,13 +102,13 @@ public override string GetProductKey(IAsset bandAsset, t_Data_File dataFile) return "composite"; } - string key = String.Format( + string key = string.Format( "{0}-{1}", nameParts[1] == "PAN" ? "PAN" : "MS", nameParts[3] ); - if (nameParts[1] != "PAN") key += String.Format("-{0}", nameParts[1]); - if (nameParts.Length >= 7) key += String.Format("-{0}", nameParts[6]); + if (nameParts[1] != "PAN") key += string.Format("-{0}", nameParts[1]); + if (nameParts.Length >= 7) key += string.Format("-{0}", nameParts[6]); return key; } @@ -127,17 +127,17 @@ internal override string GetSensorMode() return "optical"; } - internal override string GetAssetPrefix(Schemas.DimapDocument dimap, IAsset metadataAsset) + internal override string GetAssetPrefix(DimapDocument dimap, IAsset metadataAsset) { if (dimap != null) { - return Dimaps.Length == 1 ? String.Empty : String.Format("{0}-", dimap.Dataset_Id.DATASET_NAME.Substring(5, 3)); + return Dimaps.Length == 1 ? string.Empty : string.Format("{0}-", dimap.Dataset_Id.DATASET_NAME.Substring(5, 3)); } if (metadataAsset != null) { - return (Dimaps.Length == 1) ? String.Empty : String.Format("{0}-", Path.GetFileName(metadataAsset.Uri.AbsolutePath).Substring(5, 3)); + return (Dimaps.Length == 1) ? string.Empty : string.Format("{0}-", Path.GetFileName(metadataAsset.Uri.AbsolutePath).Substring(5, 3)); } - return String.Empty; + return string.Empty; } internal override StacProvider GetStacProvider() @@ -148,4 +148,4 @@ internal override StacProvider GetStacProvider() return provider; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Dimap/DimapMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Dimap/DimapMetadataExtractor.cs index e62c5186..ae1b208e 100644 --- a/src/Stars.Data/Model/Metadata/Dimap/DimapMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Dimap/DimapMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -16,18 +16,18 @@ using Stac.Extensions.Sat; using Stac.Extensions.View; using Terradue.Stars.Data.Model.Metadata.Dimap.Schemas; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Dimap { public class DimapMetadataExtractor : MetadataExtraction { - public static XmlSerializer metadataSerializer = new XmlSerializer(typeof(Schemas.t_Dimap_Document)); - public static XmlSerializer metadataAltSerializer = new XmlSerializer(typeof(Schemas.t_Metadata_Document)); + public static XmlSerializer metadataSerializer = new XmlSerializer(typeof(t_Dimap_Document)); + public static XmlSerializer metadataAltSerializer = new XmlSerializer(typeof(t_Metadata_Document)); public override string Label => "Generic DIMAP product metadata extractor"; @@ -37,12 +37,11 @@ public DimapMetadataExtractor(ILogger logger, IResourceS public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset[] metadataAssets = GetMetadataAssets(item); - Schemas.DimapDocument[] metadata = ReadMetadata(metadataAssets).GetAwaiter().GetResult(); + DimapDocument[] metadata = ReadMetadata(metadataAssets).GetAwaiter().GetResult(); var dimapProfiler = GetProfiler(metadata); return dimapProfiler != null; } @@ -95,7 +94,7 @@ private DimapProfiler GetProfiler(DimapDocument[] dimapDocuments) protected override async Task ExtractMetadata(IItem item, string suffix) { IAsset[] metadataAssets = GetMetadataAssets(item); - Schemas.DimapDocument[] metadata = await ReadMetadata(metadataAssets); + DimapDocument[] metadata = await ReadMetadata(metadataAssets); DimapProfiler dimapProfiler = GetProfiler(metadata); @@ -269,7 +268,7 @@ private void FillDateTimeProperties(DimapProfiler dimapProfiler, Dictionary properties) + private void FillBasicsProperties(DimapProfiler dimapProfiler, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -286,42 +285,43 @@ private void AddOtherProperties(DimapProfiler dimapProfiler, IDictionary positions = new List(); + List positions = new List(); foreach (var vertex in dimapProfiler.Dimap.Dataset_Frame) { - positions.Add(new GeoJSON.Net.Geometry.Position(vertex.FRAME_LAT.Value, vertex.FRAME_LON.Value)); + positions.Add(new Position(vertex.FRAME_LAT.Value, vertex.FRAME_LON.Value)); } positions.Add(positions.First()); - GeoJSON.Net.Geometry.LineString lineString = new GeoJSON.Net.Geometry.LineString( + LineString lineString = new LineString( positions.ToArray() ); - geometry = new GeoJSON.Net.Geometry.Polygon(new GeoJSON.Net.Geometry.LineString[] { lineString }).NormalizePolygon(); + geometry = new Polygon(new LineString[] { lineString }).NormalizePolygon(); } else { double minLon = 180; double maxLon = -180; - GeoJSON.Net.Geometry.Position swPosition = null, sePosition = null, nePosition = null, nwPosition = null; + Position swPosition = null, sePosition = null, nePosition = null, nwPosition = null; - foreach (Schemas.DimapDocument dimap in dimapProfiler.Dimaps) + foreach (DimapDocument dimap in dimapProfiler.Dimaps) { - List positions = new List(); + List positions = new List(); foreach (var vertex in dimap.Dataset_Frame) { - positions.Add(new GeoJSON.Net.Geometry.Position(vertex.FRAME_LAT.Value, vertex.FRAME_LON.Value)); + positions.Add(new Position(vertex.FRAME_LAT.Value, vertex.FRAME_LON.Value)); } if (positions.Count != 4) return null; - List sorted = new List(positions); - sorted.Sort((pos1, pos2) => { + List sorted = new List(positions); + sorted.Sort((pos1, pos2) => + { if (pos1.Longitude < pos2.Longitude) return -1; if (pos1.Longitude > pos2.Longitude) return 1; return 0; @@ -356,14 +356,14 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometry(DimapProfiler dimapProf } } - GeoJSON.Net.Geometry.LineString lineString = new GeoJSON.Net.Geometry.LineString( - new GeoJSON.Net.Geometry.Position[] + LineString lineString = new LineString( + new Position[] { swPosition, sePosition, nePosition, nwPosition, swPosition } ); - geometry = new GeoJSON.Net.Geometry.Polygon(new GeoJSON.Net.Geometry.LineString[] { lineString }).NormalizePolygon(); + geometry = new Polygon(new LineString[] { lineString }).NormalizePolygon(); } return geometry; @@ -386,9 +386,7 @@ protected void AddAssets(StacItem stacItem, IItem item, DimapProfiler dimapProfi foreach (var dataFile in dataFiles) { - IAsset productAsset = FindFirstAssetFromFileNameRegex(item, dataFile.DATA_FILE_PATH.href + "$"); - if (productAsset == null) - throw new FileNotFoundException(string.Format("No product found '{0}'", dataFile.DATA_FILE_PATH.href)); + IAsset productAsset = FindFirstAssetFromFileNameRegex(item, dataFile.DATA_FILE_PATH.href + "$") ?? throw new FileNotFoundException(string.Format("No product found '{0}'", dataFile.DATA_FILE_PATH.href)); var bandStacAsset = CreateRasterAsset(stacItem, productAsset, dimapProfiler, dataFile, dimap); if (dimap.Data_Access.DATA_FILE_ORGANISATION == t_DATA_FILE_ORGANISATION.BAND_SEPARATE) dimapProfiler.CompleteAsset(bandStacAsset.Value, @@ -404,7 +402,7 @@ protected void AddAssets(StacItem stacItem, IItem item, DimapProfiler dimapProfi foreach (IAsset metadataAsset in metadataAssets) { string prefix = dimapProfiler.GetAssetPrefix(null, metadataAsset); - string key = String.Format("{0}metadata", prefix); + string key = string.Format("{0}metadata", prefix); stacItem.Assets.Add(key, StacAsset.CreateMetadataAsset(stacItem, metadataAsset.Uri, new ContentType("application/xml"), "Metadata file")); stacItem.Assets[key].Properties.AddRange(metadataAsset.Properties); @@ -417,7 +415,7 @@ protected void AddAssets(StacItem stacItem, IItem item, DimapProfiler dimapProfi var overviewAsset = FindFirstAssetFromFileNameRegex(item, dimap.Dataset_Id.DATASET_QL_PATH.href); if (overviewAsset != null) { - string key = String.Format("{0}overview", prefix); + string key = string.Format("{0}overview", prefix); if (stacItem.Assets.TryAdd(key, StacAsset.CreateOverviewAsset(stacItem, overviewAsset.Uri, new ContentType(MimeTypes.GetMimeType(Path.GetFileName(overviewAsset.Uri.ToString())))))) stacItem.Assets[key].Properties.AddRange(overviewAsset.Properties); @@ -429,17 +427,17 @@ protected void AddAssets(StacItem stacItem, IItem item, DimapProfiler dimapProfi var thumbnailAsset = FindFirstAssetFromFileNameRegex(item, dimap.Dataset_Id.DATASET_TN_PATH.href); if (thumbnailAsset != null) { - string key = String.Format("{0}thumbnail", prefix); + string key = string.Format("{0}thumbnail", prefix); stacItem.Assets.Add(key, StacAsset.CreateThumbnailAsset(stacItem, thumbnailAsset.Uri, new ContentType(MimeTypes.GetMimeType(Path.GetFileName(thumbnailAsset.Uri.ToString()))))); stacItem.Assets[key].Properties.AddRange(thumbnailAsset.Properties); } } - catch{} + catch { } } } - private KeyValuePair CreateRasterAsset(StacItem stacItem, IAsset bandAsset, DimapProfiler dimapProfiler, t_Data_File dataFile, Schemas.DimapDocument dimap) + private KeyValuePair CreateRasterAsset(StacItem stacItem, IAsset bandAsset, DimapProfiler dimapProfiler, t_Data_File dataFile, DimapDocument dimap) { string mimeType; if (Path.GetExtension(bandAsset.Uri.AbsolutePath) == ".jp2") mimeType = "image/jpeg"; @@ -452,19 +450,19 @@ private KeyValuePair CreateRasterAsset(StacItem stacItem, IAs protected virtual IAsset[] GetMetadataAssets(IItem item) { - IEnumerable manifestAssets = this.FindAssetsFromFileNameRegex(item, @".*\.dim$"); - if (manifestAssets == null || manifestAssets.Count() == 0) + IEnumerable manifestAssets = FindAssetsFromFileNameRegex(item, @".*\.dim$"); + if (manifestAssets == null || manifestAssets.Count() == 0) { manifestAssets = FindAssetsFromFileNameRegex(item, @"(DIM.*|.*Meta)\.xml$"); if (manifestAssets == null || manifestAssets.Count() == 0) - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset(s)")); + throw new FileNotFoundException(string.Format("Unable to find the metadata file asset(s)")); } return manifestAssets.ToArray(); } - public virtual async Task ReadMetadata(IEnumerable metadataAssets) + public virtual async Task ReadMetadata(IEnumerable metadataAssets) { - List metadata = new List(); + List metadata = new List(); foreach (IAsset metadataAsset in metadataAssets) { @@ -475,14 +473,14 @@ protected virtual IAsset[] GetMetadataAssets(IItem item) var reader = XmlReader.Create(stream); logger.LogDebug("Deserializing manifest {0}", metadataAsset.Uri); - Schemas.DimapDocument singleDimap; + DimapDocument singleDimap; try { - singleDimap = (Schemas.DimapDocument)metadataSerializer.Deserialize(reader); + singleDimap = (DimapDocument)metadataSerializer.Deserialize(reader); } catch { - singleDimap = (Schemas.t_Metadata_Document)metadataAltSerializer.Deserialize(reader); + singleDimap = (t_Metadata_Document)metadataAltSerializer.Deserialize(reader); } metadata.Add(singleDimap); diff --git a/src/Stars.Data/Model/Metadata/Dimap/DimapProfiler.cs b/src/Stars.Data/Model/Metadata/Dimap/DimapProfiler.cs index 0c12ae8f..0d622b09 100644 --- a/src/Stars.Data/Model/Metadata/Dimap/DimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Dimap/DimapProfiler.cs @@ -1,13 +1,12 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using Humanizer; using Stac; using Stac.Extensions.Eo; -using Stac; -using Terradue.Stars.Interface; using Stac.Extensions.Raster; -using Humanizer; +using Terradue.Stars.Interface; namespace Terradue.Stars.Data.Model.Metadata.Dimap { @@ -15,12 +14,14 @@ public abstract class DimapProfiler { private Schemas.DimapDocument[] dimaps; - public Schemas.DimapDocument Dimap { - get { return (dimaps == null || dimaps.Length == 0 ? null : dimaps[0]);} + public Schemas.DimapDocument Dimap + { + get { return (dimaps == null || dimaps.Length == 0 ? null : dimaps[0]); } protected set { dimaps = new Schemas.DimapDocument[] { value }; } } - public Schemas.DimapDocument[] Dimaps { + public Schemas.DimapDocument[] Dimaps + { get { return dimaps; } protected set { dimaps = value; } } @@ -39,7 +40,7 @@ internal Schemas.t_Source_Information[] GetSceneSources() { foreach (Schemas.t_Source_Information ds in dimap.Dataset_Sources) { - if (ds.Scene_Source != null && !String.IsNullOrEmpty(ds.Scene_Source.MISSION)) + if (ds.Scene_Source != null && !string.IsNullOrEmpty(ds.Scene_Source.MISSION)) { sceneSources.Add(ds); } @@ -57,10 +58,10 @@ internal virtual string GetMission() { var ss = GetSceneSources(); if (ss == null || ss.Length == 0) return null; - var mission = String.Format( + var mission = string.Format( "{0}{1}", ss[0].Scene_Source.MISSION, - String.IsNullOrEmpty(ss[0].Scene_Source.MISSION_INDEX) ? String.Empty : "-" + ss[0].Scene_Source.MISSION_INDEX + string.IsNullOrEmpty(ss[0].Scene_Source.MISSION_INDEX) ? string.Empty : "-" + ss[0].Scene_Source.MISSION_INDEX ); return mission.Replace(" ", "-"); } @@ -100,7 +101,7 @@ internal virtual DateTime GetAcquisitionTime() if (s.Scene_Source.IMAGING_DATE > dt) dt = s.Scene_Source.IMAGING_DATE; if (s.Scene_Source.IMAGING_START_TIME < st) st = s.Scene_Source.IMAGING_START_TIME; } - if (dt == DateTime.MinValue) dt = st; + if (dt == DateTime.MinValue) dt = st; return dt; } @@ -142,9 +143,9 @@ public virtual string[] GetInstruments() var ss = GetSceneSources(); if (ss == null || ss.Length == 0) return null; return new string[] { - String.Format("{0}{1}", + string.Format("{0}{1}", ss[0].Scene_Source.INSTRUMENT, - String.IsNullOrEmpty(ss[0].Scene_Source.INSTRUMENT_INDEX) ? String.Empty : "-" + ss[0].Scene_Source.INSTRUMENT_INDEX + string.IsNullOrEmpty(ss[0].Scene_Source.INSTRUMENT_INDEX) ? string.Empty : "-" + ss[0].Scene_Source.INSTRUMENT_INDEX ) }; } @@ -159,7 +160,7 @@ public virtual string GetSpectralProcessing(Schemas.DimapDocument dimap = null) var ss = GetSceneSources(); if (ss == null || ss.Length == 0 || ss[0].Scene_Source.GRID_REFERENCE == null) return null; string[] refs = ss[0].Scene_Source.GRID_REFERENCE.Split('/'); - if (Int32.TryParse(refs[0], out int orbit)) return orbit; + if (int.TryParse(refs[0], out int orbit)) return orbit; return null; } @@ -168,7 +169,7 @@ public virtual string GetSpectralProcessing(Schemas.DimapDocument dimap = null) var ss = GetSceneSources(); if (ss == null || ss.Length == 0 || ss[0].Scene_Source?.GRID_REFERENCE == null) return null; string[] refs = ss[0].Scene_Source.GRID_REFERENCE.Split('/'); - if (refs.Length >= 2 && Int32.TryParse(refs[0], out int orbit)) return orbit; + if (refs.Length >= 2 && int.TryParse(refs[0], out int orbit)) return orbit; return null; } @@ -200,7 +201,7 @@ internal long GetProjection() { try { - return Int64.Parse(Dimap.Coordinate_Reference_System.Horizontal_CS.Projection.PROJECTION_CODE.Replace("EPSG:", "")); + return long.Parse(Dimap.Coordinate_Reference_System.Horizontal_CS.Projection.PROJECTION_CODE.Replace("EPSG:", "")); } catch { } return 0; @@ -211,7 +212,7 @@ internal int[] GetShape() int height = 0, width = 0; foreach (Schemas.DimapDocument dimap in Dimaps) { - if (Int32.TryParse(dimap.Raster_Dimensions.NCOLS, out int ncols) && Int32.TryParse(dimap.Raster_Dimensions.NROWS, out int nrows)) + if (int.TryParse(dimap.Raster_Dimensions.NCOLS, out int ncols) && int.TryParse(dimap.Raster_Dimensions.NROWS, out int nrows)) { if (height == 0 || nrows < height) height = nrows; if (width == 0 || ncols < width) width = ncols; @@ -390,7 +391,7 @@ internal virtual string GetAssetTitle(IAsset bandAsset, Schemas.t_Data_File data internal virtual string GetAssetPrefix(Schemas.DimapDocument dimap, IAsset metadataAsset = null) { - return String.Empty; + return string.Empty; } internal virtual StacProvider GetStacProvider() @@ -398,4 +399,4 @@ internal virtual StacProvider GetStacProvider() return null; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Dimap/GenericDimapProfiler.cs b/src/Stars.Data/Model/Metadata/Dimap/GenericDimapProfiler.cs index 52d512bf..665e4967 100644 --- a/src/Stars.Data/Model/Metadata/Dimap/GenericDimapProfiler.cs +++ b/src/Stars.Data/Model/Metadata/Dimap/GenericDimapProfiler.cs @@ -1,13 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; +using Humanizer; using Stac; using Stac.Extensions.Eo; +using Stac.Extensions.Raster; using Terradue.Stars.Data.Model.Metadata.Dimap.Schemas; using Terradue.Stars.Interface; -using Stac.Extensions.Raster; -using System.Linq; -using Humanizer; namespace Terradue.Stars.Data.Model.Metadata.Dimap { @@ -55,7 +55,7 @@ public override string GetTitle(IDictionary properties) properties.GetProperty("datetime").ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", culture)); } - protected override EoBandObject GetEoBandObject(Schemas.t_Spectral_Band_Info bandInfo, string description) + protected override EoBandObject GetEoBandObject(t_Spectral_Band_Info bandInfo, string description) { EoBandObject eoBandObject = new EoBandObject(bandInfo.BAND_DESCRIPTION ?? bandInfo.BAND_INDEX.Value, (EoBandCommonName)Enum.Parse(typeof(EoBandCommonName), bandInfo.BAND_DESCRIPTION.ToLower())); @@ -72,7 +72,7 @@ protected override EoBandObject GetEoBandObject(Schemas.t_Spectral_Band_Info ban return eoBandObject; } - protected override RasterBand GetRasterBandObject(Schemas.t_Spectral_Band_Info bandInfo, Schemas.t_Raster_Encoding rasterEncoding) + protected override RasterBand GetRasterBandObject(t_Spectral_Band_Info bandInfo, t_Raster_Encoding rasterEncoding) { RasterBand rasterBandObject = new RasterBand(); if (rasterEncoding.DATA_TYPESpecified) @@ -123,4 +123,4 @@ internal override string GetSensorMode() return null; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Gaofen1-2-4/GaofenMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Gaofen1-2-4/GaofenMetadataExtractor.cs index 8de9dfca..e50dd845 100644 --- a/src/Stars.Data/Model/Metadata/Gaofen1-2-4/GaofenMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Gaofen1-2-4/GaofenMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -11,18 +11,20 @@ using Stac; using Stac.Extensions.Eo; using Stac.Extensions.Processing; +using Stac.Extensions.Projection; +using Stac.Extensions.Raster; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; -using Terradue.Stars.Services.Model.Stac; -using Stac.Extensions.Raster; using Terradue.Stars.Services; -using Stac.Extensions.Projection; -using Terradue.Stars.Geometry.GeoJson; +using Terradue.Stars.Services.Model.Stac; -namespace Terradue.Stars.Data.Model.Metadata.Gaofen { - public class GaofenMetadataExtractor : MetadataExtraction { +namespace Terradue.Stars.Data.Model.Metadata.Gaofen +{ + public class GaofenMetadataExtractor : MetadataExtraction + { private const string GAOFEN1_PLATFORM_NAME = "Gaofen-1"; private const string GAOFEN2_PLATFORM_NAME = "Gaofen-2"; private const string GAOFEN4_PLATFORM_NAME = "Gaofen-4"; @@ -31,27 +33,32 @@ public class GaofenMetadataExtractor : MetadataExtraction { "Gaofen-1/2 High-resolution Imaging Satellite (CNSA) missions product metadata extractor"; public GaofenMetadataExtractor(ILogger logger, - IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) { + IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) + { } - public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + public override bool CanProcess(IResource route, IDestination destination) + { + if (!(route is IItem item)) return false; IAsset metadataFile = FindFirstAssetFromFileNameRegex(item, "^(?!order)[\\w_\\-\\.]+(? ExtractMetadata(IItem item, string suffix) { + protected override async Task ExtractMetadata(IItem item, string suffix) + { logger.LogDebug("Retrieving the metadata files in the product package"); List metadatafiles = FindAssetsFromFileNameRegex(item, "^(?!order)[\\w_\\-\\.]+(? ExtractMetadata(IItem item, string suffi } - private StacItem GetStacItemWithProperties(ProductMetaData productMetadata, string stacItemId, double gsd) { + private StacItem GetStacItemWithProperties(ProductMetaData productMetadata, string stacItemId, double gsd) + { // retrieving GeometryObject from metadata var geometryObject = GetGeometryObjectFromProductMetadata(productMetadata); @@ -114,28 +124,36 @@ private StacItem GetStacItemWithProperties(ProductMetaData productMetadata, stri return stacItem; } - private void AddProjStacExtension(ProductMetaData productMetaData, StacItem stacItem) { + private void AddProjStacExtension(ProductMetaData productMetaData, StacItem stacItem) + { ProjectionStacExtension proj = stacItem.ProjectionExtension(); - if (!string.IsNullOrEmpty(productMetaData.MapProjection) && productMetaData.MapProjection == "WGS84") { + if (!string.IsNullOrEmpty(productMetaData.MapProjection) && productMetaData.MapProjection == "WGS84") + { proj.SetCoordinateSystem(ProjNet.CoordinateSystems.GeocentricCoordinateSystem.WGS84); } - else { + else + { proj.Epsg = null; } - try { + try + { proj.Shape = new int[2] { productMetaData.WidthInPixels, productMetaData.HeightInPixels }; } - catch { + catch + { } } - private double GetLowestGsd(List productMetadataList) { + private double GetLowestGsd(List productMetadataList) + { double lowestGsd = double.Parse(productMetadataList[0].ImageGSD); // loop through each metadata file to extract the asset - foreach (var productMetaData in productMetadataList) { - if (lowestGsd > double.Parse(productMetaData.ImageGSD)) { + foreach (var productMetaData in productMetadataList) + { + if (lowestGsd > double.Parse(productMetaData.ImageGSD)) + { lowestGsd = double.Parse(productMetaData.ImageGSD); } } @@ -144,15 +162,18 @@ private double GetLowestGsd(List productMetadataList) { } - private async Task> DeserializeProductMetadataList(List medatafileList) { + private async Task> DeserializeProductMetadataList(List medatafileList) + { List productMetadataList = new List(); - foreach (var metadataFile in medatafileList.OrderBy(m => m.Uri.ToString())) { + foreach (var metadataFile in medatafileList.OrderBy(m => m.Uri.ToString())) + { logger.LogDebug("Metadata file is {0}", metadataFile.Uri); IStreamResource metadataFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(metadataFile, System.Threading.CancellationToken.None); - if (metadataFileStreamable == null) { + if (metadataFileStreamable == null) + { logger.LogError("metadata file asset is not streamable, skipping metadata extraction"); } @@ -168,7 +189,8 @@ await resourceServiceProvider.GetStreamResourceAsync(metadataFile, private void FillBasicsProperties(ProductMetaData productMetadata, - IDictionary properties) { + IDictionary properties) + { CultureInfo culture = CultureInfo.InvariantCulture; // title properties.Remove("title"); @@ -181,23 +203,28 @@ private void FillBasicsProperties(ProductMetaData productMetadata, .ToString("yyyy-MM-dd HH:mm:ss", culture))); } - private void AddEoBandPropertyInItem(StacItem stacItem) { + private void AddEoBandPropertyInItem(StacItem stacItem) + { var eo = stacItem.EoExtension(); eo.Bands = stacItem.Assets.Values.Where(a => a.EoExtension().Bands != null) .SelectMany(a => a.EoExtension().Bands).ToArray(); } - private async Task AddAssetsAsync(StacItem stacItem, string satelliteId, IAssetsContainer assetsContainer) { - foreach (var asset in assetsContainer.Assets.Values.OrderBy(a => a.Uri.ToString())) { + private async Task AddAssetsAsync(StacItem stacItem, string satelliteId, IAssetsContainer assetsContainer) + { + foreach (var asset in assetsContainer.Assets.Values.OrderBy(a => a.Uri.ToString())) + { await AddAssetAsync(stacItem, satelliteId, asset, assetsContainer); } } private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset asset, - IAssetsContainer assetsContainer) { + IAssetsContainer assetsContainer) + { string filename = Path.GetFileName(asset.Uri.ToString()); - if (filename.Split('_').Length == 1) { + if (filename.Split('_').Length == 1) + { // file that does not respect the naming convention (eg. order.xml) return; } @@ -208,16 +235,20 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a // thumbnail if (filename.EndsWith("-MSS1_thumb.jpg", true, CultureInfo.InvariantCulture) || filename.EndsWith("-MSS2_thumb.jpg", true, CultureInfo.InvariantCulture) - ) { - if (stacItem.Assets.TryAdd("MSS-thumbnail", GetGenericAsset(stacItem, asset.Uri, "thumbnail"))) { + ) + { + if (stacItem.Assets.TryAdd("MSS-thumbnail", GetGenericAsset(stacItem, asset.Uri, "thumbnail"))) + { stacItem.Assets["MSS-thumbnail"].Properties.AddRange(asset.Properties); } return; } if (filename.EndsWith("-PAN1_thumb.jpg", true, CultureInfo.InvariantCulture) || - filename.EndsWith("-PAN2_thumb.jpg", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd("PAN-thumbnail", GetGenericAsset(stacItem, asset.Uri, "thumbnail"))) { + filename.EndsWith("-PAN2_thumb.jpg", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd("PAN-thumbnail", GetGenericAsset(stacItem, asset.Uri, "thumbnail"))) + { stacItem.Assets["PAN-thumbnail"].Properties.AddRange(asset.Properties); } return; @@ -227,16 +258,20 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a // for example : GF1_WFV3_E89.0_N23.9_20200523_L1A0004819525_thumb.jpg if (satelliteImagery == null && filename.StartsWith("GF1", true, CultureInfo.InvariantCulture) && - filename.EndsWith("thumb.jpg", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd("MSS-thumbnail", GetGenericAsset(stacItem, asset.Uri, "thumbnail"))) { + filename.EndsWith("thumb.jpg", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd("MSS-thumbnail", GetGenericAsset(stacItem, asset.Uri, "thumbnail"))) + { stacItem.Assets["MSS-thumbnail"].Properties.AddRange(asset.Properties); } return; } if (filename.StartsWith("GF4", true, CultureInfo.InvariantCulture) && - filename.EndsWith("thumb.jpg", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd($"{type}-thumbnail", GetGenericAsset(stacItem, asset.Uri, "thumbnail"))) { + filename.EndsWith("thumb.jpg", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd($"{type}-thumbnail", GetGenericAsset(stacItem, asset.Uri, "thumbnail"))) + { stacItem.Assets[$"{type}-thumbnail"].Properties.AddRange(asset.Properties); } return; @@ -244,8 +279,10 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a // overview if (filename.EndsWith("-MSS1.jpg", true, CultureInfo.InvariantCulture) || - filename.EndsWith("-MSS2.jpg", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd("MSS-overview", GetGenericAsset(stacItem, asset.Uri, "overview"))) { + filename.EndsWith("-MSS2.jpg", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd("MSS-overview", GetGenericAsset(stacItem, asset.Uri, "overview"))) + { stacItem.Assets["MSS-overview"].Properties.AddRange(asset.Properties); } return; @@ -253,7 +290,8 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a if (filename.EndsWith("-PAN1.jpg", true, CultureInfo.InvariantCulture) || - filename.EndsWith("-PAN2.jpg", true, CultureInfo.InvariantCulture)) { + filename.EndsWith("-PAN2.jpg", true, CultureInfo.InvariantCulture)) + { stacItem.Assets.Add("PAN-overview", GetGenericAsset(stacItem, asset.Uri, "overview")); stacItem.Assets["PAN-overview"].Properties.AddRange(asset.Properties); @@ -262,16 +300,20 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a if (satelliteImagery == null && filename.StartsWith("GF1", true, CultureInfo.InvariantCulture) && - filename.EndsWith(".jpg", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd("MSS-overview", GetGenericAsset(stacItem, asset.Uri, "overview"))) { + filename.EndsWith(".jpg", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd("MSS-overview", GetGenericAsset(stacItem, asset.Uri, "overview"))) + { stacItem.Assets["MSS-overview"].Properties.AddRange(asset.Properties); } return; } if (filename.StartsWith("GF4", true, CultureInfo.InvariantCulture) && - filename.EndsWith(".jpg", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd($"{type}-overview", GetGenericAsset(stacItem, asset.Uri, "overview"))) { + filename.EndsWith(".jpg", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd($"{type}-overview", GetGenericAsset(stacItem, asset.Uri, "overview"))) + { stacItem.Assets[$"{type}-overview"].Properties.AddRange(asset.Properties); } return; @@ -279,15 +321,18 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a // metadata if (filename.EndsWith("-MSS1.xml", true, CultureInfo.InvariantCulture) || - filename.EndsWith("-MSS2.xml", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd("MSS-metadata", GetGenericAsset(stacItem, asset.Uri, "metadata"))) { + filename.EndsWith("-MSS2.xml", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd("MSS-metadata", GetGenericAsset(stacItem, asset.Uri, "metadata"))) + { stacItem.Assets["MSS-metadata"].Properties.AddRange(asset.Properties); } return; } - if (filename.EndsWith("-PAN1.xml", true, CultureInfo.InvariantCulture) - || filename.EndsWith("-PAN2.xml", true, CultureInfo.InvariantCulture)) { + if (filename.EndsWith("-PAN1.xml", true, CultureInfo.InvariantCulture) + || filename.EndsWith("-PAN2.xml", true, CultureInfo.InvariantCulture)) + { stacItem.Assets.Add("PAN-metadata", GetGenericAsset(stacItem, asset.Uri, "metadata")); stacItem.Assets["PAN-metadata"].Properties.AddRange(asset.Properties); return; @@ -295,16 +340,20 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a if (satelliteImagery == null && filename.StartsWith("GF1", true, CultureInfo.InvariantCulture) && - filename.EndsWith(".xml", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd("MSS-metadata", GetGenericAsset(stacItem, asset.Uri, "metadata"))) { + filename.EndsWith(".xml", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd("MSS-metadata", GetGenericAsset(stacItem, asset.Uri, "metadata"))) + { stacItem.Assets["MSS-metadata"].Properties.AddRange(asset.Properties); } return; } if (filename.StartsWith("GF4", true, CultureInfo.InvariantCulture) && - filename.EndsWith(".xml", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd($"{type}-metadata", GetGenericAsset(stacItem, asset.Uri, "metadata"))) { + filename.EndsWith(".xml", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd($"{type}-metadata", GetGenericAsset(stacItem, asset.Uri, "metadata"))) + { stacItem.Assets[$"{type}-metadata"].Properties.AddRange(asset.Properties); } return; @@ -312,14 +361,16 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a // rpb metadata if (filename.EndsWith("-MSS1.rpb", true, CultureInfo.InvariantCulture) || - filename.EndsWith("-MSS2.rpb", true, CultureInfo.InvariantCulture)) { + filename.EndsWith("-MSS2.rpb", true, CultureInfo.InvariantCulture)) + { stacItem.Assets.Add("MSS-rpb", GetGenericAsset(stacItem, asset.Uri, "metadata")); stacItem.Assets["MSS-rpb"].Properties.AddRange(asset.Properties); return; } if (filename.EndsWith("-PAN1.rpb", true, CultureInfo.InvariantCulture) || - filename.EndsWith("-PAN2.rpb", true, CultureInfo.InvariantCulture)) { + filename.EndsWith("-PAN2.rpb", true, CultureInfo.InvariantCulture)) + { stacItem.Assets.Add("PAN-rpb", GetGenericAsset(stacItem, asset.Uri, "metadata")); stacItem.Assets["PAN-rpb"].Properties.AddRange(asset.Properties); return; @@ -327,15 +378,18 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a if (satelliteImagery == null && filename.StartsWith("GF1", true, CultureInfo.InvariantCulture) && - filename.EndsWith(".rpb", true, CultureInfo.InvariantCulture)) { + filename.EndsWith(".rpb", true, CultureInfo.InvariantCulture)) + { stacItem.Assets.Add("MSS-rpb", GetGenericAsset(stacItem, asset.Uri, "metadata")); stacItem.Assets["MSS-rpb"].Properties.AddRange(asset.Properties); return; } if (filename.StartsWith("GF4", true, CultureInfo.InvariantCulture) && - filename.EndsWith(".rpb", true, CultureInfo.InvariantCulture)) { - if (stacItem.Assets.TryAdd($"{type}-rpb", GetGenericAsset(stacItem, asset.Uri, "metadata"))) { + filename.EndsWith(".rpb", true, CultureInfo.InvariantCulture)) + { + if (stacItem.Assets.TryAdd($"{type}-rpb", GetGenericAsset(stacItem, asset.Uri, "metadata"))) + { stacItem.Assets[$"{type}-rpb"].Properties.AddRange(asset.Properties); } return; @@ -343,17 +397,20 @@ private async Task AddAssetAsync(StacItem stacItem, string satelliteId, IAsset a // tiff if (filename.EndsWith("-MSS1.tiff", true, CultureInfo.InvariantCulture) || - filename.EndsWith("-MSS2.tiff", true, CultureInfo.InvariantCulture)) { + filename.EndsWith("-MSS2.tiff", true, CultureInfo.InvariantCulture)) + { string mssBandName = "MSS"; var metadataAsset = FindAssetsFromFileNameRegex(assetsContainer, ".*" + filename.Replace(".tiff", ".xml")); ProductMetaData metadata = null; - try { + try + { metadata = await DeserializeProductMetadata( await resourceServiceProvider.GetStreamResourceAsync(metadataAsset.FirstOrDefault(), System.Threading.CancellationToken.None)); } - catch { + catch + { } var bandAsset = GetBandAsset(stacItem, mssBandName, sensorName, asset, satelliteId, metadata); @@ -363,17 +420,20 @@ await resourceServiceProvider.GetStreamResourceAsync(metadataAsset.FirstOrDefaul // GAOFEN1 WFV 1 2 3 4 if (filename.StartsWith("GF1_WFV", true, CultureInfo.InvariantCulture) && - filename.EndsWith(".tiff", true, CultureInfo.InvariantCulture)) { + filename.EndsWith(".tiff", true, CultureInfo.InvariantCulture)) + { string mssBandName = "MSS"; var metadataAsset = FindAssetsFromFileNameRegex(assetsContainer, ".*" + filename.Replace(".tiff", ".xml")); ProductMetaData metadata = null; - try { + try + { metadata = await DeserializeProductMetadata( await resourceServiceProvider.GetStreamResourceAsync(metadataAsset.FirstOrDefault(), System.Threading.CancellationToken.None)); } - catch { + catch + { } var bandAsset = GetBandAsset(stacItem, mssBandName, sensorName, asset, satelliteId, metadata); @@ -383,16 +443,19 @@ await resourceServiceProvider.GetStreamResourceAsync(metadataAsset.FirstOrDefaul if (filename.EndsWith("-PAN1.tiff", true, CultureInfo.InvariantCulture) || - filename.EndsWith("-PAN2.tiff", true, CultureInfo.InvariantCulture)) { + filename.EndsWith("-PAN2.tiff", true, CultureInfo.InvariantCulture)) + { var metadataAsset = FindAssetsFromFileNameRegex(assetsContainer, ".*" + filename.Replace(".tiff", ".xml")); ProductMetaData metadata = null; - try { + try + { metadata = await DeserializeProductMetadata( await resourceServiceProvider.GetStreamResourceAsync(metadataAsset.FirstOrDefault(), System.Threading.CancellationToken.None)); } - catch { + catch + { } string panBandName = "PAN"; @@ -402,16 +465,19 @@ await resourceServiceProvider.GetStreamResourceAsync(metadataAsset.FirstOrDefaul } if (filename.StartsWith("GF4_PMS", true, CultureInfo.InvariantCulture) && - filename.EndsWith(".tiff", true, CultureInfo.InvariantCulture)) { + filename.EndsWith(".tiff", true, CultureInfo.InvariantCulture)) + { var metadataAsset = FindAssetsFromFileNameRegex(assetsContainer, ".*" + filename.Replace(".tiff", ".xml")); ProductMetaData metadata = null; - try { + try + { metadata = await DeserializeProductMetadata( await resourceServiceProvider.GetStreamResourceAsync(metadataAsset.FirstOrDefault(), System.Threading.CancellationToken.None)); } - catch { + catch + { } var bandAsset = GetBandAsset(stacItem, null, sensorName, asset, satelliteId, metadata); @@ -420,16 +486,19 @@ await resourceServiceProvider.GetStreamResourceAsync(metadataAsset.FirstOrDefaul } if (filename.StartsWith("GF4_IRS", true, CultureInfo.InvariantCulture) && - filename.EndsWith(".tiff", true, CultureInfo.InvariantCulture)) { + filename.EndsWith(".tiff", true, CultureInfo.InvariantCulture)) + { var metadataAssets = FindAssetsFromFileNameRegex(assetsContainer, ".*" + filename.Replace(".tiff", ".xml")); ProductMetaData metadata = null; - try { + try + { metadata = await DeserializeProductMetadata( await resourceServiceProvider.GetStreamResourceAsync(metadataAssets.FirstOrDefault(), System.Threading.CancellationToken.None)); } - catch { + catch + { } var bandAsset = GetBandAsset(stacItem, null, sensorName, asset, satelliteId, metadata); @@ -438,13 +507,16 @@ await resourceServiceProvider.GetStreamResourceAsync(metadataAssets.FirstOrDefau } } - private string RetrieveSatelliteImageryFromFilename(string filename) { - if (filename.EndsWith("_thumb.jpg")) { + private string RetrieveSatelliteImageryFromFilename(string filename) + { + if (filename.EndsWith("_thumb.jpg")) + { filename = filename.Replace("_thumb.jpg", ".jpg"); } string[] imagerySplit1 = filename.Split('-'); - if (imagerySplit1.Length < 2) { + if (imagerySplit1.Length < 2) + { return null; } @@ -455,20 +527,25 @@ private string RetrieveSatelliteImageryFromFilename(string filename) { private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensorName, IAsset asset, - string satelliteId, ProductMetaData? metadata) { + string satelliteId, ProductMetaData? metadata) + { StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, asset.Uri, new System.Net.Mime.ContentType(MimeTypes.GetMimeType(asset.Uri.ToString())) ); stacAsset.Properties.AddRange(asset.Properties); - if (metadata != null) { + if (metadata != null) + { stacAsset.ProjectionExtension().Shape = new int[2] { metadata.WidthInPixels, metadata.HeightInPixels }; } //////////// // GAOFEN 1 - if (satelliteId == "GF1") { - if (sensorName == "PMS1") { - if (bandName == "PAN") { + if (satelliteId == "GF1") + { + if (sensorName == "PMS1") + { + if (bandName == "PAN") + { stacAsset.SetProperty("gsd", 2); EoBandObject eoBandObject = CreateEoBandObject("PAN", EoBandCommonName.pan, 0.675, 0.450, 1361.43); @@ -476,7 +553,8 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor RasterBand rasterBandObject = CreateRasterBandObject(0.0, 0.1982); stacAsset.RasterExtension().Bands = new RasterBand[1] { rasterBandObject }; } - else { + else + { stacAsset.Properties.Add("gsd", 8); EoBandObject b01EoBandObject = CreateEoBandObject("B01", EoBandCommonName.blue, 0.485, 0.07, 1966.811); @@ -502,8 +580,10 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor { b01RasterBandObject, b02RasterBandObject, b03RasterBandObject, b04RasterBandObject }; } } - else if (sensorName == "PMS2") { - if (bandName == "PAN") { + else if (sensorName == "PMS2") + { + if (bandName == "PAN") + { stacAsset.SetProperty("gsd", 2); EoBandObject eoBandObject = CreateEoBandObject("PAN", EoBandCommonName.pan, 0.675, 0.45, 0.1979); @@ -511,7 +591,8 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor RasterBand rasterBandObject = CreateRasterBandObject(0.0, 0.1979); stacAsset.RasterExtension().Bands = new RasterBand[1] { rasterBandObject }; } - else { + else + { stacAsset.Properties.Add("gsd", 8); EoBandObject b01EoBandObject = CreateEoBandObject("B01", EoBandCommonName.blue, 0.485, 0.07, 1967.309); @@ -539,7 +620,8 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor { b01RasterBandObject, b02RasterBandObject, b03RasterBandObject, b04RasterBandObject }; } } - else if (sensorName == "WFV1") { + else if (sensorName == "WFV1") + { stacAsset.SetProperty("gsd", 16); // gaofen1 with sensor WFV1 only have Multispectral bands EoBandObject b01EoBandObject = @@ -565,7 +647,8 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor stacAsset.RasterExtension().Bands = new[] { b01RasterBandObject, b02RasterBandObject, b03RasterBandObject, b04RasterBandObject }; } - else if (sensorName == "WFV2") { + else if (sensorName == "WFV2") + { stacAsset.SetProperty("gsd", 16); // gaofen1 with sensor WFV2 only have Multispectral bands EoBandObject b01EoBandObject = @@ -591,7 +674,8 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor stacAsset.RasterExtension().Bands = new[] { b01RasterBandObject, b02RasterBandObject, b03RasterBandObject, b04RasterBandObject }; } - else if (sensorName == "WFV3") { + else if (sensorName == "WFV3") + { stacAsset.SetProperty("gsd", 16); // gaofen1 with sensor WFV3 only have Multispectral bands EoBandObject b01EoBandObject = @@ -617,7 +701,8 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor stacAsset.RasterExtension().Bands = new[] { b01RasterBandObject, b02RasterBandObject, b03RasterBandObject, b04RasterBandObject }; } - else if (sensorName == "WFV4") { + else if (sensorName == "WFV4") + { stacAsset.SetProperty("gsd", 16); // gaofen1 with sensor WFV4 only have Multispectral bands EoBandObject b01EoBandObject = @@ -647,9 +732,12 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor //////////// // GAOFEN 2 - else if (satelliteId == "GF2") { - if (sensorName == "PMS1") { - if (bandName == "PAN") { + else if (satelliteId == "GF2") + { + if (sensorName == "PMS1") + { + if (bandName == "PAN") + { stacAsset.SetProperty("gsd", 0.81); EoBandObject eoBandObject = CreateEoBandObject("PAN", EoBandCommonName.pan, 0.670, 0.440, 1361.43); @@ -657,7 +745,8 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor RasterBand rasterBandObject = CreateRasterBandObject(-0.6077, 0.163); stacAsset.RasterExtension().Bands = new RasterBand[1] { rasterBandObject }; } - else { + else + { stacAsset.SetProperty("gsd", 3.24); EoBandObject b01EoBandObject = CreateEoBandObject("B01", EoBandCommonName.blue, 0.485, 0.07, 1966.811); @@ -684,8 +773,10 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor { b01RasterBandObject, b02RasterBandObject, b03RasterBandObject, b04RasterBandObject }; } } - else if (sensorName == "PMS2") { - if (bandName == "PAN") { + else if (sensorName == "PMS2") + { + if (bandName == "PAN") + { stacAsset.SetProperty("gsd", 0.81); EoBandObject eoBandObject = CreateEoBandObject("PAN", EoBandCommonName.pan, 0.670, 0.440, 1363.494); @@ -693,7 +784,8 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor RasterBand rasterBandObject = CreateRasterBandObject(0.1654, 0.1823); stacAsset.RasterExtension().Bands = new RasterBand[1] { rasterBandObject }; } - else { + else + { stacAsset.SetProperty("gsd", 3.24); EoBandObject b01EoBandObject = CreateEoBandObject("B01", EoBandCommonName.blue, 0.485, 0.07, 1967.309); @@ -724,7 +816,8 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor //////////// // GAOFEN 4 - else if (satelliteId == "GF4") { + else if (satelliteId == "GF4") + { GetGF4BandAssets(stacAsset, metadata, sensorName); } @@ -732,11 +825,13 @@ private StacAsset GetBandAsset(StacItem stacItem, string bandName, string sensor } private void GetGF4BandAssets(StacAsset stacAsset, ProductMetaData metadata, - string sensorName) { + string sensorName) + { var acquisitionYear = metadata.StartTime.Split('-')[0]; var msList = metadata.IntegrationTime.Split(',').ToList(); JObject gf4Aux = null; - using (StreamReader r = new StreamReader("Model/Metadata/Gaofen1-2-4/GF4_bands.json")) { + using (StreamReader r = new StreamReader("Model/Metadata/Gaofen1-2-4/GF4_bands.json")) + { string json = r.ReadToEnd(); gf4Aux = JObject.Parse(json); } @@ -744,7 +839,8 @@ private void GetGF4BandAssets(StacAsset stacAsset, ProductMetaData metadata, int numberOfBands = msList.Count; stacAsset.EoExtension().Bands = new EoBandObject[numberOfBands]; stacAsset.RasterExtension().Bands = new RasterBand[numberOfBands]; - for (int i = 0; i < numberOfBands; i++) { + for (int i = 0; i < numberOfBands; i++) + { var band = gf4Aux["GF4"][sensorName][$"{msList[i]}ms"][i]; stacAsset.SetProperty("gsd", band["gsd"].Value()); EoBandObject eoBandObject = @@ -760,17 +856,22 @@ private void GetGF4BandAssets(StacAsset stacAsset, ProductMetaData metadata, } } - public static EoBandCommonName? ParseEoBandCommonNameEnum(string value) { - try { + public static EoBandCommonName? ParseEoBandCommonNameEnum(string value) + { + try + { return (EoBandCommonName)Enum.Parse(typeof(EoBandCommonName), value, true); - } catch { + } + catch + { return null; } } private EoBandObject CreateEoBandObject(string name, EoBandCommonName? eoBandCommonName, double centerWaveLength, - double fullWidthHalfMax, double eai) { + double fullWidthHalfMax, double eai) + { EoBandObject eoBandObject = new EoBandObject(name, eoBandCommonName); eoBandObject.Properties.Add("full_width_half_max", fullWidthHalfMax); eoBandObject.SolarIllumination = eai; @@ -778,7 +879,8 @@ private EoBandObject CreateEoBandObject(string name, EoBandCommonName? eoBandCom return eoBandObject; } - private RasterBand CreateRasterBandObject(double offset, double gain) { + private RasterBand CreateRasterBandObject(double offset, double gain) + { RasterBand rasterBandObject = new RasterBand(); rasterBandObject.Offset = offset; rasterBandObject.Scale = gain; @@ -786,7 +888,8 @@ private RasterBand CreateRasterBandObject(double offset, double gain) { } - private StacAsset GetGenericAsset(StacItem stacItem, Uri uri, string role) { + private StacAsset GetGenericAsset(StacItem stacItem, Uri uri, string role) + { StacAsset stacAsset = new StacAsset(stacItem, uri); stacAsset.Roles.Add(role); stacAsset.MediaType = @@ -794,12 +897,14 @@ private StacAsset GetGenericAsset(StacItem stacItem, Uri uri, string role) { return stacAsset; } - private void AddOtherProperties(ProductMetaData productMetadata, StacItem stacItem) { + private void AddOtherProperties(ProductMetaData productMetadata, StacItem stacItem) + { stacItem.Properties.Add("product_type", "PAN_MS_" + productMetadata.ProductLevel.Replace("LEVEL", "L")); - if (IncludeProviderProperty) { + if (IncludeProviderProperty) + { AddSingleProvider( stacItem.Properties, - "CNSA", + "CNSA", "The main goal of the CHEOS (China High-Resolution Earth Observation System) series is to provide NRT (Near-Real-Time) observations for disaster prevention and relief, climate change monitoring, geographical mapping, environment and resource surveying, and precision agricultural support.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("http://www.cnsa.gov.cn/english/n6465715/n6465716/c6840350/content.html") @@ -807,12 +912,14 @@ private void AddOtherProperties(ProductMetaData productMetadata, StacItem stacIt } } - private void AddProcessingStacExtension(ProductMetaData productMetadata, StacItem stacItem) { + private void AddProcessingStacExtension(ProductMetaData productMetadata, StacItem stacItem) + { var proc = stacItem.ProcessingExtension(); proc.Level = productMetadata.ProductLevel.Replace("LEVEL", "L"); } - private void AddViewStacExtension(ProductMetaData productMetadata, StacItem stacItem) { + private void AddViewStacExtension(ProductMetaData productMetadata, StacItem stacItem) + { var view = new ViewStacExtension(stacItem); view.OffNadir = double.Parse(productMetadata.PitchViewingAngle); view.IncidenceAngle = double.Parse(productMetadata.RollViewingAngle); @@ -821,7 +928,8 @@ private void AddViewStacExtension(ProductMetaData productMetadata, StacItem stac view.SunElevation = double.Parse(productMetadata.SolarZenith); } - private void AddSatStacExtension(ProductMetaData productMetadata, StacItem stacItem) { + private void AddSatStacExtension(ProductMetaData productMetadata, StacItem stacItem) + { var sat = new SatStacExtension(stacItem); sat.AbsoluteOrbit = int.Parse(productMetadata.OrbitID); sat.RelativeOrbit = int.Parse(productMetadata.OrbitID); @@ -829,7 +937,8 @@ private void AddSatStacExtension(ProductMetaData productMetadata, StacItem stacI } - private void AddEoStacExtension(ProductMetaData productMetadata, StacItem stacItem) { + private void AddEoStacExtension(ProductMetaData productMetadata, StacItem stacItem) + { EoStacExtension eo = stacItem.EoExtension(); if (productMetadata.CloudPercent != null) eo.CloudCover = double.Parse(productMetadata.CloudPercent) / 100; @@ -838,7 +947,8 @@ private void AddEoStacExtension(ProductMetaData productMetadata, StacItem stacIt } private GeoJSON.Net.Geometry.IGeometryObject GetGeometryObjectFromProductMetadata( - ProductMetaData productMetadata) { + ProductMetaData productMetadata) + { GeoJSON.Net.Geometry.LineString lineString = new GeoJSON.Net.Geometry.LineString( new GeoJSON.Net.Geometry.Position[5] { @@ -857,7 +967,8 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometryObjectFromProductMetadat return new GeoJSON.Net.Geometry.Polygon(new[] { lineString }).NormalizePolygon(); } - private IDictionary GetCommonMetadata(ProductMetaData productMetadata, double gsd) { + private IDictionary GetCommonMetadata(ProductMetaData productMetadata, double gsd) + { Dictionary properties = new Dictionary(); FillDateTimeProperties(productMetadata, properties); FillInstrument(productMetadata, properties, gsd); @@ -866,11 +977,14 @@ private IDictionary GetCommonMetadata(ProductMetaData productMet } - public static async Task DeserializeProductMetadata(IStreamResource productMetadataFile) { + public static async Task DeserializeProductMetadata(IStreamResource productMetadataFile) + { XmlSerializer ser = new XmlSerializer(typeof(ProductMetaData)); ProductMetaData auxiliary; - using (var stream = await productMetadataFile.GetStreamAsync(System.Threading.CancellationToken.None)) { - using (XmlReader reader = XmlReader.Create(stream)) { + using (var stream = await productMetadataFile.GetStreamAsync(System.Threading.CancellationToken.None)) + { + using (XmlReader reader = XmlReader.Create(stream)) + { auxiliary = (ProductMetaData)ser.Deserialize(reader); } } @@ -879,7 +993,8 @@ public static async Task DeserializeProductMetadata(IStreamReso } - private void FillDateTimeProperties(ProductMetaData productMetadata, Dictionary properties) { + private void FillDateTimeProperties(ProductMetaData productMetadata, Dictionary properties) + { CultureInfo provider = CultureInfo.InvariantCulture; string format = "yyyy-MM-dd HH:mm:ss"; DateTime.TryParseExact(productMetadata.StartTime, format, provider, DateTimeStyles.AssumeUniversal, @@ -895,14 +1010,17 @@ private void FillDateTimeProperties(ProductMetaData productMetadata, Dictionary< properties.Remove("end_datetime"); // datetime, start_datetime, end_datetime - if (dateInterval.IsAnytime) { + if (dateInterval.IsAnytime) + { properties.Add("datetime", null); } - if (dateInterval.IsMoment) { + if (dateInterval.IsMoment) + { properties.Add("datetime", dateInterval.Start.ToUniversalTime()); } - else { + else + { properties.Add("datetime", dateInterval.Start.ToUniversalTime()); properties.Add("start_datetime", dateInterval.Start.ToUniversalTime()); properties.Add("end_datetime", dateInterval.End.ToUniversalTime()); @@ -911,7 +1029,8 @@ private void FillDateTimeProperties(ProductMetaData productMetadata, Dictionary< DateTime.TryParseExact(productMetadata.ProduceTime, format, provider, DateTimeStyles.AssumeUniversal, out var createdDate); - if (createdDate.Ticks != 0) { + if (createdDate.Ticks != 0) + { properties.Remove("created"); properties.Add("created", createdDate.ToUniversalTime()); } @@ -921,24 +1040,30 @@ private void FillDateTimeProperties(ProductMetaData productMetadata, Dictionary< } private void FillInstrument(ProductMetaData productMetadata, - Dictionary properties, double gsd) { + Dictionary properties, double gsd) + { string platformName = ""; // platform & constellation - if (productMetadata.SatelliteID == "GF1") { + if (productMetadata.SatelliteID == "GF1") + { platformName = GAOFEN1_PLATFORM_NAME.ToLower(); } - else if (productMetadata.SatelliteID == "GF2") { + else if (productMetadata.SatelliteID == "GF2") + { platformName = GAOFEN2_PLATFORM_NAME.ToLower(); } - else if (productMetadata.SatelliteID == "GF4") { + else if (productMetadata.SatelliteID == "GF4") + { platformName = GAOFEN4_PLATFORM_NAME.ToLower(); } - else { + else + { throw new InvalidDataException("Platform id not found or not recognized"); } - if (!string.IsNullOrEmpty(platformName)) { + if (!string.IsNullOrEmpty(platformName)) + { properties.Remove("platform"); properties.Add("platform", platformName); @@ -951,7 +1076,8 @@ private void FillInstrument(ProductMetaData productMetadata, // instruments var instrumentName = productMetadata.SensorID.ToLower(); - if (!string.IsNullOrEmpty(instrumentName)) { + if (!string.IsNullOrEmpty(instrumentName)) + { properties.Remove("instruments"); properties.Add("instruments", new string[] { instrumentName }); } diff --git a/src/Stars.Data/Model/Metadata/Gaofen1-2-4/ProductMetaData.cs b/src/Stars.Data/Model/Metadata/Gaofen1-2-4/ProductMetaData.cs index 495f001d..6d50d459 100644 --- a/src/Stars.Data/Model/Metadata/Gaofen1-2-4/ProductMetaData.cs +++ b/src/Stars.Data/Model/Metadata/Gaofen1-2-4/ProductMetaData.cs @@ -1,149 +1,150 @@ - /* - Licensed under the Apache License, Version 2.0 - - http://www.apache.org/licenses/LICENSE-2.0 - */ -using System; +/* + Licensed under the Apache License, Version 2.0 + + http://www.apache.org/licenses/LICENSE-2.0 + */ using System.Xml.Serialization; - namespace Terradue.Stars.Data.Model.Metadata.Gaofen { - [XmlRoot(ElementName="ProductMetaData")] - public class ProductMetaData { - [XmlElement(ElementName="SatelliteID")] - public string SatelliteID { get; set; } - [XmlElement(ElementName="SensorID")] - public string SensorID { get; set; } - [XmlElement(ElementName="ReceiveTime")] - public string ReceiveTime { get; set; } - [XmlElement(ElementName="OrbitID")] - public string OrbitID { get; set; } - [XmlElement(ElementName="ProduceType")] - public string ProduceType { get; set; } - [XmlElement(ElementName="SceneID")] - public string SceneID { get; set; } - [XmlElement(ElementName="ProductID")] - public string ProductID { get; set; } - [XmlElement(ElementName="ProductLevel")] - public string ProductLevel { get; set; } - [XmlElement(ElementName="ProductQuality")] - public string ProductQuality { get; set; } - [XmlElement(ElementName="ProductQualityReport")] - public string ProductQualityReport { get; set; } - [XmlElement(ElementName="ProductFormat")] - public string ProductFormat { get; set; } - [XmlElement(ElementName="ProduceTime")] - public string ProduceTime { get; set; } - [XmlElement(ElementName="Bands")] - public string Bands { get; set; } - [XmlElement(ElementName="ScenePath")] - public string ScenePath { get; set; } - [XmlElement(ElementName="SceneRow")] - public string SceneRow { get; set; } - [XmlElement(ElementName="SatPath")] - public string SatPath { get; set; } - [XmlElement(ElementName="SatRow")] - public string SatRow { get; set; } - [XmlElement(ElementName="SceneCount")] - public string SceneCount { get; set; } - [XmlElement(ElementName="SceneShift")] - public string SceneShift { get; set; } - [XmlElement(ElementName="StartTime")] - public string StartTime { get; set; } - [XmlElement(ElementName="EndTime")] - public string EndTime { get; set; } - [XmlElement(ElementName="CenterTime")] - public string CenterTime { get; set; } - [XmlElement(ElementName="ImageGSD")] - public string ImageGSD { get; set; } - [XmlElement(ElementName="WidthInPixels")] - public int WidthInPixels { get; set; } - [XmlElement(ElementName="HeightInPixels")] - public int HeightInPixels { get; set; } - [XmlElement(ElementName="WidthInMeters")] - public string WidthInMeters { get; set; } - [XmlElement(ElementName="HeightInMeters")] - public string HeightInMeters { get; set; } - [XmlElement(ElementName="CloudPercent")] - public string CloudPercent { get; set; } - [XmlElement(ElementName="QualityInfo")] - public string QualityInfo { get; set; } - [XmlElement(ElementName="PixelBits")] - public string PixelBits { get; set; } - [XmlElement(ElementName="ValidPixelBits")] - public string ValidPixelBits { get; set; } - [XmlElement(ElementName="RollViewingAngle")] - public string RollViewingAngle { get; set; } - [XmlElement(ElementName="PitchViewingAngle")] - public string PitchViewingAngle { get; set; } - [XmlElement(ElementName="RollSatelliteAngle")] - public string RollSatelliteAngle { get; set; } - [XmlElement(ElementName="PitchSatelliteAngle")] - public string PitchSatelliteAngle { get; set; } - [XmlElement(ElementName="YawSatelliteAngle")] - public string YawSatelliteAngle { get; set; } - [XmlElement(ElementName="SolarAzimuth")] - public string SolarAzimuth { get; set; } - [XmlElement(ElementName="SolarZenith")] - public string SolarZenith { get; set; } - [XmlElement(ElementName="SatelliteAzimuth")] - public string SatelliteAzimuth { get; set; } - [XmlElement(ElementName="SatelliteZenith")] - public string SatelliteZenith { get; set; } - [XmlElement(ElementName="Gain")] +namespace Terradue.Stars.Data.Model.Metadata.Gaofen +{ + [XmlRoot(ElementName = "ProductMetaData")] + public class ProductMetaData + { + [XmlElement(ElementName = "SatelliteID")] + public string SatelliteID { get; set; } + [XmlElement(ElementName = "SensorID")] + public string SensorID { get; set; } + [XmlElement(ElementName = "ReceiveTime")] + public string ReceiveTime { get; set; } + [XmlElement(ElementName = "OrbitID")] + public string OrbitID { get; set; } + [XmlElement(ElementName = "ProduceType")] + public string ProduceType { get; set; } + [XmlElement(ElementName = "SceneID")] + public string SceneID { get; set; } + [XmlElement(ElementName = "ProductID")] + public string ProductID { get; set; } + [XmlElement(ElementName = "ProductLevel")] + public string ProductLevel { get; set; } + [XmlElement(ElementName = "ProductQuality")] + public string ProductQuality { get; set; } + [XmlElement(ElementName = "ProductQualityReport")] + public string ProductQualityReport { get; set; } + [XmlElement(ElementName = "ProductFormat")] + public string ProductFormat { get; set; } + [XmlElement(ElementName = "ProduceTime")] + public string ProduceTime { get; set; } + [XmlElement(ElementName = "Bands")] + public string Bands { get; set; } + [XmlElement(ElementName = "ScenePath")] + public string ScenePath { get; set; } + [XmlElement(ElementName = "SceneRow")] + public string SceneRow { get; set; } + [XmlElement(ElementName = "SatPath")] + public string SatPath { get; set; } + [XmlElement(ElementName = "SatRow")] + public string SatRow { get; set; } + [XmlElement(ElementName = "SceneCount")] + public string SceneCount { get; set; } + [XmlElement(ElementName = "SceneShift")] + public string SceneShift { get; set; } + [XmlElement(ElementName = "StartTime")] + public string StartTime { get; set; } + [XmlElement(ElementName = "EndTime")] + public string EndTime { get; set; } + [XmlElement(ElementName = "CenterTime")] + public string CenterTime { get; set; } + [XmlElement(ElementName = "ImageGSD")] + public string ImageGSD { get; set; } + [XmlElement(ElementName = "WidthInPixels")] + public int WidthInPixels { get; set; } + [XmlElement(ElementName = "HeightInPixels")] + public int HeightInPixels { get; set; } + [XmlElement(ElementName = "WidthInMeters")] + public string WidthInMeters { get; set; } + [XmlElement(ElementName = "HeightInMeters")] + public string HeightInMeters { get; set; } + [XmlElement(ElementName = "CloudPercent")] + public string CloudPercent { get; set; } + [XmlElement(ElementName = "QualityInfo")] + public string QualityInfo { get; set; } + [XmlElement(ElementName = "PixelBits")] + public string PixelBits { get; set; } + [XmlElement(ElementName = "ValidPixelBits")] + public string ValidPixelBits { get; set; } + [XmlElement(ElementName = "RollViewingAngle")] + public string RollViewingAngle { get; set; } + [XmlElement(ElementName = "PitchViewingAngle")] + public string PitchViewingAngle { get; set; } + [XmlElement(ElementName = "RollSatelliteAngle")] + public string RollSatelliteAngle { get; set; } + [XmlElement(ElementName = "PitchSatelliteAngle")] + public string PitchSatelliteAngle { get; set; } + [XmlElement(ElementName = "YawSatelliteAngle")] + public string YawSatelliteAngle { get; set; } + [XmlElement(ElementName = "SolarAzimuth")] + public string SolarAzimuth { get; set; } + [XmlElement(ElementName = "SolarZenith")] + public string SolarZenith { get; set; } + [XmlElement(ElementName = "SatelliteAzimuth")] + public string SatelliteAzimuth { get; set; } + [XmlElement(ElementName = "SatelliteZenith")] + public string SatelliteZenith { get; set; } + [XmlElement(ElementName = "Gain")] public string Gain { get; set; } - [XmlElement(ElementName="Bias")] + [XmlElement(ElementName = "Bias")] public string Bias { get; set; } - [XmlElement(ElementName="GainMode")] - public string GainMode { get; set; } - [XmlElement(ElementName="IntegrationTime")] - public string IntegrationTime { get; set; } - [XmlElement(ElementName="IntegrationLevel")] - public string IntegrationLevel { get; set; } - [XmlElement(ElementName="MapProjection")] - public string MapProjection { get; set; } - [XmlElement(ElementName="EarthEllipsoid")] - public string EarthEllipsoid { get; set; } - [XmlElement(ElementName="ZoneNo")] - public string ZoneNo { get; set; } - [XmlElement(ElementName="ResamplingKernel")] - public string ResamplingKernel { get; set; } - [XmlElement(ElementName="HeightMode")] - public string HeightMode { get; set; } - [XmlElement(ElementName="MtfCorrection")] - public string MtfCorrection { get; set; } - [XmlElement(ElementName="RelativeCorrectionData")] - public string RelativeCorrectionData { get; set; } - [XmlElement(ElementName="TopLeftLatitude")] - public string TopLeftLatitude { get; set; } - [XmlElement(ElementName="TopLeftLongitude")] - public string TopLeftLongitude { get; set; } - [XmlElement(ElementName="TopRightLatitude")] - public string TopRightLatitude { get; set; } - [XmlElement(ElementName="TopRightLongitude")] - public string TopRightLongitude { get; set; } - [XmlElement(ElementName="BottomRightLatitude")] - public string BottomRightLatitude { get; set; } - [XmlElement(ElementName="BottomRightLongitude")] - public string BottomRightLongitude { get; set; } - [XmlElement(ElementName="BottomLeftLatitude")] - public string BottomLeftLatitude { get; set; } - [XmlElement(ElementName="BottomLeftLongitude")] - public string BottomLeftLongitude { get; set; } - [XmlElement(ElementName="TopLeftMapX")] - public string TopLeftMapX { get; set; } - [XmlElement(ElementName="TopLeftMapY")] - public string TopLeftMapY { get; set; } - [XmlElement(ElementName="TopRightMapX")] - public string TopRightMapX { get; set; } - [XmlElement(ElementName="TopRightMapY")] - public string TopRightMapY { get; set; } - [XmlElement(ElementName="BottomRightMapX")] - public string BottomRightMapX { get; set; } - [XmlElement(ElementName="BottomRightMapY")] - public string BottomRightMapY { get; set; } - [XmlElement(ElementName="BottomLeftMapX")] - public string BottomLeftMapX { get; set; } - [XmlElement(ElementName="BottomLeftMapY")] - public string BottomLeftMapY { get; set; } - } + [XmlElement(ElementName = "GainMode")] + public string GainMode { get; set; } + [XmlElement(ElementName = "IntegrationTime")] + public string IntegrationTime { get; set; } + [XmlElement(ElementName = "IntegrationLevel")] + public string IntegrationLevel { get; set; } + [XmlElement(ElementName = "MapProjection")] + public string MapProjection { get; set; } + [XmlElement(ElementName = "EarthEllipsoid")] + public string EarthEllipsoid { get; set; } + [XmlElement(ElementName = "ZoneNo")] + public string ZoneNo { get; set; } + [XmlElement(ElementName = "ResamplingKernel")] + public string ResamplingKernel { get; set; } + [XmlElement(ElementName = "HeightMode")] + public string HeightMode { get; set; } + [XmlElement(ElementName = "MtfCorrection")] + public string MtfCorrection { get; set; } + [XmlElement(ElementName = "RelativeCorrectionData")] + public string RelativeCorrectionData { get; set; } + [XmlElement(ElementName = "TopLeftLatitude")] + public string TopLeftLatitude { get; set; } + [XmlElement(ElementName = "TopLeftLongitude")] + public string TopLeftLongitude { get; set; } + [XmlElement(ElementName = "TopRightLatitude")] + public string TopRightLatitude { get; set; } + [XmlElement(ElementName = "TopRightLongitude")] + public string TopRightLongitude { get; set; } + [XmlElement(ElementName = "BottomRightLatitude")] + public string BottomRightLatitude { get; set; } + [XmlElement(ElementName = "BottomRightLongitude")] + public string BottomRightLongitude { get; set; } + [XmlElement(ElementName = "BottomLeftLatitude")] + public string BottomLeftLatitude { get; set; } + [XmlElement(ElementName = "BottomLeftLongitude")] + public string BottomLeftLongitude { get; set; } + [XmlElement(ElementName = "TopLeftMapX")] + public string TopLeftMapX { get; set; } + [XmlElement(ElementName = "TopLeftMapY")] + public string TopLeftMapY { get; set; } + [XmlElement(ElementName = "TopRightMapX")] + public string TopRightMapX { get; set; } + [XmlElement(ElementName = "TopRightMapY")] + public string TopRightMapY { get; set; } + [XmlElement(ElementName = "BottomRightMapX")] + public string BottomRightMapX { get; set; } + [XmlElement(ElementName = "BottomRightMapY")] + public string BottomRightMapY { get; set; } + [XmlElement(ElementName = "BottomLeftMapX")] + public string BottomLeftMapX { get; set; } + [XmlElement(ElementName = "BottomLeftMapY")] + public string BottomLeftMapY { get; set; } + } } diff --git a/src/Stars.Data/Model/Metadata/Gaofen3/Gaofen3MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Gaofen3/Gaofen3MetadataExtractor.cs index 497c9ee8..cc9fb9e0 100644 --- a/src/Stars.Data/Model/Metadata/Gaofen3/Gaofen3MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Gaofen3/Gaofen3MetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -14,11 +14,11 @@ using Stac.Extensions.Sar; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; -using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services; -using Terradue.Stars.Geometry.GeoJson; +using Terradue.Stars.Services.Model.Stac; namespace Terradue.Stars.Data.Model.Metadata.Gaofen3 { @@ -26,7 +26,7 @@ public class Gaofen3MetadataExtractor : MetadataExtraction { //private const string GAOFEN3_PLATFORM_NAME = "gf-3"; private const string GAOFEN3_PLATFORM_NAME = "GAOFEN-3"; - + private const string GAOFEN3_DESCENDING_ORBIT_STATE = "descending"; public override string Label => "Gaofen-3 SAR Satellite (CNSA) mission product metadata extractor"; @@ -35,8 +35,7 @@ public Gaofen3MetadataExtractor(ILogger logger, IResou public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; IAsset metadataFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(\\.meta\\.xml)$"); if (metadataFile == null) @@ -50,13 +49,7 @@ public override bool CanProcess(IResource route, IDestination destination) protected override async Task ExtractMetadata(IItem item, string suffix) { logger.LogDebug("Retrieving the metadata files in the product package"); - IAsset metadataFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(\\.meta\\.xml)$"); - - if (metadataFile == null) - { - throw new FileNotFoundException("Unable to find the metadata file asset"); - } - + IAsset metadataFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(\\.meta\\.xml)$") ?? throw new FileNotFoundException("Unable to find the metadata file asset"); logger.LogDebug("Metadata file is {0}", metadataFile.Uri); IStreamResource metadataFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(metadataFile, System.Threading.CancellationToken.None); @@ -96,14 +89,14 @@ protected override async Task ExtractMetadata(IItem item, string suffi FillBasicsProperties(metadata, stacItem.Properties); AddOtherProperties(metadata, stacItem); - return StacItemNode.Create(stacItem, item.Uri);; + return StacItemNode.Create(stacItem, item.Uri); ; } private void AddProjStacExtension(ProductMetadata metadata, StacItem stacItem) { ProjectionStacExtension proj = stacItem.ProjectionExtension(); proj.SetCoordinateSystem(ProjNet.CoordinateSystems.GeocentricCoordinateSystem.WGS84); - proj.Shape = new int[2]{ metadata.Imageinfo.Width, metadata.Imageinfo.Height }; + proj.Shape = new int[2] { metadata.Imageinfo.Width, metadata.Imageinfo.Height }; } private void AddSarStacExtension(ProductMetadata metadata, StacItem stacItem) @@ -131,11 +124,13 @@ private string[] GetPolarizations(ProductMetadata metadata) switch (metadata.Productinfo.ProductPolar) { // single polarization - case "HH": case "DH": + case "HH": + case "DH": return new[] { "HH" }; case "HV": return new[] { "HV" }; - case "VV": case "DV": + case "VV": + case "DV": return new[] { "VV" }; case "VH": return new[] { "VH" }; @@ -221,12 +216,17 @@ private void AddAsset(StacItem stacItem, IAsset asset, if (match.Success) { string polarization; - if (match.Groups[1].Value.ToUpper().Equals("DH")) { + if (match.Groups[1].Value.ToUpper().Equals("DH")) + { polarization = "HH"; - } else if (match.Groups[1].Value.ToUpper().Equals("DV")) { + } + else if (match.Groups[1].Value.ToUpper().Equals("DV")) + { polarization = "VV"; - } else { - polarization = match.Groups[1].Value; + } + else + { + polarization = match.Groups[1].Value; } var thumbnailAsset = GetGenericAsset(stacItem, asset.Uri, new[] { "thumbnail" }); @@ -243,12 +243,17 @@ private void AddAsset(StacItem stacItem, IAsset asset, if (match.Success) { string polarization; - if (match.Groups[1].Value.ToUpper().Equals("DH")) { + if (match.Groups[1].Value.ToUpper().Equals("DH")) + { polarization = "HH"; - } else if (match.Groups[1].Value.ToUpper().Equals("DV")) { + } + else if (match.Groups[1].Value.ToUpper().Equals("DV")) + { polarization = "VV"; - } else { - polarization = match.Groups[1].Value; + } + else + { + polarization = match.Groups[1].Value; } var overviewAsset = GetGenericAsset(stacItem, asset.Uri, new[] { "overview" }); @@ -263,14 +268,20 @@ private void AddAsset(StacItem stacItem, IAsset asset, // Tiff rgx = new Regex("[0-9a-zA-Z_-]*(HH|HV|VH|VV|DH|DV)[0-9a-zA-Z_-]*(\\.tiff)$"); match = rgx.Match(filename); - if (match.Success) { + if (match.Success) + { string polarization; - if (match.Groups[1].Value.ToUpper().Equals("DH")) { + if (match.Groups[1].Value.ToUpper().Equals("DH")) + { polarization = "HH"; - } else if (match.Groups[1].Value.ToUpper().Equals("DV")) { + } + else if (match.Groups[1].Value.ToUpper().Equals("DV")) + { polarization = "VV"; - } else { - polarization = match.Groups[1].Value; + } + else + { + polarization = match.Groups[1].Value; } var tiffAsset = GetGenericAsset(stacItem, asset.Uri, new[] { "amplitude", "data" }); tiffAsset.SetProperty("sar:polarizations", new[] { polarization }); @@ -330,7 +341,7 @@ private void AddOtherProperties(ProductMetadata productMetadata, StacItem stacIt { AddSingleProvider( stacItem.Properties, - "CNSA", + "CNSA", "The main goal of the CHEOS (China High-Resolution Earth Observation System) series is to provide NRT (Near-Real-Time) observations for disaster prevention and relief, climate change monitoring, geographical mapping, environment and resource surveying, and precision agricultural support.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("http://www.cnsa.gov.cn/english/n6465715/n6465716/c6840350/content.html") @@ -491,4 +502,4 @@ private void FillInstrument(ProductMetadata productMetadata, Dictionary GPSParam { get; set; } - } + [XmlRoot(ElementName = "GPS")] + public class GPS + { + [XmlElement(ElementName = "GPSParam")] + public List GPSParam { get; set; } + } - [XmlRoot(ElementName="ATTIParam")] - public class ATTIParam { - [XmlElement(ElementName="TimeStamp")] - public string TimeStamp { get; set; } - [XmlElement(ElementName="yawAngle")] - public string YawAngle { get; set; } - [XmlElement(ElementName="rollAngle")] - public string RollAngle { get; set; } - [XmlElement(ElementName="pitchAngle")] - public string PitchAngle { get; set; } - } + [XmlRoot(ElementName = "ATTIParam")] + public class ATTIParam + { + [XmlElement(ElementName = "TimeStamp")] + public string TimeStamp { get; set; } + [XmlElement(ElementName = "yawAngle")] + public string YawAngle { get; set; } + [XmlElement(ElementName = "rollAngle")] + public string RollAngle { get; set; } + [XmlElement(ElementName = "pitchAngle")] + public string PitchAngle { get; set; } + } - [XmlRoot(ElementName="ATTI")] - public class ATTI { - [XmlElement(ElementName="ATTIParam")] - public List ATTIParam { get; set; } - } + [XmlRoot(ElementName = "ATTI")] + public class ATTI + { + [XmlElement(ElementName = "ATTIParam")] + public List ATTIParam { get; set; } + } - [XmlRoot(ElementName="productinfo")] - public class Productinfo { - [XmlElement(ElementName="NominalResolution")] - public string NominalResolution { get; set; } - [XmlElement(ElementName="WidthInMeters")] - public string WidthInMeters { get; set; } - [XmlElement(ElementName="productLevel")] - public string ProductLevel { get; set; } - [XmlElement(ElementName="productType")] - public string ProductType { get; set; } - [XmlElement(ElementName="productFormat")] - public string ProductFormat { get; set; } - [XmlElement(ElementName="productGentime")] - public string ProductGentime { get; set; } - [XmlElement(ElementName="productPolar")] - public string ProductPolar { get; set; } - } + [XmlRoot(ElementName = "productinfo")] + public class Productinfo + { + [XmlElement(ElementName = "NominalResolution")] + public string NominalResolution { get; set; } + [XmlElement(ElementName = "WidthInMeters")] + public string WidthInMeters { get; set; } + [XmlElement(ElementName = "productLevel")] + public string ProductLevel { get; set; } + [XmlElement(ElementName = "productType")] + public string ProductType { get; set; } + [XmlElement(ElementName = "productFormat")] + public string ProductFormat { get; set; } + [XmlElement(ElementName = "productGentime")] + public string ProductGentime { get; set; } + [XmlElement(ElementName = "productPolar")] + public string ProductPolar { get; set; } + } - [XmlRoot(ElementName="imagingTime")] - public class ImagingTime { - [XmlElement(ElementName="start")] - public string Start { get; set; } - [XmlElement(ElementName="end")] - public string End { get; set; } - } + [XmlRoot(ElementName = "imagingTime")] + public class ImagingTime + { + [XmlElement(ElementName = "start")] + public string Start { get; set; } + [XmlElement(ElementName = "end")] + public string End { get; set; } + } - [XmlRoot(ElementName="topLeft")] - public class TopLeft { - [XmlElement(ElementName="latitude")] - public string Latitude { get; set; } - [XmlElement(ElementName="longitude")] - public string Longitude { get; set; } - } + [XmlRoot(ElementName = "topLeft")] + public class TopLeft + { + [XmlElement(ElementName = "latitude")] + public string Latitude { get; set; } + [XmlElement(ElementName = "longitude")] + public string Longitude { get; set; } + } - [XmlRoot(ElementName="topRight")] - public class TopRight { - [XmlElement(ElementName="latitude")] - public string Latitude { get; set; } - [XmlElement(ElementName="longitude")] - public string Longitude { get; set; } - } + [XmlRoot(ElementName = "topRight")] + public class TopRight + { + [XmlElement(ElementName = "latitude")] + public string Latitude { get; set; } + [XmlElement(ElementName = "longitude")] + public string Longitude { get; set; } + } - [XmlRoot(ElementName="bottomLeft")] - public class BottomLeft { - [XmlElement(ElementName="latitude")] - public string Latitude { get; set; } - [XmlElement(ElementName="longitude")] - public string Longitude { get; set; } - } + [XmlRoot(ElementName = "bottomLeft")] + public class BottomLeft + { + [XmlElement(ElementName = "latitude")] + public string Latitude { get; set; } + [XmlElement(ElementName = "longitude")] + public string Longitude { get; set; } + } - [XmlRoot(ElementName="bottomRight")] - public class BottomRight { - [XmlElement(ElementName="latitude")] - public string Latitude { get; set; } - [XmlElement(ElementName="longitude")] - public string Longitude { get; set; } - } + [XmlRoot(ElementName = "bottomRight")] + public class BottomRight + { + [XmlElement(ElementName = "latitude")] + public string Latitude { get; set; } + [XmlElement(ElementName = "longitude")] + public string Longitude { get; set; } + } - [XmlRoot(ElementName="corner")] - public class Corner { - [XmlElement(ElementName="topLeft")] - public TopLeft TopLeft { get; set; } - [XmlElement(ElementName="topRight")] - public TopRight TopRight { get; set; } - [XmlElement(ElementName="bottomLeft")] - public BottomLeft BottomLeft { get; set; } - [XmlElement(ElementName="bottomRight")] - public BottomRight BottomRight { get; set; } - } + [XmlRoot(ElementName = "corner")] + public class Corner + { + [XmlElement(ElementName = "topLeft")] + public TopLeft TopLeft { get; set; } + [XmlElement(ElementName = "topRight")] + public TopRight TopRight { get; set; } + [XmlElement(ElementName = "bottomLeft")] + public BottomLeft BottomLeft { get; set; } + [XmlElement(ElementName = "bottomRight")] + public BottomRight BottomRight { get; set; } + } - [XmlRoot(ElementName="QualifyValue")] - public class QualifyValue { - [XmlElement(ElementName="HH")] - public string HH { get; set; } - [XmlElement(ElementName="HV")] - public string HV { get; set; } - [XmlElement(ElementName="VH")] - public string VH { get; set; } - [XmlElement(ElementName="VV")] - public string VV { get; set; } - } + [XmlRoot(ElementName = "QualifyValue")] + public class QualifyValue + { + [XmlElement(ElementName = "HH")] + public string HH { get; set; } + [XmlElement(ElementName = "HV")] + public string HV { get; set; } + [XmlElement(ElementName = "VH")] + public string VH { get; set; } + [XmlElement(ElementName = "VV")] + public string VV { get; set; } + } - [XmlRoot(ElementName="echoSaturation")] - public class EchoSaturation { - [XmlElement(ElementName="HH")] - public string HH { get; set; } - [XmlElement(ElementName="HV")] - public string HV { get; set; } - [XmlElement(ElementName="VH")] - public string VH { get; set; } - [XmlElement(ElementName="VV")] - public string VV { get; set; } - } + [XmlRoot(ElementName = "echoSaturation")] + public class EchoSaturation + { + [XmlElement(ElementName = "HH")] + public string HH { get; set; } + [XmlElement(ElementName = "HV")] + public string HV { get; set; } + [XmlElement(ElementName = "VH")] + public string VH { get; set; } + [XmlElement(ElementName = "VV")] + public string VV { get; set; } + } - [XmlRoot(ElementName="imageinfo")] - public class Imageinfo { - [XmlElement(ElementName="imagingTime")] - public ImagingTime ImagingTime { get; set; } - [XmlElement(ElementName="nearRange")] - public string NearRange { get; set; } - [XmlElement(ElementName="refRange")] - public string RefRange { get; set; } - [XmlElement(ElementName="eqvFs")] - public string EqvFs { get; set; } - [XmlElement(ElementName="eqvPRF")] - public string EqvPRF { get; set; } - [XmlElement(ElementName="center")] - public Center Center { get; set; } - [XmlElement(ElementName="corner")] - public Corner Corner { get; set; } - [XmlElement(ElementName="width")] - public int Width { get; set; } - [XmlElement(ElementName="height")] - public int Height { get; set; } - [XmlElement(ElementName="widthspace")] - public string Widthspace { get; set; } - [XmlElement(ElementName="heightspace")] - public string Heightspace { get; set; } - [XmlElement(ElementName="sceneShift")] - public string SceneShift { get; set; } - [XmlElement(ElementName="imagebit")] - public string Imagebit { get; set; } - [XmlElement(ElementName="QualifyValue")] - public QualifyValue QualifyValue { get; set; } - [XmlElement(ElementName="echoSaturation")] - public EchoSaturation EchoSaturation { get; set; } - } + [XmlRoot(ElementName = "imageinfo")] + public class Imageinfo + { + [XmlElement(ElementName = "imagingTime")] + public ImagingTime ImagingTime { get; set; } + [XmlElement(ElementName = "nearRange")] + public string NearRange { get; set; } + [XmlElement(ElementName = "refRange")] + public string RefRange { get; set; } + [XmlElement(ElementName = "eqvFs")] + public string EqvFs { get; set; } + [XmlElement(ElementName = "eqvPRF")] + public string EqvPRF { get; set; } + [XmlElement(ElementName = "center")] + public Center Center { get; set; } + [XmlElement(ElementName = "corner")] + public Corner Corner { get; set; } + [XmlElement(ElementName = "width")] + public int Width { get; set; } + [XmlElement(ElementName = "height")] + public int Height { get; set; } + [XmlElement(ElementName = "widthspace")] + public string Widthspace { get; set; } + [XmlElement(ElementName = "heightspace")] + public string Heightspace { get; set; } + [XmlElement(ElementName = "sceneShift")] + public string SceneShift { get; set; } + [XmlElement(ElementName = "imagebit")] + public string Imagebit { get; set; } + [XmlElement(ElementName = "QualifyValue")] + public QualifyValue QualifyValue { get; set; } + [XmlElement(ElementName = "echoSaturation")] + public EchoSaturation EchoSaturation { get; set; } + } - [XmlRoot(ElementName="CalibrationConst")] - public class CalibrationConst { - [XmlElement(ElementName="HH")] - public string HH { get; set; } - [XmlElement(ElementName="HV")] - public string HV { get; set; } - [XmlElement(ElementName="VH")] - public string VH { get; set; } - [XmlElement(ElementName="VV")] - public string VV { get; set; } - } + [XmlRoot(ElementName = "CalibrationConst")] + public class CalibrationConst + { + [XmlElement(ElementName = "HH")] + public string HH { get; set; } + [XmlElement(ElementName = "HV")] + public string HV { get; set; } + [XmlElement(ElementName = "VH")] + public string VH { get; set; } + [XmlElement(ElementName = "VV")] + public string VV { get; set; } + } - [XmlRoot(ElementName="DopplerCentroidCoefficients")] - public class DopplerCentroidCoefficients { - [XmlElement(ElementName="d0")] - public string D0 { get; set; } - [XmlElement(ElementName="d1")] - public string D1 { get; set; } - [XmlElement(ElementName="d2")] - public string D2 { get; set; } - [XmlElement(ElementName="d3")] - public string D3 { get; set; } - [XmlElement(ElementName="d4")] - public string D4 { get; set; } - } + [XmlRoot(ElementName = "DopplerCentroidCoefficients")] + public class DopplerCentroidCoefficients + { + [XmlElement(ElementName = "d0")] + public string D0 { get; set; } + [XmlElement(ElementName = "d1")] + public string D1 { get; set; } + [XmlElement(ElementName = "d2")] + public string D2 { get; set; } + [XmlElement(ElementName = "d3")] + public string D3 { get; set; } + [XmlElement(ElementName = "d4")] + public string D4 { get; set; } + } - [XmlRoot(ElementName="DopplerRateValuesCoefficients")] - public class DopplerRateValuesCoefficients { - [XmlElement(ElementName="r0")] - public string R0 { get; set; } - [XmlElement(ElementName="r1")] - public string R1 { get; set; } - [XmlElement(ElementName="r2")] - public string R2 { get; set; } - [XmlElement(ElementName="r3")] - public string R3 { get; set; } - [XmlElement(ElementName="r4")] - public string R4 { get; set; } - } + [XmlRoot(ElementName = "DopplerRateValuesCoefficients")] + public class DopplerRateValuesCoefficients + { + [XmlElement(ElementName = "r0")] + public string R0 { get; set; } + [XmlElement(ElementName = "r1")] + public string R1 { get; set; } + [XmlElement(ElementName = "r2")] + public string R2 { get; set; } + [XmlElement(ElementName = "r3")] + public string R3 { get; set; } + [XmlElement(ElementName = "r4")] + public string R4 { get; set; } + } - [XmlRoot(ElementName="processinfo")] - public class Processinfo { - [XmlElement(ElementName="EphemerisData")] - public string EphemerisData { get; set; } - [XmlElement(ElementName="AttitudeData")] - public string AttitudeData { get; set; } - [XmlElement(ElementName="algorithm")] - public string Algorithm { get; set; } - [XmlElement(ElementName="CalibrationConst")] - public CalibrationConst CalibrationConst { get; set; } - [XmlElement(ElementName="AzFdc0")] - public string AzFdc0 { get; set; } - [XmlElement(ElementName="AzFdc1")] - public string AzFdc1 { get; set; } - [XmlElement(ElementName="MultilookRange")] - public string MultilookRange { get; set; } - [XmlElement(ElementName="MultilookAzimuth")] - public string MultilookAzimuth { get; set; } - [XmlElement(ElementName="DoIQComp")] - public string DoIQComp { get; set; } - [XmlElement(ElementName="DoChaComp")] - public string DoChaComp { get; set; } - [XmlElement(ElementName="DoFPInnerImbalanceComp")] - public string DoFPInnerImbalanceComp { get; set; } - [XmlElement(ElementName="DoFPCalibration")] - public string DoFPCalibration { get; set; } - [XmlElement(ElementName="DoFdcEst")] - public string DoFdcEst { get; set; } - [XmlElement(ElementName="DoFrEst")] - public string DoFrEst { get; set; } - [XmlElement(ElementName="RangeWeightType")] - public string RangeWeightType { get; set; } - [XmlElement(ElementName="RangeWeightPara")] - public string RangeWeightPara { get; set; } - [XmlElement(ElementName="AzimuthWeightType")] - public string AzimuthWeightType { get; set; } - [XmlElement(ElementName="AzimuthWeightPara")] - public string AzimuthWeightPara { get; set; } - [XmlElement(ElementName="Sidelobe_Suppress_Flag")] - public string Sidelobe_Suppress_Flag { get; set; } - [XmlElement(ElementName="Speckle_Suppress_Flag")] - public string Speckle_Suppress_Flag { get; set; } - [XmlElement(ElementName="EarthModel")] - public string EarthModel { get; set; } - [XmlElement(ElementName="ProjectModel")] - public string ProjectModel { get; set; } - [XmlElement(ElementName="DEMModel")] - public string DEMModel { get; set; } - [XmlElement(ElementName="QualifyModel")] - public string QualifyModel { get; set; } - [XmlElement(ElementName="RadiometricModel")] - public string RadiometricModel { get; set; } - [XmlElement(ElementName="incidenceAngleNearRange")] - public string IncidenceAngleNearRange { get; set; } - [XmlElement(ElementName="incidenceAngleFarRange")] - public string IncidenceAngleFarRange { get; set; } - [XmlElement(ElementName="InnerCalibration")] - public string InnerCalibration { get; set; } - [XmlElement(ElementName="DifferentBetweenDifferentChannel")] - public string DifferentBetweenDifferentChannel { get; set; } - [XmlElement(ElementName="NumberOfPoleHHMissingLines")] - public string NumberOfPoleHHMissingLines { get; set; } - [XmlElement(ElementName="NumberOfPoleHVMissingLines")] - public string NumberOfPoleHVMissingLines { get; set; } - [XmlElement(ElementName="NumberOfPoleVHMissingLines")] - public string NumberOfPoleVHMissingLines { get; set; } - [XmlElement(ElementName="NumberOfPoleVVMissingLines")] - public string NumberOfPoleVVMissingLines { get; set; } - [XmlElement(ElementName="ReceiverSettableGain")] - public string ReceiverSettableGain { get; set; } - [XmlElement(ElementName="ProcessorGainCorrection")] - public string ProcessorGainCorrection { get; set; } - [XmlElement(ElementName="ElevationPatternCorrection")] - public string ElevationPatternCorrection { get; set; } - [XmlElement(ElementName="AmuthPatternCorrection")] - public string AmuthPatternCorrection { get; set; } - [XmlElement(ElementName="RangeLookBandWidth")] - public string RangeLookBandWidth { get; set; } - [XmlElement(ElementName="AzimuthLookBandWidth")] - public string AzimuthLookBandWidth { get; set; } - [XmlElement(ElementName="TotalProcessedAzimuthBandWidth")] - public string TotalProcessedAzimuthBandWidth { get; set; } - [XmlElement(ElementName="DopplerParametersReferenceTime")] - public string DopplerParametersReferenceTime { get; set; } - [XmlElement(ElementName="DopplerCentroidCoefficients")] - public DopplerCentroidCoefficients DopplerCentroidCoefficients { get; set; } - [XmlElement(ElementName="DopplerRateValuesCoefficients")] - public DopplerRateValuesCoefficients DopplerRateValuesCoefficients { get; set; } - [XmlElement(ElementName="DEM")] - public string DEM { get; set; } - } + [XmlRoot(ElementName = "processinfo")] + public class Processinfo + { + [XmlElement(ElementName = "EphemerisData")] + public string EphemerisData { get; set; } + [XmlElement(ElementName = "AttitudeData")] + public string AttitudeData { get; set; } + [XmlElement(ElementName = "algorithm")] + public string Algorithm { get; set; } + [XmlElement(ElementName = "CalibrationConst")] + public CalibrationConst CalibrationConst { get; set; } + [XmlElement(ElementName = "AzFdc0")] + public string AzFdc0 { get; set; } + [XmlElement(ElementName = "AzFdc1")] + public string AzFdc1 { get; set; } + [XmlElement(ElementName = "MultilookRange")] + public string MultilookRange { get; set; } + [XmlElement(ElementName = "MultilookAzimuth")] + public string MultilookAzimuth { get; set; } + [XmlElement(ElementName = "DoIQComp")] + public string DoIQComp { get; set; } + [XmlElement(ElementName = "DoChaComp")] + public string DoChaComp { get; set; } + [XmlElement(ElementName = "DoFPInnerImbalanceComp")] + public string DoFPInnerImbalanceComp { get; set; } + [XmlElement(ElementName = "DoFPCalibration")] + public string DoFPCalibration { get; set; } + [XmlElement(ElementName = "DoFdcEst")] + public string DoFdcEst { get; set; } + [XmlElement(ElementName = "DoFrEst")] + public string DoFrEst { get; set; } + [XmlElement(ElementName = "RangeWeightType")] + public string RangeWeightType { get; set; } + [XmlElement(ElementName = "RangeWeightPara")] + public string RangeWeightPara { get; set; } + [XmlElement(ElementName = "AzimuthWeightType")] + public string AzimuthWeightType { get; set; } + [XmlElement(ElementName = "AzimuthWeightPara")] + public string AzimuthWeightPara { get; set; } + [XmlElement(ElementName = "Sidelobe_Suppress_Flag")] + public string Sidelobe_Suppress_Flag { get; set; } + [XmlElement(ElementName = "Speckle_Suppress_Flag")] + public string Speckle_Suppress_Flag { get; set; } + [XmlElement(ElementName = "EarthModel")] + public string EarthModel { get; set; } + [XmlElement(ElementName = "ProjectModel")] + public string ProjectModel { get; set; } + [XmlElement(ElementName = "DEMModel")] + public string DEMModel { get; set; } + [XmlElement(ElementName = "QualifyModel")] + public string QualifyModel { get; set; } + [XmlElement(ElementName = "RadiometricModel")] + public string RadiometricModel { get; set; } + [XmlElement(ElementName = "incidenceAngleNearRange")] + public string IncidenceAngleNearRange { get; set; } + [XmlElement(ElementName = "incidenceAngleFarRange")] + public string IncidenceAngleFarRange { get; set; } + [XmlElement(ElementName = "InnerCalibration")] + public string InnerCalibration { get; set; } + [XmlElement(ElementName = "DifferentBetweenDifferentChannel")] + public string DifferentBetweenDifferentChannel { get; set; } + [XmlElement(ElementName = "NumberOfPoleHHMissingLines")] + public string NumberOfPoleHHMissingLines { get; set; } + [XmlElement(ElementName = "NumberOfPoleHVMissingLines")] + public string NumberOfPoleHVMissingLines { get; set; } + [XmlElement(ElementName = "NumberOfPoleVHMissingLines")] + public string NumberOfPoleVHMissingLines { get; set; } + [XmlElement(ElementName = "NumberOfPoleVVMissingLines")] + public string NumberOfPoleVVMissingLines { get; set; } + [XmlElement(ElementName = "ReceiverSettableGain")] + public string ReceiverSettableGain { get; set; } + [XmlElement(ElementName = "ProcessorGainCorrection")] + public string ProcessorGainCorrection { get; set; } + [XmlElement(ElementName = "ElevationPatternCorrection")] + public string ElevationPatternCorrection { get; set; } + [XmlElement(ElementName = "AmuthPatternCorrection")] + public string AmuthPatternCorrection { get; set; } + [XmlElement(ElementName = "RangeLookBandWidth")] + public string RangeLookBandWidth { get; set; } + [XmlElement(ElementName = "AzimuthLookBandWidth")] + public string AzimuthLookBandWidth { get; set; } + [XmlElement(ElementName = "TotalProcessedAzimuthBandWidth")] + public string TotalProcessedAzimuthBandWidth { get; set; } + [XmlElement(ElementName = "DopplerParametersReferenceTime")] + public string DopplerParametersReferenceTime { get; set; } + [XmlElement(ElementName = "DopplerCentroidCoefficients")] + public DopplerCentroidCoefficients DopplerCentroidCoefficients { get; set; } + [XmlElement(ElementName = "DopplerRateValuesCoefficients")] + public DopplerRateValuesCoefficients DopplerRateValuesCoefficients { get; set; } + [XmlElement(ElementName = "DEM")] + public string DEM { get; set; } + } - [XmlRoot(ElementName="product")] - public class ProductMetadata { - [XmlElement(ElementName="segmentID")] - public string SegmentID { get; set; } - [XmlElement(ElementName="sceneID")] - public string SceneID { get; set; } - [XmlElement(ElementName="satellite")] - public string Satellite { get; set; } - [XmlElement(ElementName="orbitID")] - public string OrbitID { get; set; } - [XmlElement(ElementName="orbitType")] - public string OrbitType { get; set; } - [XmlElement(ElementName="attiType")] - public string AttiType { get; set; } - [XmlElement(ElementName="Direction")] - public string Direction { get; set; } - [XmlElement(ElementName="productID")] - public string ProductID { get; set; } - [XmlElement(ElementName="DocumentIdentifier")] - public string DocumentIdentifier { get; set; } - [XmlElement(ElementName="ReceiveTime")] - public string ReceiveTime { get; set; } - [XmlElement(ElementName="IsZeroDopplerSteering")] - public string IsZeroDopplerSteering { get; set; } - [XmlElement(ElementName="Station")] - public string Station { get; set; } - [XmlElement(ElementName="sensor")] - public Sensor Sensor { get; set; } - [XmlElement(ElementName="platform")] - public Platform Platform { get; set; } - [XmlElement(ElementName="GPS")] - public GPS GPS { get; set; } - [XmlElement(ElementName="ATTI")] - public ATTI ATTI { get; set; } - [XmlElement(ElementName="productinfo")] - public Productinfo Productinfo { get; set; } - [XmlElement(ElementName="imageinfo")] - public Imageinfo Imageinfo { get; set; } - [XmlElement(ElementName="processinfo")] - public Processinfo Processinfo { get; set; } - } + [XmlRoot(ElementName = "product")] + public class ProductMetadata + { + [XmlElement(ElementName = "segmentID")] + public string SegmentID { get; set; } + [XmlElement(ElementName = "sceneID")] + public string SceneID { get; set; } + [XmlElement(ElementName = "satellite")] + public string Satellite { get; set; } + [XmlElement(ElementName = "orbitID")] + public string OrbitID { get; set; } + [XmlElement(ElementName = "orbitType")] + public string OrbitType { get; set; } + [XmlElement(ElementName = "attiType")] + public string AttiType { get; set; } + [XmlElement(ElementName = "Direction")] + public string Direction { get; set; } + [XmlElement(ElementName = "productID")] + public string ProductID { get; set; } + [XmlElement(ElementName = "DocumentIdentifier")] + public string DocumentIdentifier { get; set; } + [XmlElement(ElementName = "ReceiveTime")] + public string ReceiveTime { get; set; } + [XmlElement(ElementName = "IsZeroDopplerSteering")] + public string IsZeroDopplerSteering { get; set; } + [XmlElement(ElementName = "Station")] + public string Station { get; set; } + [XmlElement(ElementName = "sensor")] + public Sensor Sensor { get; set; } + [XmlElement(ElementName = "platform")] + public Platform Platform { get; set; } + [XmlElement(ElementName = "GPS")] + public GPS GPS { get; set; } + [XmlElement(ElementName = "ATTI")] + public ATTI ATTI { get; set; } + [XmlElement(ElementName = "productinfo")] + public Productinfo Productinfo { get; set; } + [XmlElement(ElementName = "imageinfo")] + public Imageinfo Imageinfo { get; set; } + [XmlElement(ElementName = "processinfo")] + public Processinfo Processinfo { get; set; } + } } diff --git a/src/Stars.Data/Model/Metadata/Gdal/GdalMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Gdal/GdalMetadataExtractor.cs index fc7bfa88..3a11d0b1 100644 --- a/src/Stars.Data/Model/Metadata/Gdal/GdalMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Gdal/GdalMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -8,12 +8,11 @@ using Microsoft.Extensions.Logging; using OSGeo.GDAL; using Stac; -using Stac.Extensions.File; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services.Plugins; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Gdal { @@ -31,12 +30,11 @@ public GdalMetadataExtractor(ILogger logger, IResourceSer public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { var gdalAsset = GetGdalAsset(item); - OSGeo.GDAL.Dataset dataset = LoadGdalAsset(gdalAsset).GetAwaiter().GetResult(); + Dataset dataset = LoadGdalAsset(gdalAsset).GetAwaiter().GetResult(); return true; } catch (Exception e) @@ -327,14 +325,14 @@ protected virtual KeyValuePair GetGdalAsset(IItem item) var gdalAsset = FindFirstKeyAssetFromFileNameRegex(item, GDALFILE_REGEX); if (gdalAsset.Key == null) { - throw new FileNotFoundException(String.Format("Unable to find the summary file asset")); + throw new FileNotFoundException(string.Format("Unable to find the summary file asset")); } return gdalAsset; } - public virtual async Task LoadGdalAsset(KeyValuePair gdalAsset) + public virtual async Task LoadGdalAsset(KeyValuePair gdalAsset) { - OSGeo.GDAL.Dataset dataset = OSGeo.GDAL.Gdal.Open(GetGdalPath(gdalAsset.Value), Access.GA_ReadOnly); + Dataset dataset = OSGeo.GDAL.Gdal.Open(GetGdalPath(gdalAsset.Value), Access.GA_ReadOnly); dataset.GetDriver(); diff --git a/src/Stars.Data/Model/Metadata/Geoeye/GeoeyeMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Geoeye/GeoeyeMetadataExtractor.cs index 457dcebb..de2d7653 100644 --- a/src/Stars.Data/Model/Metadata/Geoeye/GeoeyeMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Geoeye/GeoeyeMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -12,14 +12,14 @@ using Stac; using Stac.Extensions.Eo; using Stac.Extensions.Processing; +using Stac.Extensions.Projection; +using Stac.Extensions.Raster; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; -using Terradue.Stars.Services.Model.Stac; -using Stac.Extensions.Raster; using Terradue.Stars.Services; -using Stac.Extensions.Projection; -using Terradue.Stars.Geometry.GeoJson; +using Terradue.Stars.Services.Model.Stac; namespace Terradue.Stars.Data.Model.Metadata.Geoeye { @@ -31,8 +31,7 @@ public GeoeyeMetadataExtractor(ILogger logger, IResourc public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; IAsset metadata = FindFirstAssetFromFileNameRegex(item, "^(GE)[0-9a-zA-Z_-]*(\\.txt)$"); @@ -49,13 +48,8 @@ public override bool CanProcess(IResource route, IDestination destination) protected override async Task ExtractMetadata(IItem item, string suffix) { logger.LogDebug("Retrieving the metadata file in the product package"); - IAsset metadataFile = FindFirstAssetFromFileNameRegex(item, "^(GE)[0-9a-zA-Z_-]*(\\.txt)$"); - if (metadataFile == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } - - logger.LogDebug(String.Format("Metadata file is {0}", metadataFile.Uri)); + IAsset metadataFile = FindFirstAssetFromFileNameRegex(item, "^(GE)[0-9a-zA-Z_-]*(\\.txt)$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); + logger.LogDebug(string.Format("Metadata file is {0}", metadataFile.Uri)); // loading properties in dictionary @@ -98,7 +92,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi AddAssets(stacItem, metadata, isdMetadata, item); // AddEoBandPropertyInItem(stacItem); - return StacItemNode.Create(stacItem, item.Uri);; + return StacItemNode.Create(stacItem, item.Uri); ; } private void AddProcessingStacExtension(JavaProperties metadata, StacItem stacItem) @@ -188,7 +182,7 @@ private void AddRasterAsset(StacItem stacItem, IAsset asset, JavaProperties meta stacAsset.SetProperty("gsd", double.Parse(metadata["PIXEL_SIZE_X"])); stacAsset.ProjectionExtension().Shape = new int[] { isdMetadata.TIL.TILESIZEY, isdMetadata.TIL.TILESIZEX }; - + string key = ""; // GEOEYE-1 @@ -209,7 +203,7 @@ private void AddRasterAsset(StacItem stacItem, IAsset asset, JavaProperties meta rasterBandObjects.Add( CreateRasterBandObject(-1.7, 0.923 * (isdMetadata.IMD.BAND_P.ABSCALFACTOR / isdMetadata.IMD.BAND_P.EFFECTIVEBANDWIDTH))); - + } if (isdMetadata.IMD.BAND_B != null) { @@ -366,7 +360,7 @@ private void FillDateTimeProperties(JavaProperties metadata, } } - private void FillBasicsProperties(JavaProperties metadata, IDictionary properties) + private void FillBasicsProperties(JavaProperties metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -381,13 +375,13 @@ private void FillBasicsProperties(JavaProperties metadata, IDictionary properties) + private void AddOtherProperties(JavaProperties metadata, IDictionary properties) { if (IncludeProviderProperty) { AddSingleProvider( properties, - "DigitalGlobe/Maxar", + "DigitalGlobe/Maxar", "GeoEye-1 is a high-resolution imaging satellite. GeoEye-1 imagery is used for air and marine transportation, defence, disaster response, oil and gas exploration, mining exploration and production, mapping of remote regions, insurance and risk management, location-based services and agricultural crop management.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://gisgeography.com/digitalglobe-satellite-imagery/") @@ -456,4 +450,4 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometryObjectFromProductMetadat return new GeoJSON.Net.Geometry.Polygon(new[] { lineString }).NormalizePolygon(); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Geoeye/IsdMetadata.cs b/src/Stars.Data/Model/Metadata/Geoeye/IsdMetadata.cs index 2686581a..242e68cd 100644 --- a/src/Stars.Data/Model/Metadata/Geoeye/IsdMetadata.cs +++ b/src/Stars.Data/Model/Metadata/Geoeye/IsdMetadata.cs @@ -1,11 +1,12 @@ -using System; +using System.Collections.Generic; using System.Xml.Serialization; -using System.Collections.Generic; -namespace Terradue.Stars.Data.Model.Metadata.Geoeye { +namespace Terradue.Stars.Data.Model.Metadata.Geoeye +{ [XmlRoot(ElementName = "BAND")] - public class BAND { + public class BAND + { [XmlElement(ElementName = "ULLON")] public string ULLON { get; set; } [XmlElement(ElementName = "ULLAT")] public string ULLAT { get; set; } [XmlElement(ElementName = "ULHAE")] public string ULHAE { get; set; } @@ -33,12 +34,14 @@ public class BAND { } [XmlRoot(ElementName = "TLCLISTList")] - public class TLCLISTList { + public class TLCLISTList + { [XmlElement(ElementName = "TLCLIST")] public List TLCLIST { get; set; } } [XmlRoot(ElementName = "IMAGE")] - public class IMAGE { + public class IMAGE + { [XmlElement(ElementName = "SATID")] public string SATID { get; set; } [XmlElement(ElementName = "MODE")] public string MODE { get; set; } @@ -211,7 +214,8 @@ public class IMAGE { } [XmlRoot(ElementName = "IMD")] - public class IMD { + public class IMD + { [XmlElement(ElementName = "VERSION")] public string VERSION { get; set; } [XmlElement(ElementName = "GENERATIONTIME")] @@ -282,13 +286,15 @@ public class IMD { } [XmlRoot(ElementName = "EPHEMLISTList")] - public class EPHEMLISTList { + public class EPHEMLISTList + { [XmlElement(ElementName = "EPHEMLIST")] public List EPHEMLIST { get; set; } } [XmlRoot(ElementName = "EPH")] - public class EPH { + public class EPH + { [XmlElement(ElementName = "SATID")] public string SATID { get; set; } [XmlElement(ElementName = "REVNUMBER")] @@ -315,12 +321,14 @@ public class EPH { } [XmlRoot(ElementName = "ATTLISTList")] - public class ATTLISTList { + public class ATTLISTList + { [XmlElement(ElementName = "ATTLIST")] public List ATTLIST { get; set; } } [XmlRoot(ElementName = "ATT")] - public class ATT { + public class ATT + { [XmlElement(ElementName = "SATID")] public string SATID { get; set; } [XmlElement(ElementName = "REVNUMBER")] @@ -347,7 +355,8 @@ public class ATT { } [XmlRoot(ElementName = "TILE")] - public class TILE { + public class TILE + { [XmlElement(ElementName = "FILENAME")] public string FILENAME { get; set; } [XmlElement(ElementName = "ULCOLOFFSET")] @@ -385,7 +394,8 @@ public class TILE { } [XmlRoot(ElementName = "TIL")] - public class TIL { + public class TIL + { [XmlElement(ElementName = "BANDID")] public string BANDID { get; set; } [XmlElement(ElementName = "NUMTILES")] public string NUMTILES { get; set; } @@ -405,7 +415,8 @@ public class TIL { } [XmlRoot(ElementName = "PRINCIPAL_DISTANCE")] - public class PRINCIPAL_DISTANCE { + public class PRINCIPAL_DISTANCE + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -413,7 +424,8 @@ public class PRINCIPAL_DISTANCE { } [XmlRoot(ElementName = "OPTICAL_DISTORTION")] - public class OPTICAL_DISTORTION { + public class OPTICAL_DISTORTION + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -428,7 +440,8 @@ public class OPTICAL_DISTORTION { } [XmlRoot(ElementName = "PERSPECTIVE_CENTER")] - public class PERSPECTIVE_CENTER { + public class PERSPECTIVE_CENTER + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -438,7 +451,8 @@ public class PERSPECTIVE_CENTER { } [XmlRoot(ElementName = "CAMERA_ATTITUDE")] - public class CAMERA_ATTITUDE { + public class CAMERA_ATTITUDE + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -449,7 +463,8 @@ public class CAMERA_ATTITUDE { } [XmlRoot(ElementName = "DETECTOR_ARRAY")] - public class DETECTOR_ARRAY { + public class DETECTOR_ARRAY + { [XmlElement(ElementName = "DETARRID")] public string DETARRID { get; set; } [XmlElement(ElementName = "DETORIGINX")] @@ -465,7 +480,8 @@ public class DETECTOR_ARRAY { } [XmlRoot(ElementName = "DETECTOR_MOUNTING")] - public class DETECTOR_MOUNTING { + public class DETECTOR_MOUNTING + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -473,7 +489,8 @@ public class DETECTOR_MOUNTING { } [XmlRoot(ElementName = "GEO")] - public class GEO { + public class GEO + { [XmlElement(ElementName = "EFFECTIVETIME")] public string EFFECTIVETIME { get; set; } @@ -502,31 +519,36 @@ public class GEO { } [XmlRoot(ElementName = "LINENUMCOEFList")] - public class LINENUMCOEFList { + public class LINENUMCOEFList + { [XmlElement(ElementName = "LINENUMCOEF")] public string LINENUMCOEF { get; set; } } [XmlRoot(ElementName = "LINEDENCOEFList")] - public class LINEDENCOEFList { + public class LINEDENCOEFList + { [XmlElement(ElementName = "LINEDENCOEF")] public string LINEDENCOEF { get; set; } } [XmlRoot(ElementName = "SAMPNUMCOEFList")] - public class SAMPNUMCOEFList { + public class SAMPNUMCOEFList + { [XmlElement(ElementName = "SAMPNUMCOEF")] public string SAMPNUMCOEF { get; set; } } [XmlRoot(ElementName = "SAMPDENCOEFList")] - public class SAMPDENCOEFList { + public class SAMPDENCOEFList + { [XmlElement(ElementName = "SAMPDENCOEF")] public string SAMPDENCOEF { get; set; } } [XmlRoot(ElementName = "RPB")] - public class RPB { + public class RPB + { [XmlElement(ElementName = "SATID")] public string SATID { get; set; } [XmlElement(ElementName = "BANDID")] public string BANDID { get; set; } [XmlElement(ElementName = "SPECID")] public string SPECID { get; set; } @@ -534,7 +556,8 @@ public class RPB { } [XmlRoot(ElementName = "isd")] - public class Isd { + public class Isd + { [XmlElement(ElementName = "IMD")] public IMD IMD { get; set; } [XmlElement(ElementName = "EPH")] public EPH EPH { get; set; } [XmlElement(ElementName = "ATT")] public ATT ATT { get; set; } @@ -542,4 +565,4 @@ public class Isd { [XmlElement(ElementName = "GEO")] public GEO GEO { get; set; } [XmlElement(ElementName = "RPB")] public RPB RPB { get; set; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Iceye/IceyeMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Iceye/IceyeMetadataExtractor.cs index 4e7d54b9..7ba95255 100644 --- a/src/Stars.Data/Model/Metadata/Iceye/IceyeMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Iceye/IceyeMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -13,10 +13,10 @@ using Stac.Extensions.Sar; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Iceye { @@ -32,8 +32,7 @@ public IceyeMetadataExtractor(ILogger logger, IResourceS public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset metadataAsset = GetMetadataAsset(item); @@ -202,7 +201,7 @@ private void FillDateTimeProperties(Schemas.Metadata metadata, Dictionary properties) + private void FillBasicsProperties(Schemas.Metadata metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -217,13 +216,13 @@ private void FillBasicsProperties(Schemas.Metadata metadata, IDictionary properties) + private void AddOtherProperties(Schemas.Metadata metadata, IDictionary properties) { if (IncludeProviderProperty) { AddSingleProvider( properties, - "ICEYE", + "ICEYE", "The ICEYE constellation is a constellation of X-band Synthetic Aperture Radar (SAR) Satellites. The ICEYE constellation is designed to provide persistent monitoring capabilities and a high resolution view of the Earth’s surface, with an overall mission objective to enable better decision making by providing timely and reliable Earth observation data.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.iceye.com/sar-data") @@ -274,7 +273,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat private void AddBandAsset(StacItem stacItem, IAsset bandAsset, Schemas.Metadata metadata) { - StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, bandAsset.Uri, new System.Net.Mime.ContentType("image/x.geotiff")); + StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, bandAsset.Uri, new ContentType("image/x.geotiff")); stacAsset.Properties.AddRange(bandAsset.Properties); stacAsset.SetProperty("gsd", GetGroundSampleDistance(metadata)); stacAsset.SarExtension().Polarizations = GetPolarizations(metadata); @@ -322,11 +321,7 @@ private double GetGroundSampleDistance(string mode) protected virtual IAsset GetMetadataAsset(IItem item) { - IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"ICEYE.*\.xml$"); - if (manifestAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } + IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"ICEYE.*\.xml$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); return manifestAsset; } diff --git a/src/Stars.Data/Model/Metadata/Iceye/Schemas/Metadata.cs b/src/Stars.Data/Model/Metadata/Iceye/Schemas/Metadata.cs index 25753757..70d29656 100644 --- a/src/Stars.Data/Model/Metadata/Iceye/Schemas/Metadata.cs +++ b/src/Stars.Data/Model/Metadata/Iceye/Schemas/Metadata.cs @@ -1,11 +1,11 @@ -namespace Terradue.Stars.Data.Model.Metadata.Iceye.Schemas +namespace Terradue.Stars.Data.Model.Metadata.Iceye.Schemas { /// - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] - [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] + [System.Xml.Serialization.XmlType(AnonymousType = true)] + [System.Xml.Serialization.XmlRoot(Namespace = "", IsNullable = false)] public partial class coefficient { @@ -19,11 +19,11 @@ public string number { get { - return this.numberField; + return numberField; } set { - this.numberField = value; + numberField = value; } } @@ -33,19 +33,19 @@ public string value { get { - return this.valueField; + return valueField; } set { - this.valueField = value; + valueField = value; } } } /// - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] - [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] + [System.Xml.Serialization.XmlType(AnonymousType = true)] + [System.Xml.Serialization.XmlRoot(Namespace = "", IsNullable = false)] public partial class Metadata { @@ -203,11 +203,11 @@ public string spec_version { get { - return this.spec_versionField; + return spec_versionField; } set { - this.spec_versionField = value; + spec_versionField = value; } } @@ -217,11 +217,11 @@ public string product_file { get { - return this.product_fileField; + return product_fileField; } set { - this.product_fileField = value; + product_fileField = value; } } @@ -231,11 +231,11 @@ public string product_name { get { - return this.product_nameField; + return product_nameField; } set { - this.product_nameField = value; + product_nameField = value; } } @@ -245,11 +245,11 @@ public string product_type { get { - return this.product_typeField; + return product_typeField; } set { - this.product_typeField = value; + product_typeField = value; } } @@ -259,11 +259,11 @@ public string product_level { get { - return this.product_levelField; + return product_levelField; } set { - this.product_levelField = value; + product_levelField = value; } } @@ -273,11 +273,11 @@ public string satellite_name { get { - return this.satellite_nameField; + return satellite_nameField; } set { - this.satellite_nameField = value; + satellite_nameField = value; } } @@ -287,11 +287,11 @@ public string acquisition_mode { get { - return this.acquisition_modeField; + return acquisition_modeField; } set { - this.acquisition_modeField = value; + acquisition_modeField = value; } } @@ -301,11 +301,11 @@ public string look_side { get { - return this.look_sideField; + return look_sideField; } set { - this.look_sideField = value; + look_sideField = value; } } @@ -315,11 +315,11 @@ public double satellite_look_angle { get { - return this.satellite_look_angleField; + return satellite_look_angleField; } set { - this.satellite_look_angleField = value; + satellite_look_angleField = value; } } @@ -329,11 +329,11 @@ public string processing_time { get { - return this.processing_timeField; + return processing_timeField; } set { - this.processing_timeField = value; + processing_timeField = value; } } @@ -343,11 +343,11 @@ public string processor_version { get { - return this.processor_versionField; + return processor_versionField; } set { - this.processor_versionField = value; + processor_versionField = value; } } @@ -357,11 +357,11 @@ public string acquisition_start_utc { get { - return this.acquisition_start_utcField; + return acquisition_start_utcField; } set { - this.acquisition_start_utcField = value; + acquisition_start_utcField = value; } } @@ -371,11 +371,11 @@ public string acquisition_end_utc { get { - return this.acquisition_end_utcField; + return acquisition_end_utcField; } set { - this.acquisition_end_utcField = value; + acquisition_end_utcField = value; } } @@ -385,11 +385,11 @@ public string zerodoppler_start_utc { get { - return this.zerodoppler_start_utcField; + return zerodoppler_start_utcField; } set { - this.zerodoppler_start_utcField = value; + zerodoppler_start_utcField = value; } } @@ -399,11 +399,11 @@ public string zerodoppler_end_utc { get { - return this.zerodoppler_end_utcField; + return zerodoppler_end_utcField; } set { - this.zerodoppler_end_utcField = value; + zerodoppler_end_utcField = value; } } @@ -413,11 +413,11 @@ public int number_of_azimuth_samples { get { - return this.number_of_azimuth_samplesField; + return number_of_azimuth_samplesField; } set { - this.number_of_azimuth_samplesField = value; + number_of_azimuth_samplesField = value; } } @@ -427,11 +427,11 @@ public int number_of_range_samples { get { - return this.number_of_range_samplesField; + return number_of_range_samplesField; } set { - this.number_of_range_samplesField = value; + number_of_range_samplesField = value; } } @@ -441,11 +441,11 @@ public string orbit_repeat_cycle { get { - return this.orbit_repeat_cycleField; + return orbit_repeat_cycleField; } set { - this.orbit_repeat_cycleField = value; + orbit_repeat_cycleField = value; } } @@ -455,11 +455,11 @@ public int orbit_relative_number { get { - return this.orbit_relative_numberField; + return orbit_relative_numberField; } set { - this.orbit_relative_numberField = value; + orbit_relative_numberField = value; } } @@ -469,11 +469,11 @@ public int orbit_absolute_number { get { - return this.orbit_absolute_numberField; + return orbit_absolute_numberField; } set { - this.orbit_absolute_numberField = value; + orbit_absolute_numberField = value; } } @@ -483,11 +483,11 @@ public string orbit_direction { get { - return this.orbit_directionField; + return orbit_directionField; } set { - this.orbit_directionField = value; + orbit_directionField = value; } } @@ -497,11 +497,11 @@ public string sample_precision { get { - return this.sample_precisionField; + return sample_precisionField; } set { - this.sample_precisionField = value; + sample_precisionField = value; } } @@ -511,11 +511,11 @@ public string polarization { get { - return this.polarizationField; + return polarizationField; } set { - this.polarizationField = value; + polarizationField = value; } } @@ -525,11 +525,11 @@ public string azimuth_looks { get { - return this.azimuth_looksField; + return azimuth_looksField; } set { - this.azimuth_looksField = value; + azimuth_looksField = value; } } @@ -539,11 +539,11 @@ public string range_looks { get { - return this.range_looksField; + return range_looksField; } set { - this.range_looksField = value; + range_looksField = value; } } @@ -553,11 +553,11 @@ public string range_look_bandwidth { get { - return this.range_look_bandwidthField; + return range_look_bandwidthField; } set { - this.range_look_bandwidthField = value; + range_look_bandwidthField = value; } } @@ -567,11 +567,11 @@ public string range_look_overlap { get { - return this.range_look_overlapField; + return range_look_overlapField; } set { - this.range_look_overlapField = value; + range_look_overlapField = value; } } @@ -581,11 +581,11 @@ public string azimuth_look_bandwidth { get { - return this.azimuth_look_bandwidthField; + return azimuth_look_bandwidthField; } set { - this.azimuth_look_bandwidthField = value; + azimuth_look_bandwidthField = value; } } @@ -595,11 +595,11 @@ public string azimuth_look_overlap { get { - return this.azimuth_look_overlapField; + return azimuth_look_overlapField; } set { - this.azimuth_look_overlapField = value; + azimuth_look_overlapField = value; } } @@ -609,11 +609,11 @@ public string range_spacing { get { - return this.range_spacingField; + return range_spacingField; } set { - this.range_spacingField = value; + range_spacingField = value; } } @@ -623,11 +623,11 @@ public string azimuth_spacing { get { - return this.azimuth_spacingField; + return azimuth_spacingField; } set { - this.azimuth_spacingField = value; + azimuth_spacingField = value; } } @@ -637,11 +637,11 @@ public string acquisition_prf { get { - return this.acquisition_prfField; + return acquisition_prfField; } set { - this.acquisition_prfField = value; + acquisition_prfField = value; } } @@ -651,11 +651,11 @@ public string processing_prf { get { - return this.processing_prfField; + return processing_prfField; } set { - this.processing_prfField = value; + processing_prfField = value; } } @@ -665,11 +665,11 @@ public string carrier_frequency { get { - return this.carrier_frequencyField; + return carrier_frequencyField; } set { - this.carrier_frequencyField = value; + carrier_frequencyField = value; } } @@ -679,11 +679,11 @@ public string first_pixel_time { get { - return this.first_pixel_timeField; + return first_pixel_timeField; } set { - this.first_pixel_timeField = value; + first_pixel_timeField = value; } } @@ -693,11 +693,11 @@ public string slant_range_to_first_pixel { get { - return this.slant_range_to_first_pixelField; + return slant_range_to_first_pixelField; } set { - this.slant_range_to_first_pixelField = value; + slant_range_to_first_pixelField = value; } } @@ -707,11 +707,11 @@ public string azimuth_time_interval { get { - return this.azimuth_time_intervalField; + return azimuth_time_intervalField; } set { - this.azimuth_time_intervalField = value; + azimuth_time_intervalField = value; } } @@ -721,11 +721,11 @@ public string range_sampling_rate { get { - return this.range_sampling_rateField; + return range_sampling_rateField; } set { - this.range_sampling_rateField = value; + range_sampling_rateField = value; } } @@ -735,11 +735,11 @@ public string chirp_bandwidth { get { - return this.chirp_bandwidthField; + return chirp_bandwidthField; } set { - this.chirp_bandwidthField = value; + chirp_bandwidthField = value; } } @@ -749,11 +749,11 @@ public string chirp_duration { get { - return this.chirp_durationField; + return chirp_durationField; } set { - this.chirp_durationField = value; + chirp_durationField = value; } } @@ -763,11 +763,11 @@ public string total_processed_bandwidth_azimuth { get { - return this.total_processed_bandwidth_azimuthField; + return total_processed_bandwidth_azimuthField; } set { - this.total_processed_bandwidth_azimuthField = value; + total_processed_bandwidth_azimuthField = value; } } @@ -777,11 +777,11 @@ public string window_function_range { get { - return this.window_function_rangeField; + return window_function_rangeField; } set { - this.window_function_rangeField = value; + window_function_rangeField = value; } } @@ -791,11 +791,11 @@ public string window_function_azimuth { get { - return this.window_function_azimuthField; + return window_function_azimuthField; } set { - this.window_function_azimuthField = value; + window_function_azimuthField = value; } } @@ -805,11 +805,11 @@ public string range_spread_comp_flag { get { - return this.range_spread_comp_flagField; + return range_spread_comp_flagField; } set { - this.range_spread_comp_flagField = value; + range_spread_comp_flagField = value; } } @@ -819,11 +819,11 @@ public string ant_elev_corr_flag { get { - return this.ant_elev_corr_flagField; + return ant_elev_corr_flagField; } set { - this.ant_elev_corr_flagField = value; + ant_elev_corr_flagField = value; } } @@ -833,11 +833,11 @@ public string number_of_dc_estimations { get { - return this.number_of_dc_estimationsField; + return number_of_dc_estimationsField; } set { - this.number_of_dc_estimationsField = value; + number_of_dc_estimationsField = value; } } @@ -847,11 +847,11 @@ public string dc_estimate_poly_order { get { - return this.dc_estimate_poly_orderField; + return dc_estimate_poly_orderField; } set { - this.dc_estimate_poly_orderField = value; + dc_estimate_poly_orderField = value; } } @@ -861,11 +861,11 @@ public string doppler_rate_poly_order { get { - return this.doppler_rate_poly_orderField; + return doppler_rate_poly_orderField; } set { - this.doppler_rate_poly_orderField = value; + doppler_rate_poly_orderField = value; } } @@ -875,11 +875,11 @@ public string grsr_poly_order { get { - return this.grsr_poly_orderField; + return grsr_poly_orderField; } set { - this.grsr_poly_orderField = value; + grsr_poly_orderField = value; } } @@ -889,11 +889,11 @@ public string incidence_angle_poly_order { get { - return this.incidence_angle_poly_orderField; + return incidence_angle_poly_orderField; } set { - this.incidence_angle_poly_orderField = value; + incidence_angle_poly_orderField = value; } } @@ -903,11 +903,11 @@ public string gcp_terrain_model { get { - return this.gcp_terrain_modelField; + return gcp_terrain_modelField; } set { - this.gcp_terrain_modelField = value; + gcp_terrain_modelField = value; } } @@ -917,11 +917,11 @@ public string geo_ref_system { get { - return this.geo_ref_systemField; + return geo_ref_systemField; } set { - this.geo_ref_systemField = value; + geo_ref_systemField = value; } } @@ -931,11 +931,11 @@ public string avg_scene_height { get { - return this.avg_scene_heightField; + return avg_scene_heightField; } set { - this.avg_scene_heightField = value; + avg_scene_heightField = value; } } @@ -945,11 +945,11 @@ public string mean_orbit_altitude { get { - return this.mean_orbit_altitudeField; + return mean_orbit_altitudeField; } set { - this.mean_orbit_altitudeField = value; + mean_orbit_altitudeField = value; } } @@ -959,11 +959,11 @@ public string mean_earth_radius { get { - return this.mean_earth_radiusField; + return mean_earth_radiusField; } set { - this.mean_earth_radiusField = value; + mean_earth_radiusField = value; } } @@ -973,11 +973,11 @@ public string coord_first_near { get { - return this.coord_first_nearField; + return coord_first_nearField; } set { - this.coord_first_nearField = value; + coord_first_nearField = value; } } @@ -987,11 +987,11 @@ public string coord_first_far { get { - return this.coord_first_farField; + return coord_first_farField; } set { - this.coord_first_farField = value; + coord_first_farField = value; } } @@ -1001,11 +1001,11 @@ public string coord_last_near { get { - return this.coord_last_nearField; + return coord_last_nearField; } set { - this.coord_last_nearField = value; + coord_last_nearField = value; } } @@ -1015,11 +1015,11 @@ public string coord_last_far { get { - return this.coord_last_farField; + return coord_last_farField; } set { - this.coord_last_farField = value; + coord_last_farField = value; } } @@ -1029,11 +1029,11 @@ public string coord_center { get { - return this.coord_centerField; + return coord_centerField; } set { - this.coord_centerField = value; + coord_centerField = value; } } @@ -1043,11 +1043,11 @@ public string heading { get { - return this.headingField; + return headingField; } set { - this.headingField = value; + headingField = value; } } @@ -1057,11 +1057,11 @@ public string incidence_near { get { - return this.incidence_nearField; + return incidence_nearField; } set { - this.incidence_nearField = value; + incidence_nearField = value; } } @@ -1071,11 +1071,11 @@ public double incidence_center { get { - return this.incidence_centerField; + return incidence_centerField; } set { - this.incidence_centerField = value; + incidence_centerField = value; } } @@ -1085,11 +1085,11 @@ public string incidence_far { get { - return this.incidence_farField; + return incidence_farField; } set { - this.incidence_farField = value; + incidence_farField = value; } } @@ -1099,11 +1099,11 @@ public string calibration_factor { get { - return this.calibration_factorField; + return calibration_factorField; } set { - this.calibration_factorField = value; + calibration_factorField = value; } } @@ -1113,11 +1113,11 @@ public string orbit_processing_level { get { - return this.orbit_processing_levelField; + return orbit_processing_levelField; } set { - this.orbit_processing_levelField = value; + orbit_processing_levelField = value; } } @@ -1127,11 +1127,11 @@ public string tropo_range_delay { get { - return this.tropo_range_delayField; + return tropo_range_delayField; } set { - this.tropo_range_delayField = value; + tropo_range_delayField = value; } } @@ -1141,11 +1141,11 @@ public string data_orientation { get { - return this.data_orientationField; + return data_orientationField; } set { - this.data_orientationField = value; + data_orientationField = value; } } } diff --git a/src/Stars.Data/Model/Metadata/Inpe/InpeMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Inpe/InpeMetadataExtractor.cs index d8c0d1a3..6d300d07 100644 --- a/src/Stars.Data/Model/Metadata/Inpe/InpeMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Inpe/InpeMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -12,23 +12,23 @@ using Microsoft.Extensions.Logging; using Stac; using Stac.Extensions.Eo; -using Stac.Extensions.Projection; using Stac.Extensions.Processing; +using Stac.Extensions.Projection; +using Stac.Extensions.Raster; using Stac.Extensions.Sat; using Stac.Extensions.View; -using Stac.Extensions.Raster; using Terradue.Stars.Data.Model.Metadata.Inpe.Schemas; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Inpe { public class InpeMetadataExtractor : MetadataExtraction { private static Regex identifierRegex = new Regex(@"(?'id1'(CBERS_4A?|AMAZONIA-1)_(?'type'[^_]+)_\d{8}_\d{3}_\d{3}_L(?'level'[^_]+))(_LEFT|RIGHT)?(?'id2'_BAND(?'band'\d+))"); - + // alternative identifier regex for for filename of // this type 956-INPE-CBERS-4-urn_ogc_def_EOP_INPE_CBERS_4_AWFI_20220731_111_063_L4_B_compose private static Regex identifierRegex2 = new Regex(@".*_inpe_(call[0-9]*|cbers_4a?|amazonia_1)_(?'type'[^_]+)_\d{8}_\d{3}_\d{3}_l(?'level'[^_]+)_(band|b)?(\d+)?(.+)?\.csv$"); @@ -44,7 +44,7 @@ public class InpeMetadataExtractor : MetadataExtraction {"CBERS-4A", "2019-093E"}, {"AMAZONIA-1", "2021-015A"}, }; - + // Dictionary containing the bands offered by each spectral mode private Dictionary spectralModeBandsCbers = new Dictionary { {"AWFI", new int[] {13, 14, 15, 16}}, @@ -75,9 +75,7 @@ public InpeMetadataExtractor(ILogger logger, public override bool CanProcess(IResource route, IDestination destination) { - - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset metadataAsset = GetMetadataAsset(item); @@ -167,10 +165,10 @@ internal virtual StacItem CreateStacItem(Schemas.Metadata metadata, Dictionary bands, string suffix = "") + private void FindBands(prdfImage image, Dictionary bands, string suffix = "") { if (image == null) return; - if (image.band0 != null) bands[String.Format("band-0{0}", suffix)] = image.band0; - if (image.band1 != null) bands[String.Format("band-1{0}", suffix)] = image.band1; - if (image.band2 != null) bands[String.Format("band-2{0}", suffix)] = image.band2; - if (image.band3 != null) bands[String.Format("band-3{0}", suffix)] = image.band3; - if (image.band4 != null) bands[String.Format("band-4{0}", suffix)] = image.band4; - if (image.band5 != null) bands[String.Format("band-5{0}", suffix)] = image.band5; - if (image.band6 != null) bands[String.Format("band-6{0}", suffix)] = image.band6; - if (image.band7 != null) bands[String.Format("band-7{0}", suffix)] = image.band7; - if (image.band8 != null) bands[String.Format("band-8{0}", suffix)] = image.band8; - if (image.band13 != null) bands[String.Format("band-13{0}", suffix)] = image.band13; - if (image.band14 != null) bands[String.Format("band-14{0}", suffix)] = image.band14; - if (image.band15 != null) bands[String.Format("band-15{0}", suffix)] = image.band15; - if (image.band16 != null) bands[String.Format("band-16{0}", suffix)] = image.band16; + if (image.band0 != null) bands[string.Format("band-0{0}", suffix)] = image.band0; + if (image.band1 != null) bands[string.Format("band-1{0}", suffix)] = image.band1; + if (image.band2 != null) bands[string.Format("band-2{0}", suffix)] = image.band2; + if (image.band3 != null) bands[string.Format("band-3{0}", suffix)] = image.band3; + if (image.band4 != null) bands[string.Format("band-4{0}", suffix)] = image.band4; + if (image.band5 != null) bands[string.Format("band-5{0}", suffix)] = image.band5; + if (image.band6 != null) bands[string.Format("band-6{0}", suffix)] = image.band6; + if (image.band7 != null) bands[string.Format("band-7{0}", suffix)] = image.band7; + if (image.band8 != null) bands[string.Format("band-8{0}", suffix)] = image.band8; + if (image.band13 != null) bands[string.Format("band-13{0}", suffix)] = image.band13; + if (image.band14 != null) bands[string.Format("band-14{0}", suffix)] = image.band14; + if (image.band15 != null) bands[string.Format("band-15{0}", suffix)] = image.band15; + if (image.band16 != null) bands[string.Format("band-16{0}", suffix)] = image.band16; } @@ -227,16 +225,16 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometry(Schemas.Metadata metada GeoJSON.Net.Geometry.LineString lineString = new GeoJSON.Net.Geometry.LineString( new GeoJSON.Net.Geometry.Position[] { - new GeoJSON.Net.Geometry.Position(Double.Parse(metadata.image.boundingBox.LL.latitude), - Double.Parse(metadata.image.boundingBox.LL.longitude)), - new GeoJSON.Net.Geometry.Position(Double.Parse(metadata.image.boundingBox.LR.latitude), - Double.Parse(metadata.image.boundingBox.LR.longitude)), - new GeoJSON.Net.Geometry.Position(Double.Parse(metadata.image.boundingBox.UR.latitude), - Double.Parse(metadata.image.boundingBox.UR.longitude)), - new GeoJSON.Net.Geometry.Position(Double.Parse(metadata.image.boundingBox.UL.latitude), - Double.Parse(metadata.image.boundingBox.UL.longitude)), - new GeoJSON.Net.Geometry.Position(Double.Parse(metadata.image.boundingBox.LL.latitude), - Double.Parse(metadata.image.boundingBox.LL.longitude)), + new GeoJSON.Net.Geometry.Position(double.Parse(metadata.image.boundingBox.LL.latitude), + double.Parse(metadata.image.boundingBox.LL.longitude)), + new GeoJSON.Net.Geometry.Position(double.Parse(metadata.image.boundingBox.LR.latitude), + double.Parse(metadata.image.boundingBox.LR.longitude)), + new GeoJSON.Net.Geometry.Position(double.Parse(metadata.image.boundingBox.UR.latitude), + double.Parse(metadata.image.boundingBox.UR.longitude)), + new GeoJSON.Net.Geometry.Position(double.Parse(metadata.image.boundingBox.UL.latitude), + double.Parse(metadata.image.boundingBox.UL.longitude)), + new GeoJSON.Net.Geometry.Position(double.Parse(metadata.image.boundingBox.LL.latitude), + double.Parse(metadata.image.boundingBox.LL.longitude)), } ); return new GeoJSON.Net.Geometry.Polygon(new GeoJSON.Net.Geometry.LineString[] { lineString }) @@ -246,12 +244,7 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometry(Schemas.Metadata metada protected virtual IAsset GetMetadataAsset(IItem item) { - IAsset metadataAsset = FindFirstAssetFromFileNameRegex(item, metadataAssetRegexPattern); - if (metadataAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } - + IAsset metadataAsset = FindFirstAssetFromFileNameRegex(item, metadataAssetRegexPattern) ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); return metadataAsset; } @@ -293,7 +286,7 @@ protected virtual IAsset GetMetadataAsset(IItem item) case "WPM": break; default: - throw new InvalidOperationException(String.Format("Unknown metadata/band type: {0}", typeStr)); + throw new InvalidOperationException(string.Format("Unknown metadata/band type: {0}", typeStr)); } logger.LogDebug("Opening metadata file {0}", metadataAsset.Uri); @@ -342,7 +335,7 @@ await resourceServiceProvider.GetAssetStreamAsync(metadataAsset, private string GetProcessingLevel(Schemas.Metadata metadata) { - return String.Format("L{0}", metadata.image.level); + return string.Format("L{0}", metadata.image.level); } private IDictionary GetCommonMetadata(Schemas.Metadata metadata) @@ -395,13 +388,12 @@ private void FillDateTimeProperties(Schemas.Metadata metadata, Dictionary properties) { // platform & constellation - properties["constellation"] = String.Format("{0}-{1}", metadata.satellite.name, metadata.satellite.number).ToLower(); - properties["platform"] = String.Format("{0}-{1}", metadata.satellite.name, metadata.satellite.number).ToLower(); + properties["constellation"] = string.Format("{0}-{1}", metadata.satellite.name, metadata.satellite.number).ToLower(); + properties["platform"] = string.Format("{0}-{1}", metadata.satellite.name, metadata.satellite.number).ToLower(); properties["mission"] = properties["platform"]; properties["instruments"] = new string[] { metadata.satellite.instrument.Value.ToLower() }; properties["sensor_type"] = "optical"; - double gsd = 0; - if (Double.TryParse(metadata.image.verticalPixelSize, out gsd)) + if (double.TryParse(metadata.image.verticalPixelSize, out double gsd)) { properties["gsd"] = gsd; } @@ -438,18 +430,18 @@ private void FillInstrument(Schemas.Metadata metadata, Dictionary properties) + private void FillBasicsProperties(Schemas.Metadata metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); - properties["title"] = String.Format("{0} {1} {2} {3}", - String.Format("{0}-{1}", metadata.satellite.name.ToUpper(), metadata.satellite.number.ToUpper()), + properties["title"] = string.Format("{0} {1} {2} {3}", + string.Format("{0}-{1}", metadata.satellite.name.ToUpper(), metadata.satellite.number.ToUpper()), metadata.spectralMode, GetProcessingLevel(metadata), properties.GetProperty("datetime").ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", culture) ); } - private void AddOtherProperties(Schemas.Metadata metadata, IDictionary properties) + private void AddOtherProperties(Schemas.Metadata metadata, IDictionary properties) { if (IncludeProviderProperty) { @@ -498,15 +490,15 @@ private void AddSatStacExtension(Schemas.Metadata metadata, StacItem stacItem) sat.OrbitState = metadata.image.orbitDirection.ToLower(); } - if (Int64.TryParse(metadata.image.path, out long path) && Int64.TryParse(metadata.image.row, out long row)) + if (long.TryParse(metadata.image.path, out long path) && long.TryParse(metadata.image.row, out long row)) { stacItem.Properties["cbers:path"] = path; stacItem.Properties["cbers:row"] = row; //sat.AbsoluteOrbit = Convert.ToInt32(1000 * path + row); } // sat.RelativeOrbit = - - string platformFullName = String.Format("{0}-{1}", metadata.satellite.name, metadata.satellite.number); + + string platformFullName = string.Format("{0}-{1}", metadata.satellite.name, metadata.satellite.number); if (platformInternationalDesignators.ContainsKey(platformFullName)) { sat.PlatformInternationalDesignator = platformInternationalDesignators[platformFullName]; @@ -516,7 +508,7 @@ private void AddSatStacExtension(Schemas.Metadata metadata, StacItem stacItem) private void AddProjStacExtension(Schemas.Metadata metadata, StacItem stacItem) { - if (metadata.image != null && !String.IsNullOrEmpty(metadata.image.epsg) && Int64.TryParse(metadata.image.epsg, out long epsg)) + if (metadata.image != null && !string.IsNullOrEmpty(metadata.image.epsg) && long.TryParse(metadata.image.epsg, out long epsg)) { ProjectionStacExtension proj = stacItem.ProjectionExtension(); proj.Epsg = epsg; @@ -543,17 +535,17 @@ private void AddProjStacExtension(Schemas.Metadata metadata, StacItem stacItem) private void AddViewStacExtension(Schemas.Metadata metadata, StacItem stacItem) { var view = new ViewStacExtension(stacItem); - if (Double.TryParse(metadata.image.offNadirAngle, out double offNadir)) + if (double.TryParse(metadata.image.offNadirAngle, out double offNadir)) { view.OffNadir = offNadir / 1000; } - if (Double.TryParse(metadata.image.sunPosition.sunAzimuth, out double sunAzimuth)) + if (double.TryParse(metadata.image.sunPosition.sunAzimuth, out double sunAzimuth)) { view.SunAzimuth = sunAzimuth; } - if (Double.TryParse(metadata.image.sunPosition.elevation, out double sunElevation)) + if (double.TryParse(metadata.image.sunPosition.elevation, out double sunElevation)) { view.SunElevation = sunElevation; } @@ -576,13 +568,9 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat { string bandFile = Path.GetFileName(bands[key]); - IAsset bandAsset = FindFirstAssetFromFileNameRegex(item, String.Format("{0}$", bandFile)); //.Replace(".", @"\.") - if (bandAsset == null) - { - throw new FileNotFoundException(string.Format( + IAsset bandAsset = FindFirstAssetFromFileNameRegex(item, string.Format("{0}$", bandFile)) ?? throw new FileNotFoundException(string.Format( "Band file declared in metadata, but not present '{0}'", - bandFile)); - } + bandFile)); //.Replace(".", @"\.") AddBandAsset(stacItem, key, bandAsset, metadata, null, null); } @@ -628,25 +616,25 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat // Identifier contains band names string[] bandsStrs = new string[defaultCompositeBands.Length]; for (int i = 0; i < bandsStrs.Length; i++) bandsStrs[i] = defaultCompositeBands[i].ToString(); - Regex bandsRegex = new Regex(String.Format(@"(band|b)(?'bands'{0})+", String.Join("|", bandsStrs))); + Regex bandsRegex = new Regex(string.Format(@"(band|b)(?'bands'{0})+", string.Join("|", bandsStrs))); Match bandMatch = bandsRegex.Match(rest); compositeBands = new int[bandMatch.Groups["bands"].Captures.Count]; for (int i = 0; i < bandMatch.Groups["bands"].Captures.Count; i++) { - compositeBands[i] = Int32.Parse(bandMatch.Groups["bands"].Captures[i].Value); + compositeBands[i] = int.Parse(bandMatch.Groups["bands"].Captures[i].Value); } } string s = ""; - foreach (int b in compositeBands) s += String.Format(" {0}", b); + foreach (int b in compositeBands) s += string.Format(" {0}", b); } if (compositeBands == null || compositeBands.Length == 0) { - throw new Exception(String.Format("Contained bands not detectable from identifier \"{0}\"", metadata.identifier)); + throw new Exception(string.Format("Contained bands not detectable from identifier \"{0}\"", metadata.identifier)); } StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, compositeAsset.Uri, - new ContentType(MimeTypes.GetMimeType(compositeAsset.Uri.OriginalString)), String.Format("{0} {1} COMPOSE", metadata.spectralMode, GetProcessingLevel(metadata)) + new ContentType(MimeTypes.GetMimeType(compositeAsset.Uri.OriginalString)), string.Format("{0} {1} COMPOSE", metadata.spectralMode, GetProcessingLevel(metadata)) ); stacAsset.Roles.Add("dn"); stacAsset.Properties.AddRange(compositeAsset.Properties); @@ -692,7 +680,7 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat private void AddBandAsset(StacItem stacItem, int bandNumber, IAsset imageAsset, Schemas.Metadata metadata, StacAsset stacAsset = null, int[] defaultCompositeBands = null) { - AddBandAsset(stacItem, String.Format("band-{0}", bandNumber), imageAsset, metadata, stacAsset, defaultCompositeBands); + AddBandAsset(stacItem, string.Format("band-{0}", bandNumber), imageAsset, metadata, stacAsset, defaultCompositeBands); } private void AddBandAsset(StacItem stacItem, string bandId, IAsset imageAsset, Schemas.Metadata metadata, StacAsset stacAsset = null, int[] defaultCompositeBands = null) @@ -889,7 +877,7 @@ private void AddBandAsset(StacItem stacItem, string bandId, IAsset imageAsset, S if (notFound) { - throw new InvalidOperationException(String.Format("Band information not found for {0}", bandId)); + throw new InvalidOperationException(string.Format("Band information not found for {0}", bandId)); } // Find absolute calibration coefficients @@ -915,14 +903,14 @@ private void AddBandAsset(StacItem stacItem, string bandId, IAsset imageAsset, S if (stacAsset == null) { stacAsset = StacAsset.CreateDataAsset(stacItem, imageAsset.Uri, - new ContentType(MimeTypes.GetMimeType(imageAsset.Uri.OriginalString)), String.Format("{0} {1} {2}", metadata.spectralMode, GetProcessingLevel(metadata), bandId.ToUpper())); + new ContentType(MimeTypes.GetMimeType(imageAsset.Uri.OriginalString)), string.Format("{0} {1} {2}", metadata.spectralMode, GetProcessingLevel(metadata), bandId.ToUpper())); stacAsset.Roles.Add("dn"); stacAsset.Properties.AddRange(imageAsset.Properties); stacAsset.EoExtension().Bands = new EoBandObject[] { eoBandObject }; - + if (rasterBand != null) { - stacAsset.RasterExtension().Bands = new RasterBand[] { rasterBand}; + stacAsset.RasterExtension().Bands = new RasterBand[] { rasterBand }; } stacItem.Assets.Add(bandId, stacAsset); @@ -942,7 +930,7 @@ private void AddBandAsset(StacItem stacItem, string bandId, IAsset imageAsset, S }; eo.Bands = bands.ToArray(); } - + if (rasterBand != null) { RasterStacExtension raster = stacAsset.RasterExtension(); @@ -964,7 +952,7 @@ private void AddBandAsset(StacItem stacItem, string bandId, IAsset imageAsset, S private double? GetAbsoluteCalibrationCoefficient(string bandId, band[] coefficients, int[] defaultCompositeBands) { - string bandIdNumber = bandId.Replace("band-", String.Empty); + string bandIdNumber = bandId.Replace("band-", string.Empty); if (coefficients != null) { if (defaultCompositeBands == null) @@ -972,9 +960,9 @@ private void AddBandAsset(StacItem stacItem, string bandId, IAsset imageAsset, S // In case of properly provided metadata with asset path (via XML), get coefficient from band with same ID foreach (band coefficient in coefficients) { - if (coefficient.name.Replace("band-", String.Empty) == bandIdNumber) + if (coefficient.name.Replace("band-", string.Empty) == bandIdNumber) { - if (Double.TryParse(coefficient.Value, out double scale)) return scale; + if (double.TryParse(coefficient.Value, out double scale)) return scale; } } } @@ -990,7 +978,7 @@ private void AddBandAsset(StacItem stacItem, string bandId, IAsset imageAsset, S { if (defaultCompositeBands[i].ToString() == bandIdNumber && i < coefficients.Length) { - if (Double.TryParse(coefficients[i].Value, out double scale)) return scale; + if (double.TryParse(coefficients[i].Value, out double scale)) return scale; } } } @@ -999,4 +987,4 @@ private void AddBandAsset(StacItem stacItem, string bandId, IAsset imageAsset, S } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Inpe/Schemas/MetadataCsv.cs b/src/Stars.Data/Model/Metadata/Inpe/Schemas/MetadataCsv.cs index 65c8ebd3..d5dac071 100644 --- a/src/Stars.Data/Model/Metadata/Inpe/Schemas/MetadataCsv.cs +++ b/src/Stars.Data/Model/Metadata/Inpe/Schemas/MetadataCsv.cs @@ -1,10 +1,12 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; -namespace Terradue.Stars.Data.Model.Metadata.Inpe.Schemas { - public class MetadataCsv { +namespace Terradue.Stars.Data.Model.Metadata.Inpe.Schemas +{ + public class MetadataCsv + { public string AGENCY { get; set; } public string SATELLITE { get; set; } public string INSTRUMENT { get; set; } @@ -27,18 +29,21 @@ public class MetadataCsv { public string SUN_ELEVATION { get; set; } public string ABSOLUTE_CALIBRATION_COEFFICIENTS { get; set; } - public Metadata getMetadata() { + public Metadata getMetadata() + { Metadata metadata = new Metadata(); // SATELLITE metadata.satellite = new prdfSatellite(); string pattern = @"(CBERS|AMAZONIA)(.*)"; Match match = Regex.Match(SATELLITE, pattern); - if (match.Success) { + if (match.Success) + { metadata.satellite.name = match.Groups[1].Value; metadata.satellite.number = match.Groups[2].Value; } - else { + else + { throw new Exception("No match found"); } @@ -47,13 +52,13 @@ public Metadata getMetadata() { { Value = INSTRUMENT }; - + // IDENTIFIER metadata.identifier = IDENTIFIER; var footprintArray = FOOTPRINT.Trim().Split(' '); var bboxArray = FindBoundingBox(footprintArray); - + // IMAGE metadata.image = new prdfImage @@ -62,7 +67,7 @@ public Metadata getMetadata() { timeStamp = new prdfImageTimeStamp { begin = START_DATE, - center = CalculateMeanDate(START_DATE, COMPLETE_DATE), + center = CalculateMeanDate(START_DATE, COMPLETE_DATE), end = COMPLETE_DATE }, // FOOTPRINT @@ -91,30 +96,33 @@ public Metadata getMetadata() { }, // SUN_AZIMUTH SUN_ELEVATION - sunPosition = new prdfImageSunPosition { + sunPosition = new prdfImageSunPosition + { elevation = SUN_ELEVATION, sunAzimuth = SUN_AZIMUTH }, // OFF_NADIR offNadirAngle = OFF_NADIR, - + // PATH ROW row = ROW, path = PATH, - + absoluteCalibrationCoefficient = GetBandValuesFromAbsoluteCalibrationCoefficients(ABSOLUTE_CALIBRATION_COEFFICIENTS), - + }; - + // PROCESSING_LEVEL pattern = @"L(\d+)"; match = Regex.Match(PROCESSING_LEVEL, pattern); - if (match.Success) { + if (match.Success) + { string level = match.Groups[1].Value; metadata.image.level = level; } - else { + else + { throw new Exception("No match found"); } @@ -122,7 +130,7 @@ public Metadata getMetadata() { metadata.image.epsg = EPSG; - + // PROCESSING_LEVEL_DESCRIPTION // PROJECTION // MODE @@ -130,12 +138,13 @@ public Metadata getMetadata() { // AOI // FORMAT // AGENCY - + return metadata; } - private static double[,] FindBoundingBox(string[] singleCoordinates) { + private static double[,] FindBoundingBox(string[] singleCoordinates) + { // Assumes bounding box has only 4 unique points // position (upper/lower and left/right) is not considered // (unimportant for geometry generation) @@ -154,8 +163,8 @@ public Metadata getMetadata() { for (int i = 0; i < len; i++) { // Latitude comes before longitude in original string -> invert - coordinates[i, 0] = Double.Parse(singleCoordinates[2 * i + 1]); - coordinates[i, 1] = Double.Parse(singleCoordinates[2 * i]); + coordinates[i, 0] = double.Parse(singleCoordinates[2 * i + 1]); + coordinates[i, 1] = double.Parse(singleCoordinates[2 * i]); } return coordinates; @@ -175,14 +184,14 @@ private static band[] GetBandValuesFromAbsoluteCalibrationCoefficients(string in { if (match.Groups.Count >= 2) { - attributeValues.Add(new band() { Value = match.Groups[1].Value} ); + attributeValues.Add(new band() { Value = match.Groups[1].Value }); } } return attributeValues.ToArray(); } - - + + private static string CalculateMeanDate(string dateString1, string dateString2) { DateTime date1 = DateTime.Parse(dateString1, null, DateTimeStyles.AssumeUniversal).ToUniversalTime(); @@ -197,4 +206,4 @@ private static string CalculateMeanDate(string dateString1, string dateString2) return meanDate.ToString("yyyy-MM-ddTHH:mm:ssZ"); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Isro/IsroMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Isro/IsroMetadataExtractor.cs index 4be97729..81aeee72 100644 --- a/src/Stars.Data/Model/Metadata/Isro/IsroMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Isro/IsroMetadataExtractor.cs @@ -3,10 +3,7 @@ using System.Globalization; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using System.Threading.Tasks; -using System.Xml; -using System.Xml.Serialization; using Kajabity.Tools.Java; using Microsoft.Extensions.Logging; using ProjNet.CoordinateSystems; @@ -17,12 +14,12 @@ using Stac.Extensions.Raster; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services; using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services.Plugins; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Isro { @@ -44,8 +41,7 @@ public IsroMetadataExtractor(ILogger logger, IResourceSer public override bool CanProcess(IResource route, IDestination destinations) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset metadataAsset = GetMetadataAsset(item); @@ -60,12 +56,8 @@ public override bool CanProcess(IResource route, IDestination destinations) protected override async Task ExtractMetadata(IItem item, string suffix) { - IAsset metadataAsset = GetMetadataAsset(item); - if (metadataAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } - logger.LogDebug(String.Format("Metadata file is {0}", metadataAsset.Uri)); + IAsset metadataAsset = GetMetadataAsset(item) ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); + logger.LogDebug(string.Format("Metadata file is {0}", metadataAsset.Uri)); logger.LogDebug("Reading metadata"); JavaProperties metadata = await ReadMetadata(await resourceServiceProvider.GetStreamResourceAsync(metadataAsset, System.Threading.CancellationToken.None)); logger.LogDebug("Metadata deserialized. Starting metadata generation"); @@ -242,25 +234,21 @@ private void AddbandAsset(JavaProperties metadata, IAsset asset, StacItem stacIt private void AddViewStacExtension(JavaProperties metadata, StacItem stacItem) { var view = new ViewStacExtension(stacItem); - double azimuth = 0; - double.TryParse(metadata["SatelliteHeading"], out azimuth); + double.TryParse(metadata["SatelliteHeading"], out double azimuth); if (azimuth != 0) view.Azimuth = azimuth; - double incidenceAngle = 0; - double.TryParse(metadata["AngleIncidence"], out incidenceAngle); + double.TryParse(metadata["AngleIncidence"], out double incidenceAngle); if (incidenceAngle != 0) view.IncidenceAngle = incidenceAngle; - double sunazimuth = 0; - double.TryParse(metadata["SunAziumthAtCenter"], out sunazimuth); + double.TryParse(metadata["SunAziumthAtCenter"], out double sunazimuth); if (sunazimuth == 0) double.TryParse(metadata["SunAzimuthAtCenter"], out sunazimuth); if (sunazimuth != 0) view.SunAzimuth = sunazimuth; - double elevation = 0; - double.TryParse(metadata["SunElevationAtCenter"], out elevation); + double.TryParse(metadata["SunElevationAtCenter"], out double elevation); if (elevation != 0) view.SunElevation = elevation; @@ -269,8 +257,7 @@ private void AddViewStacExtension(JavaProperties metadata, StacItem stacItem) private void AddSatStacExtension(JavaProperties metadata, StacItem stacItem) { var sat = new SatStacExtension(stacItem); - int orbitno = 0; - int.TryParse(metadata["ImagingOrbitNo"], out orbitno); + int.TryParse(metadata["ImagingOrbitNo"], out int orbitno); if (orbitno != 0) sat.AbsoluteOrbit = orbitno; @@ -352,8 +339,7 @@ private void FillInstrument(JavaProperties metadata, Dictionary } properties["sensor_type"] = "optical"; - double gsd = 0; - double.TryParse(metadata["PlannedGSD"], out gsd); + double.TryParse(metadata["PlannedGSD"], out double gsd); if (gsd != 0) { properties.Remove("gsd"); @@ -416,7 +402,7 @@ private void FillDateTimeProperties(JavaProperties metadata, Dictionary properties) + private void FillBasicsProperties(JavaProperties metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -430,7 +416,7 @@ private void FillBasicsProperties(JavaProperties metadata, IDictionary properties) + private void AddOtherProperties(JavaProperties metadata, IDictionary properties) { string description = null; string url = null; @@ -453,7 +439,7 @@ private void AddOtherProperties(JavaProperties metadata, IDictionary ReadMetadata(IStreamResource metadataFi protected virtual IAsset GetMetadataAsset(IItem item) { - IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"[0-9a-zA-Z_-]*(META*\.(txt|TXT))$"); - if (manifestAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } + IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"[0-9a-zA-Z_-]*(META*\.(txt|TXT))$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); return manifestAsset; } @@ -502,4 +484,4 @@ protected virtual IAsset GetMetadataAsset(IItem item) } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaProperties.cs b/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaProperties.cs index 0caeaa9d..2d7492ae 100644 --- a/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaProperties.cs +++ b/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaProperties.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright 2009-14 Simon J. Williams. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,159 +16,158 @@ * http://www.kajabity.com */ -using System; using System.Collections; -using System.IO; using System.Collections.Specialized; +using System.IO; namespace Kajabity.Tools.Java { - /// - /// Hold Java style properties as key-value pairs and allow them to be loaded from or - /// saved to a ".properties" file. The file is stored with character set ISO-8859-1 which extends US-ASCII - /// (the characters 0-127 are the same) and forms the first part of the Unicode character set. Within the - /// application are Unicode - but all values outside the basic US-ASCII set are escaped. - /// + /// + /// Hold Java style properties as key-value pairs and allow them to be loaded from or + /// saved to a ".properties" file. The file is stored with character set ISO-8859-1 which extends US-ASCII + /// (the characters 0-127 are the same) and forms the first part of the Unicode character set. Within the + /// application are Unicode - but all values outside the basic US-ASCII set are escaped. + /// public class JavaProperties : NameValueCollection - { - /// - /// A reference to an optional set of default properties - these values are returned - /// if the value has not been loaded from a ".properties" file or set programatically. - /// + { + /// + /// A reference to an optional set of default properties - these values are returned + /// if the value has not been loaded from a ".properties" file or set programatically. + /// protected NameValueCollection defaults; - /// - /// An empty constructor that doesn't set the defaults. - /// - public JavaProperties() - { - } + /// + /// An empty constructor that doesn't set the defaults. + /// + public JavaProperties() + { + } - /// - /// Use this constructor to provide a set of default values. The default values are kept separate - /// to the ones in this instant. - /// - /// A Hashtable that holds a set of defafult key value pairs to - /// return when the requested key has not been set. - public JavaProperties( NameValueCollection defaults ) - { - this.defaults = defaults; - } + /// + /// Use this constructor to provide a set of default values. The default values are kept separate + /// to the ones in this instant. + /// + /// A Hashtable that holds a set of defafult key value pairs to + /// return when the requested key has not been set. + public JavaProperties(NameValueCollection defaults) + { + this.defaults = defaults; + } - /// - /// Load Java Properties from a stream expecting the format as described in . - /// - /// An input stream to read properties from. - /// If the stream source is invalid. - public void Load( Stream streamIn ) - { - JavaPropertyReader reader = new JavaPropertyReader( this ); - reader.Parse( streamIn ); - } + /// + /// Load Java Properties from a stream expecting the format as described in . + /// + /// An input stream to read properties from. + /// If the stream source is invalid. + public void Load(Stream streamIn) + { + JavaPropertyReader reader = new JavaPropertyReader(this); + reader.Parse(streamIn); + } - /// - /// Store the contents of this collection of properties to the stream in the format - /// used for Java ".properties" files using an instance of . - /// The keys and values will be minimally escaped to ensure special characters are read back - /// in properly. Keys are not sorted. The file will begin with a comment identifying the - /// date - and an additional comment may be included. - /// - /// - /// - /// An output stream to write the properties to. - /// Optional additional comment to include at the head of the output. - public void Store( Stream streamOut, string comments ) - { - JavaPropertyWriter writer = new JavaPropertyWriter( this ); - writer.Write( streamOut, comments ); - } + /// + /// Store the contents of this collection of properties to the stream in the format + /// used for Java ".properties" files using an instance of . + /// The keys and values will be minimally escaped to ensure special characters are read back + /// in properly. Keys are not sorted. The file will begin with a comment identifying the + /// date - and an additional comment may be included. + /// + /// + /// + /// An output stream to write the properties to. + /// Optional additional comment to include at the head of the output. + public void Store(Stream streamOut, string comments) + { + JavaPropertyWriter writer = new JavaPropertyWriter(this); + writer.Write(streamOut, comments); + } - /// - /// Get the value for the specified key value. If the key is not found, then return the - /// default value - and if still not found, return null. - /// - /// The key whose value should be returned. - /// The value corresponding to the key - or null if not found. - public string GetProperty( string key ) - { - Object objectValue = this[ key ]; - if( objectValue != null ) - { - return AsString( objectValue ); - } - else if( defaults != null ) - { - return AsString( defaults[ key ] ); - } + /// + /// Get the value for the specified key value. If the key is not found, then return the + /// default value - and if still not found, return null. + /// + /// The key whose value should be returned. + /// The value corresponding to the key - or null if not found. + public string GetProperty(string key) + { + object objectValue = this[key]; + if (objectValue != null) + { + return AsString(objectValue); + } + else if (defaults != null) + { + return AsString(defaults[key]); + } - return null; - } + return null; + } - /// - /// Get the value for the specified key value. If the key is not found, then return the - /// default value - and if still not found, return defaultValue. - /// - /// The key whose value should be returned. - /// The default value if the key is not found. - /// The value corresponding to the key - or null if not found. - public string GetProperty( string key, string defaultValue ) - { - string val = GetProperty( key ); - return (val == null) ? defaultValue : val; - } + /// + /// Get the value for the specified key value. If the key is not found, then return the + /// default value - and if still not found, return defaultValue. + /// + /// The key whose value should be returned. + /// The default value if the key is not found. + /// The value corresponding to the key - or null if not found. + public string GetProperty(string key, string defaultValue) + { + string val = GetProperty(key); + return val ?? defaultValue; + } - /// - /// Set the value for a property key. The old value is returned - if any. - /// - /// The key whose value is to be set. - /// The new value off the key. - /// The original value of the key - as a string. - public string SetProperty( string key, string newValue ) - { - string oldValue = AsString( this[ key ] ); - this[ key ] = newValue; - return oldValue; - } + /// + /// Set the value for a property key. The old value is returned - if any. + /// + /// The key whose value is to be set. + /// The new value off the key. + /// The original value of the key - as a string. + public string SetProperty(string key, string newValue) + { + string oldValue = AsString(this[key]); + this[key] = newValue; + return oldValue; + } - /// - /// Returns an enumerator of all the properties available in this instance - including the - /// defaults. - /// - /// An enumarator for all of the keys including defaults. - public IEnumerator PropertyNames() - { + /// + /// Returns an enumerator of all the properties available in this instance - including the + /// defaults. + /// + /// An enumarator for all of the keys including defaults. + public IEnumerator PropertyNames() + { NameValueCollection combined; - if( defaults != null) - { - combined = new NameValueCollection( defaults ); - - for( IEnumerator e = this.Keys.GetEnumerator(); e.MoveNext(); ) - { - string key = AsString( e.Current ); - combined.Add( key, this[ key ] ); - } - } - else - { - combined = new NameValueCollection( this ); - } + if (defaults != null) + { + combined = new NameValueCollection(defaults); + + for (IEnumerator e = Keys.GetEnumerator(); e.MoveNext();) + { + string key = AsString(e.Current); + combined.Add(key, this[key]); + } + } + else + { + combined = new NameValueCollection(this); + } + + return combined.Keys.GetEnumerator(); + } - return combined.Keys.GetEnumerator(); - } + /// + /// A utility method to safely convert an Object to a string. + /// + /// An Object or null to be returned as a string. + /// string value of the object - or null. + private string AsString(object o) + { + if (o == null) + { + return null; + } - /// - /// A utility method to safely convert an Object to a string. - /// - /// An Object or null to be returned as a string. - /// string value of the object - or null. - private string AsString( Object o ) - { - if( o == null ) - { - return null; - } - - return o.ToString(); - } - } + return o.ToString(); + } + } } diff --git a/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaPropertyReader.cs b/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaPropertyReader.cs index e889f848..dcaf3cb3 100644 --- a/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaPropertyReader.cs +++ b/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaPropertyReader.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright 2009-14 Simon J. Williams. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,377 +16,373 @@ * http://www.kajabity.com */ -using System; -using System.Collections; using System.IO; using System.Text; -using System.Diagnostics; - namespace Kajabity.Tools.Java { - /// - /// This class reads Java style properties from an input stream. - /// - public class JavaPropertyReader - { - private const int MATCH_end_of_input = 1; - private const int MATCH_terminator = 2; - private const int MATCH_whitespace = 3; - private const int MATCH_any = 4; - - private const int ACTION_add_to_key = 1; - private const int ACTION_add_to_value = 2; - private const int ACTION_store_property = 3; - private const int ACTION_escape = 4; - private const int ACTION_ignore = 5; - - private const int STATE_start = 0; - private const int STATE_comment = 1; - private const int STATE_key = 2; - private const int STATE_key_escape = 3; - private const int STATE_key_ws = 4; - private const int STATE_before_separator = 5; - private const int STATE_after_separator = 6; - private const int STATE_value = 7; - private const int STATE_value_escape = 8; - private const int STATE_value_ws = 9; - private const int STATE_finish = 10; - - private static string [] stateNames = new string[] - { "STATE_start", "STATE_comment", "STATE_key", "STATE_key_escape", "STATE_key_ws", - "STATE_before_separator", "STATE_after_separator", "STATE_value", "STATE_value_escape", - "STATE_value_ws", "STATE_finish" }; - - private static int [][] states = new int[][] { - new int[]{//STATE_start - MATCH_end_of_input, STATE_finish, ACTION_ignore, - MATCH_terminator, STATE_start, ACTION_ignore, - '#', STATE_comment, ACTION_ignore, - '!', STATE_comment, ACTION_ignore, - MATCH_whitespace, STATE_start, ACTION_ignore, - '\\', STATE_key_escape, ACTION_escape, - ':', STATE_after_separator, ACTION_ignore, - '=', STATE_after_separator, ACTION_ignore, - MATCH_any, STATE_key, ACTION_add_to_key, - }, - new int[]{//STATE_comment - MATCH_end_of_input, STATE_finish, ACTION_ignore, - MATCH_terminator, STATE_start, ACTION_ignore, - MATCH_any, STATE_comment, ACTION_ignore, - }, - new int[]{//STATE_key - MATCH_end_of_input, STATE_finish, ACTION_store_property, - MATCH_terminator, STATE_start, ACTION_store_property, - MATCH_whitespace, STATE_before_separator, ACTION_ignore, - '\\', STATE_key_escape, ACTION_escape, - ':', STATE_after_separator, ACTION_ignore, - '=', STATE_after_separator, ACTION_ignore, - MATCH_any, STATE_key, ACTION_add_to_key, - }, - new int[]{//STATE_key_escape - MATCH_terminator, STATE_key_ws, ACTION_ignore, - MATCH_any, STATE_key, ACTION_add_to_key, - }, - new int[]{//STATE_key_ws - MATCH_end_of_input, STATE_finish, ACTION_store_property, - MATCH_terminator, STATE_start, ACTION_store_property, - MATCH_whitespace, STATE_key_ws, ACTION_ignore, - '\\', STATE_key_escape, ACTION_escape, - ':', STATE_after_separator, ACTION_ignore, - '=', STATE_after_separator, ACTION_ignore, - MATCH_any, STATE_key, ACTION_add_to_key, - }, - new int[]{//STATE_before_separator - MATCH_end_of_input, STATE_finish, ACTION_store_property, - MATCH_terminator, STATE_start, ACTION_store_property, - MATCH_whitespace, STATE_before_separator, ACTION_ignore, - '\\', STATE_value_escape, ACTION_escape, - ':', STATE_after_separator, ACTION_ignore, - '=', STATE_after_separator, ACTION_ignore, - MATCH_any, STATE_value, ACTION_add_to_value, - }, - new int[]{//STATE_after_separator - MATCH_end_of_input, STATE_finish, ACTION_store_property, - MATCH_terminator, STATE_start, ACTION_store_property, - MATCH_whitespace, STATE_after_separator, ACTION_ignore, - '\\', STATE_value_escape, ACTION_escape, - MATCH_any, STATE_value, ACTION_add_to_value, - }, - new int[]{//STATE_value - MATCH_end_of_input, STATE_finish, ACTION_store_property, - MATCH_terminator, STATE_start, ACTION_store_property, - '\\', STATE_value_escape, ACTION_escape, - MATCH_any, STATE_value, ACTION_add_to_value, - }, - new int[]{//STATE_value_escape - MATCH_terminator, STATE_value_ws, ACTION_ignore, - MATCH_any, STATE_value, ACTION_add_to_value - }, - new int[]{//STATE_value_ws - MATCH_end_of_input, STATE_finish, ACTION_store_property, - MATCH_terminator, STATE_start, ACTION_store_property, - MATCH_whitespace, STATE_value_ws, ACTION_ignore, - '\\', STATE_value_escape, ACTION_escape, - MATCH_any, STATE_value, ACTION_add_to_value, - } - }; + /// + /// This class reads Java style properties from an input stream. + /// + public class JavaPropertyReader + { + private const int MATCH_end_of_input = 1; + private const int MATCH_terminator = 2; + private const int MATCH_whitespace = 3; + private const int MATCH_any = 4; + + private const int ACTION_add_to_key = 1; + private const int ACTION_add_to_value = 2; + private const int ACTION_store_property = 3; + private const int ACTION_escape = 4; + private const int ACTION_ignore = 5; + + private const int STATE_start = 0; + private const int STATE_comment = 1; + private const int STATE_key = 2; + private const int STATE_key_escape = 3; + private const int STATE_key_ws = 4; + private const int STATE_before_separator = 5; + private const int STATE_after_separator = 6; + private const int STATE_value = 7; + private const int STATE_value_escape = 8; + private const int STATE_value_ws = 9; + private const int STATE_finish = 10; + + private static string[] stateNames = new string[] + { "STATE_start", "STATE_comment", "STATE_key", "STATE_key_escape", "STATE_key_ws", + "STATE_before_separator", "STATE_after_separator", "STATE_value", "STATE_value_escape", + "STATE_value_ws", "STATE_finish" }; + + private static int[][] states = new int[][] { + new int[]{//STATE_start + MATCH_end_of_input, STATE_finish, ACTION_ignore, + MATCH_terminator, STATE_start, ACTION_ignore, + '#', STATE_comment, ACTION_ignore, + '!', STATE_comment, ACTION_ignore, + MATCH_whitespace, STATE_start, ACTION_ignore, + '\\', STATE_key_escape, ACTION_escape, + ':', STATE_after_separator, ACTION_ignore, + '=', STATE_after_separator, ACTION_ignore, + MATCH_any, STATE_key, ACTION_add_to_key, + }, + new int[]{//STATE_comment + MATCH_end_of_input, STATE_finish, ACTION_ignore, + MATCH_terminator, STATE_start, ACTION_ignore, + MATCH_any, STATE_comment, ACTION_ignore, + }, + new int[]{//STATE_key + MATCH_end_of_input, STATE_finish, ACTION_store_property, + MATCH_terminator, STATE_start, ACTION_store_property, + MATCH_whitespace, STATE_before_separator, ACTION_ignore, + '\\', STATE_key_escape, ACTION_escape, + ':', STATE_after_separator, ACTION_ignore, + '=', STATE_after_separator, ACTION_ignore, + MATCH_any, STATE_key, ACTION_add_to_key, + }, + new int[]{//STATE_key_escape + MATCH_terminator, STATE_key_ws, ACTION_ignore, + MATCH_any, STATE_key, ACTION_add_to_key, + }, + new int[]{//STATE_key_ws + MATCH_end_of_input, STATE_finish, ACTION_store_property, + MATCH_terminator, STATE_start, ACTION_store_property, + MATCH_whitespace, STATE_key_ws, ACTION_ignore, + '\\', STATE_key_escape, ACTION_escape, + ':', STATE_after_separator, ACTION_ignore, + '=', STATE_after_separator, ACTION_ignore, + MATCH_any, STATE_key, ACTION_add_to_key, + }, + new int[]{//STATE_before_separator + MATCH_end_of_input, STATE_finish, ACTION_store_property, + MATCH_terminator, STATE_start, ACTION_store_property, + MATCH_whitespace, STATE_before_separator, ACTION_ignore, + '\\', STATE_value_escape, ACTION_escape, + ':', STATE_after_separator, ACTION_ignore, + '=', STATE_after_separator, ACTION_ignore, + MATCH_any, STATE_value, ACTION_add_to_value, + }, + new int[]{//STATE_after_separator + MATCH_end_of_input, STATE_finish, ACTION_store_property, + MATCH_terminator, STATE_start, ACTION_store_property, + MATCH_whitespace, STATE_after_separator, ACTION_ignore, + '\\', STATE_value_escape, ACTION_escape, + MATCH_any, STATE_value, ACTION_add_to_value, + }, + new int[]{//STATE_value + MATCH_end_of_input, STATE_finish, ACTION_store_property, + MATCH_terminator, STATE_start, ACTION_store_property, + '\\', STATE_value_escape, ACTION_escape, + MATCH_any, STATE_value, ACTION_add_to_value, + }, + new int[]{//STATE_value_escape + MATCH_terminator, STATE_value_ws, ACTION_ignore, + MATCH_any, STATE_value, ACTION_add_to_value + }, + new int[]{//STATE_value_ws + MATCH_end_of_input, STATE_finish, ACTION_store_property, + MATCH_terminator, STATE_start, ACTION_store_property, + MATCH_whitespace, STATE_value_ws, ACTION_ignore, + '\\', STATE_value_escape, ACTION_escape, + MATCH_any, STATE_value, ACTION_add_to_value, + } + }; private System.Collections.Specialized.NameValueCollection hashtable; - private const int bufferSize = 1000; - - private bool escaped = false; - private StringBuilder keyBuilder = new StringBuilder(); - private StringBuilder valueBuilder = new StringBuilder(); - - /// - /// Construct a reader passing a reference to a Hashtable (or JavaProperties) instance - /// where the keys are to be stored. - /// - /// A reference to a hashtable where the key-value pairs can be stored. - public JavaPropertyReader( System.Collections.Specialized.NameValueCollection hashtable ) - { - this.hashtable = hashtable; - } - - /// - /// Load key value pairs (properties) from an input Stream expected to have ISO-8859-1 encoding (code page 28592). - /// The input stream (usually reading from a ".properties" file) consists of a series of lines (terminated - /// by \r, \n or \r\n) each a key value pair, a comment or a blank line. - /// - /// Leading whitespace (spaces, tabs, formfeeds) are ignored at the start of any line - and a line that is empty or - /// contains only whitespace is blank and ignored. - /// - /// A line with the first non-whitespace character is a '#' or '!' is a comment line and the rest of the line is - /// ignored. - /// - /// If the first non-whitespace character is not '#' or '!' then it is the start of a key. A key is all the - /// characters up to the first whitespace or a key/value separator - '=' or ':'. - /// - /// The separator is optional. Any whitespace after the key or after the separator (if present) is ignored. - /// - /// The first non-whitespace character after the separator (or after the key if no separator) begins the value. - /// The value may include whitespace, separators, or comment characters. - /// - /// Any unicode character may be included in either key or value by using escapes preceded by the escape - /// character '\'. - /// - /// The following special cases are defined: - /// - /// '\t' - horizontal tab. - /// '\f' - form feed. - /// '\r' - return - /// '\n' - new line - /// '\\' - add escape character. - /// - /// '\ ' - add space in a key or at the start of a value. - /// '\!', '\#' - add comment markers at the start of a key. - /// '\=', '\:' - add a separator in a key. - /// - /// - /// Any unicode character using the following escape: - /// - /// '\uXXXX' - where XXXX represents the unicode character code as 4 hexadecimal digits. - /// - /// - /// Finally, longer lines can be broken by putting an escape at the very end of the line. Any leading space - /// (unless escaped) is skipped at the beginning of the following line. - /// - /// Examples - /// - /// a-key = a-value - /// a-key : a-value - /// a-key=a-value - /// a-key a-value - /// - /// - /// All the above will result in the same key/value pair - key "a-key" and value "a-value". - /// - /// ! comment... - /// # another comment... - /// - /// - /// The above are two examples of comments. - /// - /// Honk\ Kong = Near China - /// - /// - /// The above shows how to embed a space in a key - key is "Hong Kong", value is "Near China". - /// - /// a-longer-key-example = a really long value that is \ - /// split over two lines. - /// - /// - /// An example of a long line split into two. - /// - /// The input stream that the properties are read from. - public void Parse( Stream stream ) - { - reader = new BufferedStream( stream, bufferSize ); + private const int bufferSize = 1000; + + private bool escaped = false; + private StringBuilder keyBuilder = new StringBuilder(); + private StringBuilder valueBuilder = new StringBuilder(); + + /// + /// Construct a reader passing a reference to a Hashtable (or JavaProperties) instance + /// where the keys are to be stored. + /// + /// A reference to a hashtable where the key-value pairs can be stored. + public JavaPropertyReader(System.Collections.Specialized.NameValueCollection hashtable) + { + this.hashtable = hashtable; + } + + /// + /// Load key value pairs (properties) from an input Stream expected to have ISO-8859-1 encoding (code page 28592). + /// The input stream (usually reading from a ".properties" file) consists of a series of lines (terminated + /// by \r, \n or \r\n) each a key value pair, a comment or a blank line. + /// + /// Leading whitespace (spaces, tabs, formfeeds) are ignored at the start of any line - and a line that is empty or + /// contains only whitespace is blank and ignored. + /// + /// A line with the first non-whitespace character is a '#' or '!' is a comment line and the rest of the line is + /// ignored. + /// + /// If the first non-whitespace character is not '#' or '!' then it is the start of a key. A key is all the + /// characters up to the first whitespace or a key/value separator - '=' or ':'. + /// + /// The separator is optional. Any whitespace after the key or after the separator (if present) is ignored. + /// + /// The first non-whitespace character after the separator (or after the key if no separator) begins the value. + /// The value may include whitespace, separators, or comment characters. + /// + /// Any unicode character may be included in either key or value by using escapes preceded by the escape + /// character '\'. + /// + /// The following special cases are defined: + /// + /// '\t' - horizontal tab. + /// '\f' - form feed. + /// '\r' - return + /// '\n' - new line + /// '\\' - add escape character. + /// + /// '\ ' - add space in a key or at the start of a value. + /// '\!', '\#' - add comment markers at the start of a key. + /// '\=', '\:' - add a separator in a key. + /// + /// + /// Any unicode character using the following escape: + /// + /// '\uXXXX' - where XXXX represents the unicode character code as 4 hexadecimal digits. + /// + /// + /// Finally, longer lines can be broken by putting an escape at the very end of the line. Any leading space + /// (unless escaped) is skipped at the beginning of the following line. + /// + /// Examples + /// + /// a-key = a-value + /// a-key : a-value + /// a-key=a-value + /// a-key a-value + /// + /// + /// All the above will result in the same key/value pair - key "a-key" and value "a-value". + /// + /// ! comment... + /// # another comment... + /// + /// + /// The above are two examples of comments. + /// + /// Honk\ Kong = Near China + /// + /// + /// The above shows how to embed a space in a key - key is "Hong Kong", value is "Near China". + /// + /// a-longer-key-example = a really long value that is \ + /// split over two lines. + /// + /// + /// An example of a long line split into two. + /// + /// The input stream that the properties are read from. + public void Parse(Stream stream) + { + reader = new BufferedStream(stream, bufferSize); //TODO: Read using correct encoding ISO-8859-1 encoding (code page 28592). - int state = STATE_start; - do - { - int ch = nextChar(); - - bool matched = false; - - for( int s = 0; s < states[ state ].Length; s += 3 ) - { - if( matches( states[ state ][ s ], ch ) ) - { - //Debug.WriteLine( stateNames[ state ] + ", " + (s/3) + ", " + ch + (ch>20?" (" + (char) ch + ")" : "") ); - matched = true; - doAction( states[ state ][ s + 2 ], ch ); - - state = states[ state ][ s + 1 ]; - break; - } - } - - if( !matched ) - { - throw new ParseException( "Unexpected character at " + 1 + ": <<<" + ch + ">>>" ); - } - } while( state != STATE_finish ); - } - - private bool matches( int match, int ch ) - { - switch( match ) - { - case MATCH_end_of_input: - return ch == -1; - - case MATCH_terminator: - if( ch == '\r' ) - { - if( peekChar() == '\n') - { - saved = false; - } - return true; - } - else if( ch == '\n' ) - { - return true; - } - return false; - - case MATCH_whitespace: - return ch == ' ' || ch == '\t' || ch == '\f'; - - case MATCH_any: - return true; - - default: - return ch == match; - } - } - - private void doAction( int action, int ch ) - { - switch( action ) - { - case ACTION_add_to_key: - keyBuilder.Append( escapedChar( ch ) ); - escaped = false; - break; - - case ACTION_add_to_value: - valueBuilder.Append( escapedChar( ch ) ); - escaped = false; - break; - - case ACTION_store_property: - //Debug.WriteLine( keyBuilder.ToString() + "=" + valueBuilder.ToString() ); + int state = STATE_start; + do + { + int ch = nextChar(); + + bool matched = false; + + for (int s = 0; s < states[state].Length; s += 3) + { + if (matches(states[state][s], ch)) + { + //Debug.WriteLine( stateNames[ state ] + ", " + (s/3) + ", " + ch + (ch>20?" (" + (char) ch + ")" : "") ); + matched = true; + doAction(states[state][s + 2], ch); + + state = states[state][s + 1]; + break; + } + } + + if (!matched) + { + throw new ParseException("Unexpected character at " + 1 + ": <<<" + ch + ">>>"); + } + } while (state != STATE_finish); + } + + private bool matches(int match, int ch) + { + switch (match) + { + case MATCH_end_of_input: + return ch == -1; + + case MATCH_terminator: + if (ch == '\r') + { + if (peekChar() == '\n') + { + saved = false; + } + return true; + } + else if (ch == '\n') + { + return true; + } + return false; + + case MATCH_whitespace: + return ch == ' ' || ch == '\t' || ch == '\f'; + + case MATCH_any: + return true; + + default: + return ch == match; + } + } + + private void doAction(int action, int ch) + { + switch (action) + { + case ACTION_add_to_key: + keyBuilder.Append(escapedChar(ch)); + escaped = false; + break; + + case ACTION_add_to_value: + valueBuilder.Append(escapedChar(ch)); + escaped = false; + break; + + case ACTION_store_property: + //Debug.WriteLine( keyBuilder.ToString() + "=" + valueBuilder.ToString() ); // Corrected to avoid duplicate entry errors - thanks to David Tanner. - hashtable.Set(keyBuilder.ToString(),valueBuilder.ToString()); - keyBuilder.Length = 0; - valueBuilder.Length = 0; - escaped = false; - break; - - case ACTION_escape: - escaped = true; - break; - - //case ACTION_ignore: - default: - escaped = false; - break; - } - } - - private char escapedChar( int ch ) - { - if( escaped ) - { - switch( ch ) - { - case 't': - return '\t'; - case 'r': - return '\r'; - case 'n': - return '\n'; - case 'f': - return '\f'; - case 'u': - int uch = 0; - for( int i = 0; i < 4; i++ ) - { - ch = nextChar(); - if( ch >= '0' && ch <='9' ) - { - uch = (uch << 4) + ch - '0'; - } - else if( ch >= 'a' && ch <='z' ) - { - uch = (uch << 4) + ch - 'a' + 10; - } - else if( ch >= 'A' && ch <='Z' ) - { - uch = (uch << 4) + ch - 'A' + 10; - } - else - { - throw new ParseException( "Invalid Unicode character." ); - } - } - return (char) uch; - } - } - - return (char) ch; - } - - private BufferedStream reader = null; - private int savedChar; - private bool saved = false; - - private int nextChar() - { - if( saved ) - { - saved = false; - return savedChar; - } - - return reader.ReadByte(); - } - - private int peekChar() - { - if( saved ) - { - return savedChar; - } - - saved = true; - return savedChar = reader.ReadByte(); - } - } + hashtable.Set(keyBuilder.ToString(), valueBuilder.ToString()); + keyBuilder.Length = 0; + valueBuilder.Length = 0; + escaped = false; + break; + + case ACTION_escape: + escaped = true; + break; + + //case ACTION_ignore: + default: + escaped = false; + break; + } + } + + private char escapedChar(int ch) + { + if (escaped) + { + switch (ch) + { + case 't': + return '\t'; + case 'r': + return '\r'; + case 'n': + return '\n'; + case 'f': + return '\f'; + case 'u': + int uch = 0; + for (int i = 0; i < 4; i++) + { + ch = nextChar(); + if (ch >= '0' && ch <= '9') + { + uch = (uch << 4) + ch - '0'; + } + else if (ch >= 'a' && ch <= 'z') + { + uch = (uch << 4) + ch - 'a' + 10; + } + else if (ch >= 'A' && ch <= 'Z') + { + uch = (uch << 4) + ch - 'A' + 10; + } + else + { + throw new ParseException("Invalid Unicode character."); + } + } + return (char)uch; + } + } + + return (char)ch; + } + + private BufferedStream reader = null; + private int savedChar; + private bool saved = false; + + private int nextChar() + { + if (saved) + { + saved = false; + return savedChar; + } + + return reader.ReadByte(); + } + + private int peekChar() + { + if (saved) + { + return savedChar; + } + + saved = true; + return savedChar = reader.ReadByte(); + } + } } diff --git a/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaPropertyWriter.cs b/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaPropertyWriter.cs index 48b8c360..270ea78c 100644 --- a/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaPropertyWriter.cs +++ b/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/JavaPropertyWriter.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright 2009-14 Simon J. Williams. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,10 +17,10 @@ */ using System; -using System.IO; using System.Collections; -using System.Text; using System.Collections.Specialized; +using System.IO; +using System.Text; namespace Kajabity.Tools.Java { @@ -30,7 +30,7 @@ namespace Kajabity.Tools.Java /// public class JavaPropertyWriter { - private static char[] HEX = new char[] { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' }; + private static char[] HEX = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private NameValueCollection hashtable; @@ -39,7 +39,7 @@ public class JavaPropertyWriter /// /// The Hashtable (or JavaProperties) instance /// whose values are to be written. - public JavaPropertyWriter( NameValueCollection hashtable ) + public JavaPropertyWriter(NameValueCollection hashtable) { this.hashtable = hashtable; } @@ -49,29 +49,29 @@ public JavaPropertyWriter( NameValueCollection hashtable ) /// /// The output stream where the properties are written. /// Optional comments that are placed at the beginning of the output. - public void Write( Stream stream, string comments ) + public void Write(Stream stream, string comments) { // Create a writer to output to an ISO-8859-1 encoding (code page 28592). - StreamWriter writer = new StreamWriter( stream, System.Text.Encoding.GetEncoding( 28592 ) ); + StreamWriter writer = new StreamWriter(stream, System.Text.Encoding.GetEncoding(28592)); //TODO: Confirm correct codepage: // 28592 iso-8859-2 Central European (ISO) // 28591 iso-8859-1 Western European (ISO) // from http://msdn.microsoft.com/en-us/library/system.text.encodinginfo.getencoding.aspx - if( comments != null) + if (comments != null) { - writer.WriteLine( "# " + comments ); + writer.WriteLine("# " + comments); } - writer.WriteLine( "# " + DateTime.Now.ToString() ); + writer.WriteLine("# " + DateTime.Now.ToString()); - for( IEnumerator e = hashtable.Keys.GetEnumerator(); e.MoveNext(); ) + for (IEnumerator e = hashtable.Keys.GetEnumerator(); e.MoveNext();) { string key = e.Current.ToString(); - string val = hashtable[ key ].ToString(); + string val = hashtable[key].ToString(); - writer.WriteLine( escapeKey( key ) + "=" + escapeValue( val ) ); + writer.WriteLine(escapeKey(key) + "=" + escapeValue(val)); } writer.Flush(); @@ -84,120 +84,120 @@ public void Write( Stream stream, string comments ) /// /// /// - private string escapeKey( string s ) + private string escapeKey(string s) { StringBuilder buf = new StringBuilder(); bool first = true; - foreach( char c in s ) + foreach (char c in s) { // Avoid confusing with a comment: '!' (33), '#' (35). - if( first ) + if (first) { first = false; - if( c == '!' || c == '#' ) + if (c == '!' || c == '#') { - buf.Append( '\\' ); + buf.Append('\\'); } } - switch( c ) + switch (c) { - case '\t': // =09 U+0009 HORIZONTAL TABULATION \t - buf.Append( '\\' ).Append( 't' ); - break; - case '\n': // =0A U+000A LINE FEED \n - buf.Append( '\\' ).Append( 'n' ); - break; - case '\f': // =0C U+000C FORM FEED \f - buf.Append( '\\' ).Append( 'f' ); - break; - case '\r': // =0D U+000D CARRIAGE RETURN \r - buf.Append( '\\' ).Append( 'r' ); - break; - - case ' ': // 32: ' ' - case ':': // 58: ':' - case '=': // 61: '=' - case '\\': // 92: '\' - buf.Append( '\\' ).Append( c ); - break; - - default: - if( c > 31 && c < 127 ) - { - buf.Append( c ); - } - else - { - buf.Append( '\\' ).Append( 'u' ); - buf.Append( HEX[ (c >> 12) & 0xF ] ); - buf.Append( HEX[ (c >> 8) & 0xF ] ); - buf.Append( HEX[ (c >> 4) & 0xF ] ); - buf.Append( HEX[ c & 0xF ] ); - } - break; + case '\t': // =09 U+0009 HORIZONTAL TABULATION \t + buf.Append('\\').Append('t'); + break; + case '\n': // =0A U+000A LINE FEED \n + buf.Append('\\').Append('n'); + break; + case '\f': // =0C U+000C FORM FEED \f + buf.Append('\\').Append('f'); + break; + case '\r': // =0D U+000D CARRIAGE RETURN \r + buf.Append('\\').Append('r'); + break; + + case ' ': // 32: ' ' + case ':': // 58: ':' + case '=': // 61: '=' + case '\\': // 92: '\' + buf.Append('\\').Append(c); + break; + + default: + if (c > 31 && c < 127) + { + buf.Append(c); + } + else + { + buf.Append('\\').Append('u'); + buf.Append(HEX[(c >> 12) & 0xF]); + buf.Append(HEX[(c >> 8) & 0xF]); + buf.Append(HEX[(c >> 4) & 0xF]); + buf.Append(HEX[c & 0xF]); + } + break; } } return buf.ToString(); } - private string escapeValue( string s ) + private string escapeValue(string s) { StringBuilder buf = new StringBuilder(); bool first = true; - foreach( char c in s ) + foreach (char c in s) { // Handle value starting with whitespace. - if( first ) + if (first) { first = false; - if( c == ' ' ) + if (c == ' ') { - buf.Append( '\\' ).Append( ' ' ); + buf.Append('\\').Append(' '); continue; } - else if( c == '\t' ) // =09 U+0009 HORIZONTAL TABULATION \t + else if (c == '\t') // =09 U+0009 HORIZONTAL TABULATION \t { - buf.Append( '\\' ).Append( 't' ); + buf.Append('\\').Append('t'); continue; } } - switch( c ) + switch (c) { - case '\t': // =09 U+0009 HORIZONTAL TABULATION \t - buf.Append( '\t' ); //OK after first position. - break; - case '\n': // =0A U+000A LINE FEED \n - buf.Append( '\\' ).Append( 'n' ); - break; - case '\f': // =0C U+000C FORM FEED \f - buf.Append( '\\' ).Append( 'f' ); - break; - case '\r': // =0D U+000D CARRIAGE RETURN \r - buf.Append( '\\' ).Append( 'r' ); - break; - case '\\': // 92: '\' - buf.Append( '\\' ).Append( c ); - break; - - default: - if( c > 31 && c < 127 ) - { - buf.Append( c ); - } - else - { - buf.Append( '\\' ).Append( 'u' ); - buf.Append( HEX[ (c >> 12) & 0xF ] ); - buf.Append( HEX[ (c >> 8) & 0xF ] ); - buf.Append( HEX[ (c >> 4) & 0xF ] ); - buf.Append( HEX[ c & 0xF ] ); - } - break; + case '\t': // =09 U+0009 HORIZONTAL TABULATION \t + buf.Append('\t'); //OK after first position. + break; + case '\n': // =0A U+000A LINE FEED \n + buf.Append('\\').Append('n'); + break; + case '\f': // =0C U+000C FORM FEED \f + buf.Append('\\').Append('f'); + break; + case '\r': // =0D U+000D CARRIAGE RETURN \r + buf.Append('\\').Append('r'); + break; + case '\\': // 92: '\' + buf.Append('\\').Append(c); + break; + + default: + if (c > 31 && c < 127) + { + buf.Append(c); + } + else + { + buf.Append('\\').Append('u'); + buf.Append(HEX[(c >> 12) & 0xF]); + buf.Append(HEX[(c >> 8) & 0xF]); + buf.Append(HEX[(c >> 4) & 0xF]); + buf.Append(HEX[c & 0xF]); + } + break; } } diff --git a/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/ParseException.cs b/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/ParseException.cs index 50e658fa..180910fc 100644 --- a/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/ParseException.cs +++ b/src/Stars.Data/Model/Metadata/Kajabity/Tools/Java/ParseException.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright 2009-14 Simon J. Williams. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -20,18 +20,18 @@ namespace Kajabity.Tools.Java { - /// - /// An exception thrown by when parsing - /// a properties stream. - /// - public class ParseException : System.Exception - { - /// - /// Construct an exception with an error message. - /// - /// A descriptive message for the exception - public ParseException( string message ) : base( message ) - { - } - } + /// + /// An exception thrown by when parsing + /// a properties stream. + /// + public class ParseException : Exception + { + /// + /// Construct an exception with an error message. + /// + /// A descriptive message for the exception + public ParseException(string message) : base(message) + { + } + } } diff --git a/src/Stars.Data/Model/Metadata/Kanopus/KanopusVMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Kanopus/KanopusVMetadataExtractor.cs index f9929455..fcf56132 100644 --- a/src/Stars.Data/Model/Metadata/Kanopus/KanopusVMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Kanopus/KanopusVMetadataExtractor.cs @@ -11,10 +11,10 @@ using Stac.Extensions.Eo; using Stac.Extensions.Processing; using Stac.Extensions.Projection; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Kanopus { @@ -27,8 +27,7 @@ public KanopusVMetadataExtractor(ILogger logger, IRes public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset metadataAsset = GetMetadataAsset(item); @@ -89,7 +88,7 @@ private void AddProcessingStacExtension(KanopusVMetadata metadata, StacItem stac private string GetProcessingLevel(KanopusVMetadata metadata) { - return String.Format("L{0}", metadata.GetString("/cProcLevel")); + return string.Format("L{0}", metadata.GetString("/cProcLevel")); } private IDictionary GetCommonMetadata(KanopusVMetadata metadata) @@ -103,7 +102,7 @@ private IDictionary GetCommonMetadata(KanopusVMetadata metadata) return properties; } - private void FillBasicsProperties(KanopusVMetadata metadata, IDictionary properties) + private void FillBasicsProperties(KanopusVMetadata metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -117,13 +116,13 @@ private void FillBasicsProperties(KanopusVMetadata metadata, IDictionary properties) + private void AddOtherProperties(KanopusVMetadata metadata, IDictionary properties) { if (IncludeProviderProperty) { AddSingleProvider( properties, - "Roscosmos", + "Roscosmos", "Kanopus-V is an Earth observation minisatellite mission of the Russian Space Agency, Roscosmos and ROSHYDROMET/Planeta. The overall objective is to monitor Earth's surface, the atmosphere, ionosphere, and magnetosphere to detect and study the probability of strong earthquake occurrence.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.eoportal.org/satellite-missions/kanopus-v-1") @@ -141,11 +140,11 @@ private void FillDateTimeProperties(KanopusVMetadata metadata, Dictionary/dSessionDateUTC") + " " + metadata.GetString("/tSessionTimeUTC"), format, null, DateTimeStyles.AssumeUniversal, out dt)) { - int[] date = Array.ConvertAll(metadata.GetString("/dSessionDateUTC").Split('/'), + int[] date = Array.ConvertAll(metadata.GetString("/dSessionDateUTC").Split('/'), s => int.Parse(s)); string stime = metadata.GetString("/tSessionTimeUTC").Split('.')[0]; int milli = int.Parse(metadata.GetString("/tSessionTimeUTC").Split('.')[1]); - int[] time = Array.ConvertAll(stime.Split(':'), + int[] time = Array.ConvertAll(stime.Split(':'), s => int.Parse(s)); dt = new DateTime(date[2], date[1], date[0], time[0], time[1], time[2], milli, DateTimeKind.Utc); } @@ -170,21 +169,21 @@ private void FillPlatformDefinition(KanopusVMetadata metadata, Dictionary positions = new List(); + List positions = new List(); for (int i = 0; i < metadata.GetString("/bLat").Split(',').Length; i++) { - positions.Add(new GeoJSON.Net.Geometry.Position( + positions.Add(new Position( metadata.GetDouble("/bLat")[i], metadata.GetDouble("/bLon")[i]) ); } positions.Add(positions.First()); - GeoJSON.Net.Geometry.LineString lineString = new GeoJSON.Net.Geometry.LineString( + LineString lineString = new LineString( positions.ToArray() ); - return new GeoJSON.Net.Geometry.Polygon(new GeoJSON.Net.Geometry.LineString[] { lineString }).NormalizePolygon(); + return new Polygon(new LineString[] { lineString }).NormalizePolygon(); } @@ -210,7 +209,7 @@ private StacAsset GetBandAsset(StacItem stacItem, string name, IAsset asset, Kan { for (int i = 0; i < numberOfChannels; i++) { - channelValues = Array.ConvertAll((metadata.GetString("/bSpectralZone").Split(',')), (Double.Parse)); + channelValues = Array.ConvertAll((metadata.GetString("/bSpectralZone").Split(',')), (double.Parse)); mean = channelValues.Sum() / channelValues.Length; if (mean < 0.69 && mean > 0.63) @@ -290,7 +289,7 @@ protected virtual IAsset GetMetadataAsset(IItem item) manifestAsset = FindFirstAssetFromFileNameRegex(item, @".*MSS.*\.xml"); if (manifestAsset != null) return manifestAsset; - throw new FileNotFoundException(String.Format("Unable to find the summary file asset")); + throw new FileNotFoundException(string.Format("Unable to find the summary file asset")); } public virtual async Task ReadMetadata(IAsset manifestAsset) @@ -314,7 +313,7 @@ public class KanopusVMetadata public KanopusVMetadata(IAsset summaryAsset) { this.summaryAsset = summaryAsset; - this.properties = new Dictionary>(); + properties = new Dictionary>(); Assets = new List(); } @@ -356,7 +355,7 @@ public string GetString(string key, bool throwIfMissing = true) { return properties[keys[0]][keys[1]]; } - if (throwIfMissing) throw new Exception(String.Format("No value for key '{0}'", key)); + if (throwIfMissing) throw new Exception(string.Format("No value for key '{0}'", key)); return null; } @@ -368,9 +367,9 @@ public long GetLong(string key, bool throwIfMissing = true) if (long.TryParse(properties[keys[0]][keys[1]], out long value)) return value; else - throw new FormatException(String.Format("Invalid value for key '{0}' (not an int)", key)); + throw new FormatException(string.Format("Invalid value for key '{0}' (not an int)", key)); } - if (throwIfMissing) throw new Exception(String.Format("No value for key '{0}'", key)); + if (throwIfMissing) throw new Exception(string.Format("No value for key '{0}'", key)); return 0; } @@ -382,9 +381,9 @@ public int GetInt(string key, bool throwIfMissing = true) if (int.TryParse(properties[keys[0]][keys[1]], out int value)) return value; else - throw new FormatException(String.Format("Invalid value for key '{0}' (not an int)", key)); + throw new FormatException(string.Format("Invalid value for key '{0}' (not an int)", key)); } - if (throwIfMissing) throw new Exception(String.Format("No value for key '{0}'", key)); + if (throwIfMissing) throw new Exception(string.Format("No value for key '{0}'", key)); return 0; } @@ -393,11 +392,11 @@ public double[] GetDouble(string key, bool throwIfMissing = true) string[] keys = key.Split('/'); if (properties[keys[0]].ContainsKey(keys[1])) { - double[] value = Array.ConvertAll(properties[keys[0]][keys[1]].Split(','), (Double.Parse)); + double[] value = Array.ConvertAll(properties[keys[0]][keys[1]].Split(','), (double.Parse)); return value; } - if (throwIfMissing) throw new Exception(String.Format("No value for key '{0}'", key)); + if (throwIfMissing) throw new Exception(string.Format("No value for key '{0}'", key)); return null; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Kompsat3/Auxiliary.cs b/src/Stars.Data/Model/Metadata/Kompsat3/Auxiliary.cs index 8607d675..445acf95 100644 --- a/src/Stars.Data/Model/Metadata/Kompsat3/Auxiliary.cs +++ b/src/Stars.Data/Model/Metadata/Kompsat3/Auxiliary.cs @@ -1,9 +1,9 @@ -using System.Xml.Serialization; +using System; using System.Collections.Generic; -using System; -using System.Globalization; using System.ComponentModel; using System.Diagnostics; +using System.Globalization; +using System.Xml.Serialization; namespace Terradue.Stars.Data.Model.Metadata.Kompsat3 { @@ -720,7 +720,7 @@ public XmlKeyTextValueListWrapper XmlKeys { get { - return new XmlKeyTextValueListWrapper(() => this.Images); + return new XmlKeyTextValueListWrapper(() => Images); } set { @@ -736,4 +736,4 @@ public XmlKeyTextValueListWrapper XmlKeys } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Kompsat3/Kompsat3MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Kompsat3/Kompsat3MetadataExtractor.cs index ef4ef6b5..1105f7e4 100644 --- a/src/Stars.Data/Model/Metadata/Kompsat3/Kompsat3MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Kompsat3/Kompsat3MetadataExtractor.cs @@ -7,23 +7,23 @@ using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; +using Humanizer; using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; using ProjNet.CoordinateSystems; using Stac; using Stac.Extensions.Eo; using Stac.Extensions.Processing; using Stac.Extensions.Projection; +using Stac.Extensions.Raster; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; +using Terradue.Stars.Services; using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services.Plugins; -using Stac.Extensions.Raster; -using Humanizer; -using Newtonsoft.Json.Linq; -using Terradue.Stars.Services; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Kompsat3 { @@ -44,12 +44,8 @@ public Kompsat3MetadataExtraction(ILogger logger, IR protected override async Task ExtractMetadata(IItem item, string suffix) { logger.LogDebug("Retrieving the metadata file in the product package"); - IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(Aux\\.xml)$"); - if (auxFile == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } - logger.LogDebug(String.Format("Metadata file is {0}", auxFile.Uri)); + IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(Aux\\.xml)$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); + logger.LogDebug(string.Format("Metadata file is {0}", auxFile.Uri)); IStreamResource auxFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(auxFile, System.Threading.CancellationToken.None); if (auxFileStreamable == null) @@ -78,7 +74,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi FillBasicsProperties(auxiliary, stacItem.Properties); AddOtherProperties(auxiliary, stacItem); - return StacItemNode.Create(stacItem, item.Uri);; ; + return StacItemNode.Create(stacItem, item.Uri); ; ; } @@ -160,7 +156,7 @@ private void AddbandAsset(StacItem stacItem, string bandKey, IAsset asset, IImag bandName = "PAN"; EoBandObject eoBandObject = new EoBandObject(bandKey, GetEoCommonName(bandName)); - var bandRanges = Array.ConvertAll(image.Bandwidth.Split('-'), s => double.Parse(s, CultureInfo.CreateSpecificCulture("en-US"))); + var bandRanges = Array.ConvertAll(image.Bandwidth.Split('-'), s => double.Parse(s, CultureInfo.CreateSpecificCulture("en-US"))); double? bandwidth = (bandRanges.Length > 1 ? (bandRanges[0] + ((bandRanges[1] - bandRanges[0]) / 2)) : bandRanges[0]) / 100; stacAsset.EoExtension().CloudCover = image.CloudCover?.Average; RasterBand rasterBand = new RasterBand(); @@ -205,7 +201,7 @@ private void AddOtherProperties(Auxiliary auxiliary, StacItem stacItem) { AddSingleProvider( stacItem.Properties, - "KARI", + "KARI", "KOMPSAT-3 is an optical high-resolution Korean observation mission. The objective is to provide observation continuity from the KOMPSAT-1 and KOMPSAT-2 missions to meet the nation's needs for high-resolution optical imagery required for GIS and other environmental, agricultural and oceanographic monitoring applications.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.eoportal.org/satellite-missions/kompsat-3") @@ -355,7 +351,7 @@ private void FillDateTimeProperties(Auxiliary auxiliary, Dictionary properties) + private void FillBasicsProperties(Auxiliary auxiliary, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -406,18 +402,13 @@ public static async Task DeserializeAuxiliary(IStreamResource auxilia protected virtual IAsset GetMetadataAsset(IItem item) { - IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"[0-9a-zA-Z_-]*(Aux\.xml)$"); - if (manifestAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } + IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"[0-9a-zA-Z_-]*(Aux\.xml)$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); return manifestAsset; } public override bool CanProcess(IResource route, IDestination destinations) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset metadataAsset = GetMetadataAsset(item); @@ -433,4 +424,4 @@ public override bool CanProcess(IResource route, IDestination destinations) } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Kompsat3/XmlKeyTextValueListWrapper.cs b/src/Stars.Data/Model/Metadata/Kompsat3/XmlKeyTextValueListWrapper.cs index 8c42a3d5..8b5c7f0e 100644 --- a/src/Stars.Data/Model/Metadata/Kompsat3/XmlKeyTextValueListWrapper.cs +++ b/src/Stars.Data/Model/Metadata/Kompsat3/XmlKeyTextValueListWrapper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; @@ -115,7 +115,7 @@ public CollectionWrapper(ICollection baseCollection) { if (baseCollection == null) throw new ArgumentNullException(); - this.getCollection = () => baseCollection; + getCollection = () => baseCollection; } public CollectionWrapper(Func> getCollection) @@ -129,8 +129,7 @@ public bool IsWrapperFor(ICollection other) { if (other == Collection) return true; - var otherWrapper = other as CollectionWrapper; - return otherWrapper != null && otherWrapper.IsWrapperFor(Collection); + return other is CollectionWrapper otherWrapper && otherWrapper.IsWrapperFor(Collection); } ICollection Collection { get { return getCollection(); } } @@ -192,4 +191,4 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() #endregion } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Kompsat5/AuxiliaryL1D.cs b/src/Stars.Data/Model/Metadata/Kompsat5/AuxiliaryL1D.cs index 6e2365fc..0bba32f8 100644 --- a/src/Stars.Data/Model/Metadata/Kompsat5/AuxiliaryL1D.cs +++ b/src/Stars.Data/Model/Metadata/Kompsat5/AuxiliaryL1D.cs @@ -1,863 +1,870 @@ +using System.Collections.Generic; using System.Xml.Serialization; -using System.Collections.Generic; -using System; -using System.Globalization; namespace Terradue.Stars.Data.Model.Metadata.Kompsat5 { - [XmlRoot(ElementName="BurstsPerSubswath")] - public class BurstsPerSubswath { + [XmlRoot(ElementName = "BurstsPerSubswath")] + public class BurstsPerSubswath + { - [XmlAttribute(AttributeName="id")] - public int Id { get; set; } + [XmlAttribute(AttributeName = "id")] + public int Id { get; set; } - [XmlElement(ElementName="FinalOnBoardTime")] - public double FinalOnBoardTime { get; set; } + [XmlElement(ElementName = "FinalOnBoardTime")] + public double FinalOnBoardTime { get; set; } - [XmlElement(ElementName="InitialOnBoardTime")] - public double InitialOnBoardTime { get; set; } + [XmlElement(ElementName = "InitialOnBoardTime")] + public double InitialOnBoardTime { get; set; } - [XmlElement(ElementName="AzimuthFirstTime")] - public double AzimuthFirstTime { get; set; } + [XmlElement(ElementName = "AzimuthFirstTime")] + public double AzimuthFirstTime { get; set; } - [XmlElement(ElementName="AzimuthLastTime")] - public double AzimuthLastTime { get; set; } + [XmlElement(ElementName = "AzimuthLastTime")] + public double AzimuthLastTime { get; set; } - [XmlElement(ElementName="AzimuthRampCode")] - public string AzimuthRampCode { get; set; } + [XmlElement(ElementName = "AzimuthRampCode")] + public string AzimuthRampCode { get; set; } - [XmlElement(ElementName="AzimuthRampCodeChangeLines")] - public int AzimuthRampCodeChangeLines { get; set; } + [XmlElement(ElementName = "AzimuthRampCodeChangeLines")] + public int AzimuthRampCodeChangeLines { get; set; } - [XmlElement(ElementName="AzimuthSteering")] - public string AzimuthSteering { get; set; } + [XmlElement(ElementName = "AzimuthSteering")] + public string AzimuthSteering { get; set; } - [XmlElement(ElementName="ElevationRampCode")] - public int ElevationRampCode { get; set; } + [XmlElement(ElementName = "ElevationRampCode")] + public int ElevationRampCode { get; set; } - [XmlElement(ElementName="ElevationRampCodeChangeLines")] - public string ElevationRampCodeChangeLines { get; set; } + [XmlElement(ElementName = "ElevationRampCodeChangeLines")] + public string ElevationRampCodeChangeLines { get; set; } - [XmlElement(ElementName="ElevationSteering")] - public string ElevationSteering { get; set; } + [XmlElement(ElementName = "ElevationSteering")] + public string ElevationSteering { get; set; } - [XmlElement(ElementName="RangeFirstTimeChangeLines")] - public string RangeFirstTimeChangeLines { get; set; } + [XmlElement(ElementName = "RangeFirstTimeChangeLines")] + public string RangeFirstTimeChangeLines { get; set; } - [XmlElement(ElementName="RangeFirstTimes")] - public string RangeFirstTimes { get; set; } + [XmlElement(ElementName = "RangeFirstTimes")] + public string RangeFirstTimes { get; set; } - [XmlElement(ElementName="ReceiverGain")] - public int ReceiverGain { get; set; } + [XmlElement(ElementName = "ReceiverGain")] + public int ReceiverGain { get; set; } - [XmlElement(ElementName="ReceiverGainChangeLines")] - public string ReceiverGainChangeLines { get; set; } + [XmlElement(ElementName = "ReceiverGainChangeLines")] + public string ReceiverGainChangeLines { get; set; } - [XmlElement(ElementName="RAWAmbiguousDopplerCentroid")] - public string RAWAmbiguousDopplerCentroid { get; set; } + [XmlElement(ElementName = "RAWAmbiguousDopplerCentroid")] + public string RAWAmbiguousDopplerCentroid { get; set; } - [XmlElement(ElementName="RAWBias")] - public string RAWBias { get; set; } + [XmlElement(ElementName = "RAWBias")] + public string RAWBias { get; set; } - [XmlElement(ElementName="RAWGainImbalance")] - public string RAWGainImbalance { get; set; } + [XmlElement(ElementName = "RAWGainImbalance")] + public string RAWGainImbalance { get; set; } - [XmlElement(ElementName="RAWIQNormality")] - public string RAWIQNormality { get; set; } + [XmlElement(ElementName = "RAWIQNormality")] + public string RAWIQNormality { get; set; } - [XmlElement(ElementName="RAWMissingBlocksStartLines")] - public int RAWMissingBlocksStartLines { get; set; } + [XmlElement(ElementName = "RAWMissingBlocksStartLines")] + public int RAWMissingBlocksStartLines { get; set; } - [XmlElement(ElementName="RAWMissingLinesperBlock")] - public int RAWMissingLinesperBlock { get; set; } + [XmlElement(ElementName = "RAWMissingLinesperBlock")] + public int RAWMissingLinesperBlock { get; set; } - [XmlElement(ElementName="RAWMissingLinesPercentage")] - public int RAWMissingLinesPercentage { get; set; } + [XmlElement(ElementName = "RAWMissingLinesPercentage")] + public int RAWMissingLinesPercentage { get; set; } - [XmlElement(ElementName="RAWOverSaturatedPercentage")] - public string RAWOverSaturatedPercentage { get; set; } + [XmlElement(ElementName = "RAWOverSaturatedPercentage")] + public string RAWOverSaturatedPercentage { get; set; } - [XmlElement(ElementName="RAWPhaseUniformity")] - public string RAWPhaseUniformity { get; set; } + [XmlElement(ElementName = "RAWPhaseUniformity")] + public string RAWPhaseUniformity { get; set; } - [XmlElement(ElementName="RAWStandardDeviation")] - public string RAWStandardDeviation { get; set; } + [XmlElement(ElementName = "RAWStandardDeviation")] + public string RAWStandardDeviation { get; set; } - [XmlElement(ElementName="RAWUnderSaturatedPercentage")] - public string RAWUnderSaturatedPercentage { get; set; } + [XmlElement(ElementName = "RAWUnderSaturatedPercentage")] + public string RAWUnderSaturatedPercentage { get; set; } - [XmlText] - public string Text { get; set; } - } + [XmlText] + public string Text { get; set; } + } - [XmlRoot(ElementName="BurstsPerSubswaths")] - public class BurstsPerSubswaths { + [XmlRoot(ElementName = "BurstsPerSubswaths")] + public class BurstsPerSubswaths + { - [XmlElement(ElementName="BurstsPerSubswath")] - public List BurstsPerSubswath { get; set; } - } + [XmlElement(ElementName = "BurstsPerSubswath")] + public List BurstsPerSubswath { get; set; } + } - [XmlRoot(ElementName="GIM")] - public class GIM { + [XmlRoot(ElementName = "GIM")] + public class GIM + { - [XmlElement(ElementName="LayoverPixelValue")] - public int LayoverPixelValue { get; set; } + [XmlElement(ElementName = "LayoverPixelValue")] + public int LayoverPixelValue { get; set; } - [XmlElement(ElementName="ShadowingPixelValue")] - public int ShadowingPixelValue { get; set; } + [XmlElement(ElementName = "ShadowingPixelValue")] + public int ShadowingPixelValue { get; set; } - [XmlElement(ElementName="RescalingFactor")] - public double RescalingFactor { get; set; } + [XmlElement(ElementName = "RescalingFactor")] + public double RescalingFactor { get; set; } - [XmlElement(ElementName="Offset")] - public int Offset { get; set; } + [XmlElement(ElementName = "Offset")] + public int Offset { get; set; } - [XmlElement(ElementName="InvalidValue")] - public int InvalidValue { get; set; } + [XmlElement(ElementName = "InvalidValue")] + public int InvalidValue { get; set; } - [XmlElement(ElementName="LayoverPixelPercentage")] - public int LayoverPixelPercentage { get; set; } + [XmlElement(ElementName = "LayoverPixelPercentage")] + public int LayoverPixelPercentage { get; set; } - [XmlElement(ElementName="ShadowingPixelPercentage")] - public int ShadowingPixelPercentage { get; set; } - } + [XmlElement(ElementName = "ShadowingPixelPercentage")] + public int ShadowingPixelPercentage { get; set; } + } - [XmlRoot(ElementName="SubSwath")] - public class SubSwath { + [XmlRoot(ElementName = "SubSwath")] + public class SubSwath + { - [XmlElement(ElementName="AntennaBeamCode")] - public int AntennaBeamCode { get; set; } + [XmlElement(ElementName = "AntennaBeamCode")] + public int AntennaBeamCode { get; set; } - [XmlElement(ElementName="AntennaBeamElevation")] - public double AntennaBeamElevation { get; set; } + [XmlElement(ElementName = "AntennaBeamElevation")] + public double AntennaBeamElevation { get; set; } - [XmlElement(ElementName="AzimuthInstrumentGeometricResolution")] - public double AzimuthInstrumentGeometricResolution { get; set; } + [XmlElement(ElementName = "AzimuthInstrumentGeometricResolution")] + public double AzimuthInstrumentGeometricResolution { get; set; } - [XmlElement(ElementName="BeamID")] - public string BeamID { get; set; } + [XmlElement(ElementName = "BeamID")] + public string BeamID { get; set; } - [XmlElement(ElementName="BeamOffNadirAngle")] - public double BeamOffNadirAngle { get; set; } + [XmlElement(ElementName = "BeamOffNadirAngle")] + public double BeamOffNadirAngle { get; set; } - [XmlElement(ElementName="BurstsperSubswath")] - public int BurstsperSubswath { get; set; } + [XmlElement(ElementName = "BurstsperSubswath")] + public int BurstsperSubswath { get; set; } - [XmlElement(ElementName="EchoSamplingWindowLength")] - public int EchoSamplingWindowLength { get; set; } + [XmlElement(ElementName = "EchoSamplingWindowLength")] + public int EchoSamplingWindowLength { get; set; } - [XmlElement(ElementName="GroundRangeInstrumentGeometricResolution")] - public double GroundRangeInstrumentGeometricResolution { get; set; } + [XmlElement(ElementName = "GroundRangeInstrumentGeometricResolution")] + public double GroundRangeInstrumentGeometricResolution { get; set; } - [XmlElement(ElementName="LinesperBurst")] - public int LinesperBurst { get; set; } + [XmlElement(ElementName = "LinesperBurst")] + public int LinesperBurst { get; set; } - [XmlElement(ElementName="PassBandIFFilter")] - public int PassBandIFFilter { get; set; } + [XmlElement(ElementName = "PassBandIFFilter")] + public int PassBandIFFilter { get; set; } - [XmlElement(ElementName="Polarisation")] - public string Polarisation { get; set; } + [XmlElement(ElementName = "Polarisation")] + public string Polarisation { get; set; } - [XmlElement(ElementName="PRF")] - public double PRF { get; set; } + [XmlElement(ElementName = "PRF")] + public double PRF { get; set; } - [XmlElement(ElementName="RangeChirpLength")] - public double RangeChirpLength { get; set; } + [XmlElement(ElementName = "RangeChirpLength")] + public double RangeChirpLength { get; set; } - [XmlElement(ElementName="RangeChirpRate")] - public double RangeChirpRate { get; set; } + [XmlElement(ElementName = "RangeChirpRate")] + public double RangeChirpRate { get; set; } - [XmlElement(ElementName="RangeChirpSamples")] - public int RangeChirpSamples { get; set; } + [XmlElement(ElementName = "RangeChirpSamples")] + public int RangeChirpSamples { get; set; } - [XmlElement(ElementName="Rank")] - public int Rank { get; set; } + [XmlElement(ElementName = "Rank")] + public int Rank { get; set; } - [XmlElement(ElementName="ReferenceDechirpingTime")] - public double ReferenceDechirpingTime { get; set; } + [XmlElement(ElementName = "ReferenceDechirpingTime")] + public double ReferenceDechirpingTime { get; set; } - [XmlElement(ElementName="SamplingRate")] - public int SamplingRate { get; set; } + [XmlElement(ElementName = "SamplingRate")] + public int SamplingRate { get; set; } - [XmlElement(ElementName="SyntheticApertureDuration")] - public double SyntheticApertureDuration { get; set; } + [XmlElement(ElementName = "SyntheticApertureDuration")] + public double SyntheticApertureDuration { get; set; } - [XmlElement(ElementName="AzimuthBandwidthperLook")] - public double AzimuthBandwidthperLook { get; set; } + [XmlElement(ElementName = "AzimuthBandwidthperLook")] + public double AzimuthBandwidthperLook { get; set; } - [XmlElement(ElementName="AzimuthFocusingBandwidth")] - public double AzimuthFocusingBandwidth { get; set; } + [XmlElement(ElementName = "AzimuthFocusingBandwidth")] + public double AzimuthFocusingBandwidth { get; set; } - [XmlElement(ElementName="AzimuthFocusingTransitionBandwidth")] - public int AzimuthFocusingTransitionBandwidth { get; set; } + [XmlElement(ElementName = "AzimuthFocusingTransitionBandwidth")] + public int AzimuthFocusingTransitionBandwidth { get; set; } - [XmlElement(ElementName="AzimuthMultilookingTransitionBandwidth")] - public int AzimuthMultilookingTransitionBandwidth { get; set; } + [XmlElement(ElementName = "AzimuthMultilookingTransitionBandwidth")] + public int AzimuthMultilookingTransitionBandwidth { get; set; } - [XmlElement(ElementName="ECEFBeamPointingforProcessing")] - public string ECEFBeamPointingforProcessing { get; set; } + [XmlElement(ElementName = "ECEFBeamPointingforProcessing")] + public string ECEFBeamPointingforProcessing { get; set; } - [XmlElement(ElementName="RangeBandwidthperLook")] - public double RangeBandwidthperLook { get; set; } + [XmlElement(ElementName = "RangeBandwidthperLook")] + public double RangeBandwidthperLook { get; set; } - [XmlElement(ElementName="RangeFocusingBandwidth")] - public double RangeFocusingBandwidth { get; set; } + [XmlElement(ElementName = "RangeFocusingBandwidth")] + public double RangeFocusingBandwidth { get; set; } - [XmlElement(ElementName="RangeFocusingTransitionBandwidth")] - public double RangeFocusingTransitionBandwidth { get; set; } + [XmlElement(ElementName = "RangeFocusingTransitionBandwidth")] + public double RangeFocusingTransitionBandwidth { get; set; } - [XmlElement(ElementName="RangeMultilookingTransitionBandwidth")] - public int RangeMultilookingTransitionBandwidth { get; set; } + [XmlElement(ElementName = "RangeMultilookingTransitionBandwidth")] + public int RangeMultilookingTransitionBandwidth { get; set; } - [XmlElement(ElementName="RAWStatisticsBlockSize")] - public string RAWStatisticsBlockSize { get; set; } + [XmlElement(ElementName = "RAWStatisticsBlockSize")] + public string RAWStatisticsBlockSize { get; set; } - [XmlElement(ElementName="InternalPower")] - public string InternalPower { get; set; } + [XmlElement(ElementName = "InternalPower")] + public string InternalPower { get; set; } - [XmlElement(ElementName="CentreGeodeticCoordinates")] - public string CentreGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "CentreGeodeticCoordinates")] + public string CentreGeodeticCoordinates { get; set; } - [XmlElement(ElementName="AzimuthAntennaPatternGains")] - public string AzimuthAntennaPatternGains { get; set; } + [XmlElement(ElementName = "AzimuthAntennaPatternGains")] + public string AzimuthAntennaPatternGains { get; set; } - [XmlElement(ElementName="AzimuthAntennaPatternOrigin")] - public double AzimuthAntennaPatternOrigin { get; set; } + [XmlElement(ElementName = "AzimuthAntennaPatternOrigin")] + public double AzimuthAntennaPatternOrigin { get; set; } - [XmlElement(ElementName="AzimuthAntennaPatternResolution")] - public double AzimuthAntennaPatternResolution { get; set; } + [XmlElement(ElementName = "AzimuthAntennaPatternResolution")] + public double AzimuthAntennaPatternResolution { get; set; } - [XmlElement(ElementName="CalibrationConstant")] - public double CalibrationConstant { get; set; } + [XmlElement(ElementName = "CalibrationConstant")] + public double CalibrationConstant { get; set; } - [XmlElement(ElementName="CalibrationConstantEstimationUTC")] - public string CalibrationConstantEstimationUTC { get; set; } + [XmlElement(ElementName = "CalibrationConstantEstimationUTC")] + public string CalibrationConstantEstimationUTC { get; set; } - [XmlElement(ElementName="RangeAntennaPatternGains")] - public string RangeAntennaPatternGains { get; set; } + [XmlElement(ElementName = "RangeAntennaPatternGains")] + public string RangeAntennaPatternGains { get; set; } - [XmlElement(ElementName="RangeAntennaPatternOrigin")] - public string RangeAntennaPatternOrigin { get; set; } + [XmlElement(ElementName = "RangeAntennaPatternOrigin")] + public string RangeAntennaPatternOrigin { get; set; } - [XmlElement(ElementName="RangeAntennaPatternResolution")] - public double RangeAntennaPatternResolution { get; set; } + [XmlElement(ElementName = "RangeAntennaPatternResolution")] + public double RangeAntennaPatternResolution { get; set; } - [XmlElement(ElementName="AlongTrackVector")] - public object AlongTrackVector { get; set; } + [XmlElement(ElementName = "AlongTrackVector")] + public object AlongTrackVector { get; set; } - [XmlElement(ElementName="AzimuthCalibrationFactor")] - public object AzimuthCalibrationFactor { get; set; } + [XmlElement(ElementName = "AzimuthCalibrationFactor")] + public object AzimuthCalibrationFactor { get; set; } - [XmlElement(ElementName="ReferenceInternalPower")] - public int ReferenceInternalPower { get; set; } + [XmlElement(ElementName = "ReferenceInternalPower")] + public int ReferenceInternalPower { get; set; } - [XmlElement(ElementName="DopplerAmbiguity")] - public int DopplerAmbiguity { get; set; } + [XmlElement(ElementName = "DopplerAmbiguity")] + public int DopplerAmbiguity { get; set; } - [XmlElement(ElementName="BurstsPerSubswaths")] - public BurstsPerSubswaths BurstsPerSubswaths { get; set; } + [XmlElement(ElementName = "BurstsPerSubswaths")] + public BurstsPerSubswaths BurstsPerSubswaths { get; set; } - [XmlElement(ElementName="GIM")] - public GIM GIM { get; set; } + [XmlElement(ElementName = "GIM")] + public GIM GIM { get; set; } - [XmlAttribute(AttributeName="id")] - public int Id { get; set; } + [XmlAttribute(AttributeName = "id")] + public int Id { get; set; } - [XmlText] - public string Text { get; set; } + [XmlText] + public string Text { get; set; } - [XmlElement(ElementName="SBI")] - public MBI SBI { get; set; } - } + [XmlElement(ElementName = "SBI")] + public MBI SBI { get; set; } + } - [XmlRoot(ElementName="SubSwaths")] - public class SubSwaths { + [XmlRoot(ElementName = "SubSwaths")] + public class SubSwaths + { - [XmlElement(ElementName="SubSwath")] - public List SubSwath { get; set; } - } + [XmlElement(ElementName = "SubSwath")] + public List SubSwath { get; set; } + } - [XmlRoot(ElementName="QLK")] - public class QLK { + [XmlRoot(ElementName = "QLK")] + public class QLK + { - [XmlElement(ElementName="QuickLookColumnsOrder")] - public string QuickLookColumnsOrder { get; set; } + [XmlElement(ElementName = "QuickLookColumnsOrder")] + public string QuickLookColumnsOrder { get; set; } - [XmlElement(ElementName="QuickLookLinesOrder")] - public string QuickLookLinesOrder { get; set; } + [XmlElement(ElementName = "QuickLookLinesOrder")] + public string QuickLookLinesOrder { get; set; } - [XmlElement(ElementName="QuickLookColumnSpacing")] - public int QuickLookColumnSpacing { get; set; } + [XmlElement(ElementName = "QuickLookColumnSpacing")] + public int QuickLookColumnSpacing { get; set; } - [XmlElement(ElementName="QuickLookLineSpacing")] - public int QuickLookLineSpacing { get; set; } + [XmlElement(ElementName = "QuickLookLineSpacing")] + public int QuickLookLineSpacing { get; set; } - [XmlElement(ElementName="QuickLookProjectionID")] - public string QuickLookProjectionID { get; set; } - } + [XmlElement(ElementName = "QuickLookProjectionID")] + public string QuickLookProjectionID { get; set; } + } - [XmlRoot(ElementName="MBI")] - public class MBI { + [XmlRoot(ElementName = "MBI")] + public class MBI + { - [XmlElement(ElementName="ZeroDopplerAzimuthFirstTime")] - public double ZeroDopplerAzimuthFirstTime { get; set; } + [XmlElement(ElementName = "ZeroDopplerAzimuthFirstTime")] + public double ZeroDopplerAzimuthFirstTime { get; set; } - [XmlElement(ElementName="ZeroDopplerAzimuthLastTime")] - public double ZeroDopplerAzimuthLastTime { get; set; } + [XmlElement(ElementName = "ZeroDopplerAzimuthLastTime")] + public double ZeroDopplerAzimuthLastTime { get; set; } - [XmlElement(ElementName="ZeroDopplerRangeFirstTime")] - public double ZeroDopplerRangeFirstTime { get; set; } + [XmlElement(ElementName = "ZeroDopplerRangeFirstTime")] + public double ZeroDopplerRangeFirstTime { get; set; } - [XmlElement(ElementName="ZeroDopplerRangeLastTime")] - public double ZeroDopplerRangeLastTime { get; set; } + [XmlElement(ElementName = "ZeroDopplerRangeLastTime")] + public double ZeroDopplerRangeLastTime { get; set; } - [XmlElement(ElementName="ColumnSpacing")] - public string ColumnSpacing { get; set; } + [XmlElement(ElementName = "ColumnSpacing")] + public string ColumnSpacing { get; set; } - [XmlElement(ElementName="EquivalentNumberofLooks")] - public double EquivalentNumberofLooks { get; set; } + [XmlElement(ElementName = "EquivalentNumberofLooks")] + public double EquivalentNumberofLooks { get; set; } - [XmlElement(ElementName="LineSpacing")] - public string LineSpacing { get; set; } + [XmlElement(ElementName = "LineSpacing")] + public string LineSpacing { get; set; } - [XmlElement(ElementName="BottomLeftGeodeticCoordinates")] - public string BottomLeftGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "BottomLeftGeodeticCoordinates")] + public string BottomLeftGeodeticCoordinates { get; set; } - [XmlElement(ElementName="BottomRightGeodeticCoordinates")] - public string BottomRightGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "BottomRightGeodeticCoordinates")] + public string BottomRightGeodeticCoordinates { get; set; } - [XmlElement(ElementName="FarEarlyGeodeticCoordinates")] - public string FarEarlyGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "FarEarlyGeodeticCoordinates")] + public string FarEarlyGeodeticCoordinates { get; set; } - [XmlElement(ElementName="FarIncidenceAngle")] - public double FarIncidenceAngle { get; set; } + [XmlElement(ElementName = "FarIncidenceAngle")] + public double FarIncidenceAngle { get; set; } - [XmlElement(ElementName="FarLateGeodeticCoordinates")] - public string FarLateGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "FarLateGeodeticCoordinates")] + public string FarLateGeodeticCoordinates { get; set; } - [XmlElement(ElementName="FarLookAngle")] - public double FarLookAngle { get; set; } + [XmlElement(ElementName = "FarLookAngle")] + public double FarLookAngle { get; set; } - [XmlElement(ElementName="NearEarlyGeodeticCoordinates")] - public string NearEarlyGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "NearEarlyGeodeticCoordinates")] + public string NearEarlyGeodeticCoordinates { get; set; } - [XmlElement(ElementName="NearIncidenceAngle")] - public double NearIncidenceAngle { get; set; } + [XmlElement(ElementName = "NearIncidenceAngle")] + public double NearIncidenceAngle { get; set; } - [XmlElement(ElementName="NearLateGeodeticCoordinates")] - public string NearLateGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "NearLateGeodeticCoordinates")] + public string NearLateGeodeticCoordinates { get; set; } - [XmlElement(ElementName="NearLookAngle")] - public double NearLookAngle { get; set; } + [XmlElement(ElementName = "NearLookAngle")] + public double NearLookAngle { get; set; } - [XmlElement(ElementName="TopLeftGeodeticCoordinates")] - public string TopLeftGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "TopLeftGeodeticCoordinates")] + public string TopLeftGeodeticCoordinates { get; set; } - [XmlElement(ElementName="TopRightGeodeticCoordinates")] - public string TopRightGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "TopRightGeodeticCoordinates")] + public string TopRightGeodeticCoordinates { get; set; } - [XmlElement(ElementName="ImageMax")] - public string ImageMax { get; set; } + [XmlElement(ElementName = "ImageMax")] + public string ImageMax { get; set; } - [XmlElement(ElementName="ImageMean")] - public string ImageMean { get; set; } + [XmlElement(ElementName = "ImageMean")] + public string ImageMean { get; set; } - [XmlElement(ElementName="ImageMin")] - public string ImageMin { get; set; } + [XmlElement(ElementName = "ImageMin")] + public string ImageMin { get; set; } - [XmlElement(ElementName="ImageOverSaturatedPercentage")] - public string ImageOverSaturatedPercentage { get; set; } + [XmlElement(ElementName = "ImageOverSaturatedPercentage")] + public string ImageOverSaturatedPercentage { get; set; } - [XmlElement(ElementName="ImageStandardDeviation")] - public string ImageStandardDeviation { get; set; } + [XmlElement(ElementName = "ImageStandardDeviation")] + public string ImageStandardDeviation { get; set; } - [XmlElement(ElementName="ImageUnderSaturatedPercentage")] - public string ImageUnderSaturatedPercentage { get; set; } - } + [XmlElement(ElementName = "ImageUnderSaturatedPercentage")] + public string ImageUnderSaturatedPercentage { get; set; } + } - [XmlRoot(ElementName="Root")] - public class Root { + [XmlRoot(ElementName = "Root")] + public class Root + { - [XmlElement(ElementName="AcquisitionStationID")] - public string AcquisitionStationID { get; set; } + [XmlElement(ElementName = "AcquisitionStationID")] + public string AcquisitionStationID { get; set; } - [XmlElement(ElementName="DeliveryMode")] - public string DeliveryMode { get; set; } + [XmlElement(ElementName = "DeliveryMode")] + public string DeliveryMode { get; set; } - [XmlElement(ElementName="DownlinkStartUTC")] - public string DownlinkStartUTC { get; set; } + [XmlElement(ElementName = "DownlinkStartUTC")] + public string DownlinkStartUTC { get; set; } - [XmlElement(ElementName="DownlinkStopUTC")] - public string DownlinkStopUTC { get; set; } + [XmlElement(ElementName = "DownlinkStopUTC")] + public string DownlinkStopUTC { get; set; } - [XmlElement(ElementName="MissionID")] - public string MissionID { get; set; } + [XmlElement(ElementName = "MissionID")] + public string MissionID { get; set; } - [XmlElement(ElementName="ProcessingCentre")] - public string ProcessingCentre { get; set; } + [XmlElement(ElementName = "ProcessingCentre")] + public string ProcessingCentre { get; set; } - [XmlElement(ElementName="ProductFilename")] - public string ProductFilename { get; set; } + [XmlElement(ElementName = "ProductFilename")] + public string ProductFilename { get; set; } - [XmlElement(ElementName="ProductSpecificationDocument")] - public string ProductSpecificationDocument { get; set; } + [XmlElement(ElementName = "ProductSpecificationDocument")] + public string ProductSpecificationDocument { get; set; } - [XmlElement(ElementName="ProductType")] - public string ProductType { get; set; } + [XmlElement(ElementName = "ProductType")] + public string ProductType { get; set; } - [XmlElement(ElementName="SatelliteID")] - public string SatelliteID { get; set; } + [XmlElement(ElementName = "SatelliteID")] + public string SatelliteID { get; set; } - [XmlElement(ElementName="BitsperSample")] - public int BitsperSample { get; set; } + [XmlElement(ElementName = "BitsperSample")] + public int BitsperSample { get; set; } - [XmlElement(ElementName="ColumnsOrder")] - public string ColumnsOrder { get; set; } + [XmlElement(ElementName = "ColumnsOrder")] + public string ColumnsOrder { get; set; } - [XmlElement(ElementName="ImageLayers")] - public int ImageLayers { get; set; } + [XmlElement(ElementName = "ImageLayers")] + public int ImageLayers { get; set; } - [XmlElement(ElementName="ImageScale")] - public string ImageScale { get; set; } + [XmlElement(ElementName = "ImageScale")] + public string ImageScale { get; set; } - [XmlElement(ElementName="LinesOrder")] - public string LinesOrder { get; set; } + [XmlElement(ElementName = "LinesOrder")] + public string LinesOrder { get; set; } - [XmlElement(ElementName="SampleFormat")] - public string SampleFormat { get; set; } + [XmlElement(ElementName = "SampleFormat")] + public string SampleFormat { get; set; } - [XmlElement(ElementName="SamplesperPixel")] - public int SamplesperPixel { get; set; } + [XmlElement(ElementName = "SamplesperPixel")] + public int SamplesperPixel { get; set; } - [XmlElement(ElementName="LeapSign")] - public int LeapSign { get; set; } + [XmlElement(ElementName = "LeapSign")] + public int LeapSign { get; set; } - [XmlElement(ElementName="LeapUTC")] - public string LeapUTC { get; set; } + [XmlElement(ElementName = "LeapUTC")] + public string LeapUTC { get; set; } - [XmlElement(ElementName="OrbitNumber")] - public int OrbitNumber { get; set; } + [XmlElement(ElementName = "OrbitNumber")] + public int OrbitNumber { get; set; } - [XmlElement(ElementName="ProgrammedImageID")] - public int ProgrammedImageID { get; set; } + [XmlElement(ElementName = "ProgrammedImageID")] + public int ProgrammedImageID { get; set; } - [XmlElement(ElementName="SceneSensingStartUTC")] - public string SceneSensingStartUTC { get; set; } + [XmlElement(ElementName = "SceneSensingStartUTC")] + public string SceneSensingStartUTC { get; set; } - [XmlElement(ElementName="SceneSensingStopUTC")] - public string SceneSensingStopUTC { get; set; } + [XmlElement(ElementName = "SceneSensingStopUTC")] + public string SceneSensingStopUTC { get; set; } - [XmlElement(ElementName="SelectiveAvailabilityStatus")] - public string SelectiveAvailabilityStatus { get; set; } + [XmlElement(ElementName = "SelectiveAvailabilityStatus")] + public string SelectiveAvailabilityStatus { get; set; } - [XmlElement(ElementName="AcquisitionMode")] - public string AcquisitionMode { get; set; } + [XmlElement(ElementName = "AcquisitionMode")] + public string AcquisitionMode { get; set; } - [XmlElement(ElementName="AntennaLength")] - public double AntennaLength { get; set; } + [XmlElement(ElementName = "AntennaLength")] + public double AntennaLength { get; set; } - [XmlElement(ElementName="AzimuthBeamwidth")] - public double AzimuthBeamwidth { get; set; } + [XmlElement(ElementName = "AzimuthBeamwidth")] + public double AzimuthBeamwidth { get; set; } - [XmlElement(ElementName="LookSide")] - public string LookSide { get; set; } + [XmlElement(ElementName = "LookSide")] + public string LookSide { get; set; } - [XmlElement(ElementName="MultiBeamID")] - public string MultiBeamID { get; set; } + [XmlElement(ElementName = "MultiBeamID")] + public string MultiBeamID { get; set; } - [XmlElement(ElementName="OriginalBitQuantisation")] - public int OriginalBitQuantisation { get; set; } + [XmlElement(ElementName = "OriginalBitQuantisation")] + public int OriginalBitQuantisation { get; set; } - [XmlElement(ElementName="RadarFrequency")] - public double RadarFrequency { get; set; } + [XmlElement(ElementName = "RadarFrequency")] + public double RadarFrequency { get; set; } - [XmlElement(ElementName="RadarWavelength")] - public double RadarWavelength { get; set; } + [XmlElement(ElementName = "RadarWavelength")] + public double RadarWavelength { get; set; } - [XmlElement(ElementName="SubswathsNumber")] - public int SubswathsNumber { get; set; } + [XmlElement(ElementName = "SubswathsNumber")] + public int SubswathsNumber { get; set; } - [XmlElement(ElementName="GeometricConformity")] - public double GeometricConformity { get; set; } + [XmlElement(ElementName = "GeometricConformity")] + public double GeometricConformity { get; set; } - [XmlElement(ElementName="GroundRangeGeometricResolution")] - public double GroundRangeGeometricResolution { get; set; } + [XmlElement(ElementName = "GroundRangeGeometricResolution")] + public double GroundRangeGeometricResolution { get; set; } - [XmlElement(ElementName="AzimuthGeometricResolution")] - public double AzimuthGeometricResolution { get; set; } + [XmlElement(ElementName = "AzimuthGeometricResolution")] + public double AzimuthGeometricResolution { get; set; } - [XmlElement(ElementName="AttitudeQuaternions")] - public string AttitudeQuaternions { get; set; } + [XmlElement(ElementName = "AttitudeQuaternions")] + public string AttitudeQuaternions { get; set; } - [XmlElement(ElementName="AttitudeTimes")] - public string AttitudeTimes { get; set; } + [XmlElement(ElementName = "AttitudeTimes")] + public string AttitudeTimes { get; set; } - [XmlElement(ElementName="ECEFSatellitePosition")] - public string ECEFSatellitePosition { get; set; } + [XmlElement(ElementName = "ECEFSatellitePosition")] + public string ECEFSatellitePosition { get; set; } - [XmlElement(ElementName="ECEFSatelliteVelocity")] - public string ECEFSatelliteVelocity { get; set; } + [XmlElement(ElementName = "ECEFSatelliteVelocity")] + public string ECEFSatelliteVelocity { get; set; } - [XmlElement(ElementName="ECEFSatelliteAcceleration")] - public string ECEFSatelliteAcceleration { get; set; } + [XmlElement(ElementName = "ECEFSatelliteAcceleration")] + public string ECEFSatelliteAcceleration { get; set; } - [XmlElement(ElementName="NumberofStateVectors")] - public int NumberofStateVectors { get; set; } + [XmlElement(ElementName = "NumberofStateVectors")] + public int NumberofStateVectors { get; set; } - [XmlElement(ElementName="NumberofAttitudedata")] - public int NumberofAttitudedata { get; set; } + [XmlElement(ElementName = "NumberofAttitudedata")] + public int NumberofAttitudedata { get; set; } - [XmlElement(ElementName="OrbitDirection")] - public string OrbitDirection { get; set; } + [XmlElement(ElementName = "OrbitDirection")] + public string OrbitDirection { get; set; } - [XmlElement(ElementName="PitchAngle")] - public string PitchAngle { get; set; } + [XmlElement(ElementName = "PitchAngle")] + public string PitchAngle { get; set; } - [XmlElement(ElementName="PitchRate")] - public string PitchRate { get; set; } + [XmlElement(ElementName = "PitchRate")] + public string PitchRate { get; set; } - [XmlElement(ElementName="RollAngle")] - public string RollAngle { get; set; } + [XmlElement(ElementName = "RollAngle")] + public string RollAngle { get; set; } - [XmlElement(ElementName="RollRate")] - public string RollRate { get; set; } + [XmlElement(ElementName = "RollRate")] + public string RollRate { get; set; } - [XmlElement(ElementName="SatelliteHeight")] - public double SatelliteHeight { get; set; } + [XmlElement(ElementName = "SatelliteHeight")] + public double SatelliteHeight { get; set; } - [XmlElement(ElementName="StateVectorsTimes")] - public string StateVectorsTimes { get; set; } + [XmlElement(ElementName = "StateVectorsTimes")] + public string StateVectorsTimes { get; set; } - [XmlElement(ElementName="YawAngle")] - public string YawAngle { get; set; } + [XmlElement(ElementName = "YawAngle")] + public string YawAngle { get; set; } - [XmlElement(ElementName="YawRate")] - public string YawRate { get; set; } + [XmlElement(ElementName = "YawRate")] + public string YawRate { get; set; } - [XmlElement(ElementName="AzimuthPolynomialReferenceTime")] - public double AzimuthPolynomialReferenceTime { get; set; } + [XmlElement(ElementName = "AzimuthPolynomialReferenceTime")] + public double AzimuthPolynomialReferenceTime { get; set; } - [XmlElement(ElementName="CentroidvsAzimuthTimePolynomial")] - public string CentroidvsAzimuthTimePolynomial { get; set; } + [XmlElement(ElementName = "CentroidvsAzimuthTimePolynomial")] + public string CentroidvsAzimuthTimePolynomial { get; set; } - [XmlElement(ElementName="CentroidvsRangeTimePolynomial")] - public string CentroidvsRangeTimePolynomial { get; set; } + [XmlElement(ElementName = "CentroidvsRangeTimePolynomial")] + public string CentroidvsRangeTimePolynomial { get; set; } - [XmlElement(ElementName="DopplerAmbiguityEstimationMethod")] - public string DopplerAmbiguityEstimationMethod { get; set; } + [XmlElement(ElementName = "DopplerAmbiguityEstimationMethod")] + public string DopplerAmbiguityEstimationMethod { get; set; } - [XmlElement(ElementName="DopplerCentroidEstimationMethod")] - public string DopplerCentroidEstimationMethod { get; set; } + [XmlElement(ElementName = "DopplerCentroidEstimationMethod")] + public string DopplerCentroidEstimationMethod { get; set; } - [XmlElement(ElementName="DopplerRateEstimationMethod")] - public string DopplerRateEstimationMethod { get; set; } + [XmlElement(ElementName = "DopplerRateEstimationMethod")] + public string DopplerRateEstimationMethod { get; set; } - [XmlElement(ElementName="DopplerRatevsAzimuthTimePolynomial")] - public string DopplerRatevsAzimuthTimePolynomial { get; set; } + [XmlElement(ElementName = "DopplerRatevsAzimuthTimePolynomial")] + public string DopplerRatevsAzimuthTimePolynomial { get; set; } - [XmlElement(ElementName="DopplerRatevsRangeTimePolynomial")] - public string DopplerRatevsRangeTimePolynomial { get; set; } + [XmlElement(ElementName = "DopplerRatevsRangeTimePolynomial")] + public string DopplerRatevsRangeTimePolynomial { get; set; } - [XmlElement(ElementName="RangePolynomialReferenceTime")] - public double RangePolynomialReferenceTime { get; set; } + [XmlElement(ElementName = "RangePolynomialReferenceTime")] + public double RangePolynomialReferenceTime { get; set; } - [XmlElement(ElementName="AzimuthFocusingWeightingCoefficient")] - public double AzimuthFocusingWeightingCoefficient { get; set; } + [XmlElement(ElementName = "AzimuthFocusingWeightingCoefficient")] + public double AzimuthFocusingWeightingCoefficient { get; set; } - [XmlElement(ElementName="AzimuthFocusingWeightingFunction")] - public string AzimuthFocusingWeightingFunction { get; set; } + [XmlElement(ElementName = "AzimuthFocusingWeightingFunction")] + public string AzimuthFocusingWeightingFunction { get; set; } - [XmlElement(ElementName="AzimuthMultilookingWeightingCoefficient")] - public int AzimuthMultilookingWeightingCoefficient { get; set; } + [XmlElement(ElementName = "AzimuthMultilookingWeightingCoefficient")] + public int AzimuthMultilookingWeightingCoefficient { get; set; } - [XmlElement(ElementName="AzimuthMultilookingWeightingFunction")] - public string AzimuthMultilookingWeightingFunction { get; set; } + [XmlElement(ElementName = "AzimuthMultilookingWeightingFunction")] + public string AzimuthMultilookingWeightingFunction { get; set; } - [XmlElement(ElementName="AzimuthProcessingNumberofLooks")] - public int AzimuthProcessingNumberofLooks { get; set; } + [XmlElement(ElementName = "AzimuthProcessingNumberofLooks")] + public int AzimuthProcessingNumberofLooks { get; set; } - [XmlElement(ElementName="ECEFBeamCentreDirectionforProcessing")] - public string ECEFBeamCentreDirectionforProcessing { get; set; } + [XmlElement(ElementName = "ECEFBeamCentreDirectionforProcessing")] + public string ECEFBeamCentreDirectionforProcessing { get; set; } - [XmlElement(ElementName="FocusingAlgorithmID")] - public string FocusingAlgorithmID { get; set; } + [XmlElement(ElementName = "FocusingAlgorithmID")] + public string FocusingAlgorithmID { get; set; } - [XmlElement(ElementName="InvalidValue")] - public int InvalidValue { get; set; } + [XmlElement(ElementName = "InvalidValue")] + public int InvalidValue { get; set; } - [XmlElement(ElementName="L0SoftwareVersion")] - public string L0SoftwareVersion { get; set; } + [XmlElement(ElementName = "L0SoftwareVersion")] + public string L0SoftwareVersion { get; set; } - [XmlElement(ElementName="L1ASoftwareVersion")] - public string L1ASoftwareVersion { get; set; } + [XmlElement(ElementName = "L1ASoftwareVersion")] + public string L1ASoftwareVersion { get; set; } - [XmlElement(ElementName="L1BSoftwareVersion")] - public string L1BSoftwareVersion { get; set; } + [XmlElement(ElementName = "L1BSoftwareVersion")] + public string L1BSoftwareVersion { get; set; } - [XmlElement(ElementName="L1DSoftwareVersion")] - public string L1DSoftwareVersion { get; set; } + [XmlElement(ElementName = "L1DSoftwareVersion")] + public string L1DSoftwareVersion { get; set; } - [XmlElement(ElementName="LightSpeed")] - public int LightSpeed { get; set; } + [XmlElement(ElementName = "LightSpeed")] + public int LightSpeed { get; set; } - [XmlElement(ElementName="DespeckleTechnique")] - public string DespeckleTechnique { get; set; } + [XmlElement(ElementName = "DespeckleTechnique")] + public string DespeckleTechnique { get; set; } - [XmlElement(ElementName="DespeckleDirection")] - public string DespeckleDirection { get; set; } + [XmlElement(ElementName = "DespeckleDirection")] + public string DespeckleDirection { get; set; } - [XmlElement(ElementName="ProductErrorFlag")] - public int ProductErrorFlag { get; set; } + [XmlElement(ElementName = "ProductErrorFlag")] + public int ProductErrorFlag { get; set; } - [XmlElement(ElementName="ProductGenerationUTC")] - public string ProductGenerationUTC { get; set; } + [XmlElement(ElementName = "ProductGenerationUTC")] + public string ProductGenerationUTC { get; set; } - [XmlElement(ElementName="RangeFocusingWeightingCoefficient")] - public double RangeFocusingWeightingCoefficient { get; set; } + [XmlElement(ElementName = "RangeFocusingWeightingCoefficient")] + public double RangeFocusingWeightingCoefficient { get; set; } - [XmlElement(ElementName="RangeFocusingWeightingFunction")] - public string RangeFocusingWeightingFunction { get; set; } + [XmlElement(ElementName = "RangeFocusingWeightingFunction")] + public string RangeFocusingWeightingFunction { get; set; } - [XmlElement(ElementName="RangeMultilookingWeightingCoefficient")] - public double RangeMultilookingWeightingCoefficient { get; set; } + [XmlElement(ElementName = "RangeMultilookingWeightingCoefficient")] + public double RangeMultilookingWeightingCoefficient { get; set; } - [XmlElement(ElementName="RangeMultilookingWeightingFunction")] - public string RangeMultilookingWeightingFunction { get; set; } + [XmlElement(ElementName = "RangeMultilookingWeightingFunction")] + public string RangeMultilookingWeightingFunction { get; set; } - [XmlElement(ElementName="RangeProcessingNumberofLooks")] - public int RangeProcessingNumberofLooks { get; set; } + [XmlElement(ElementName = "RangeProcessingNumberofLooks")] + public int RangeProcessingNumberofLooks { get; set; } - [XmlElement(ElementName="ReferenceUTC")] - public string ReferenceUTC { get; set; } + [XmlElement(ElementName = "ReferenceUTC")] + public string ReferenceUTC { get; set; } - [XmlElement(ElementName="ReplicaReconstructionMethod")] - public string ReplicaReconstructionMethod { get; set; } + [XmlElement(ElementName = "ReplicaReconstructionMethod")] + public string ReplicaReconstructionMethod { get; set; } - [XmlElement(ElementName="RescalingFactor")] - public double RescalingFactor { get; set; } + [XmlElement(ElementName = "RescalingFactor")] + public double RescalingFactor { get; set; } - [XmlElement(ElementName="DespeckleFilterMovingWindow")] - public int DespeckleFilterMovingWindow { get; set; } + [XmlElement(ElementName = "DespeckleFilterMovingWindow")] + public int DespeckleFilterMovingWindow { get; set; } - [XmlElement(ElementName="DespeckleFilter")] - public string DespeckleFilter { get; set; } + [XmlElement(ElementName = "DespeckleFilter")] + public string DespeckleFilter { get; set; } - [XmlElement(ElementName="DatumRotation")] - public string DatumRotation { get; set; } + [XmlElement(ElementName = "DatumRotation")] + public string DatumRotation { get; set; } - [XmlElement(ElementName="DatumScale")] - public int DatumScale { get; set; } + [XmlElement(ElementName = "DatumScale")] + public int DatumScale { get; set; } - [XmlElement(ElementName="DatumShift")] - public string DatumShift { get; set; } + [XmlElement(ElementName = "DatumShift")] + public string DatumShift { get; set; } - [XmlElement(ElementName="EllipsoidDesignator")] - public string EllipsoidDesignator { get; set; } + [XmlElement(ElementName = "EllipsoidDesignator")] + public string EllipsoidDesignator { get; set; } - [XmlElement(ElementName="EllipsoidSemimajorAxis")] - public int EllipsoidSemimajorAxis { get; set; } + [XmlElement(ElementName = "EllipsoidSemimajorAxis")] + public int EllipsoidSemimajorAxis { get; set; } - [XmlElement(ElementName="EllipsoidSemiminorAxis")] - public int EllipsoidSemiminorAxis { get; set; } + [XmlElement(ElementName = "EllipsoidSemiminorAxis")] + public int EllipsoidSemiminorAxis { get; set; } - [XmlElement(ElementName="GroundProjectionReferenceSurface")] - public string GroundProjectionReferenceSurface { get; set; } + [XmlElement(ElementName = "GroundProjectionReferenceSurface")] + public string GroundProjectionReferenceSurface { get; set; } - [XmlElement(ElementName="MapProjectionCentre")] - public string MapProjectionCentre { get; set; } + [XmlElement(ElementName = "MapProjectionCentre")] + public string MapProjectionCentre { get; set; } - [XmlElement(ElementName="MapProjectionScaleFactor")] - public int MapProjectionScaleFactor { get; set; } + [XmlElement(ElementName = "MapProjectionScaleFactor")] + public int MapProjectionScaleFactor { get; set; } - [XmlElement(ElementName="MapProjectionZone")] - public int MapProjectionZone { get; set; } + [XmlElement(ElementName = "MapProjectionZone")] + public int MapProjectionZone { get; set; } - [XmlElement(ElementName="ProjectionID")] - public string ProjectionID { get; set; } + [XmlElement(ElementName = "ProjectionID")] + public string ProjectionID { get; set; } - [XmlElement(ElementName="AzimuthCoverage")] - public double AzimuthCoverage { get; set; } + [XmlElement(ElementName = "AzimuthCoverage")] + public double AzimuthCoverage { get; set; } - [XmlElement(ElementName="CentreEarthRadius")] - public double CentreEarthRadius { get; set; } + [XmlElement(ElementName = "CentreEarthRadius")] + public double CentreEarthRadius { get; set; } - [XmlElement(ElementName="GroundRangeCoverage")] - public double GroundRangeCoverage { get; set; } + [XmlElement(ElementName = "GroundRangeCoverage")] + public double GroundRangeCoverage { get; set; } - [XmlElement(ElementName="SceneCentreGeodeticCoordinates")] - public string SceneCentreGeodeticCoordinates { get; set; } + [XmlElement(ElementName = "SceneCentreGeodeticCoordinates")] + public string SceneCentreGeodeticCoordinates { get; set; } - [XmlElement(ElementName="SceneOrientation")] - public int SceneOrientation { get; set; } + [XmlElement(ElementName = "SceneOrientation")] + public int SceneOrientation { get; set; } - [XmlElement(ElementName="TerrainElevationStandardDeviation")] - public string TerrainElevationStandardDeviation { get; set; } + [XmlElement(ElementName = "TerrainElevationStandardDeviation")] + public string TerrainElevationStandardDeviation { get; set; } - [XmlElement(ElementName="TerrainMaximumElevation")] - public int TerrainMaximumElevation { get; set; } + [XmlElement(ElementName = "TerrainMaximumElevation")] + public int TerrainMaximumElevation { get; set; } - [XmlElement(ElementName="TerrainMeanElevation")] - public string TerrainMeanElevation { get; set; } + [XmlElement(ElementName = "TerrainMeanElevation")] + public string TerrainMeanElevation { get; set; } - [XmlElement(ElementName="TerrainMinimumElevation")] - public int TerrainMinimumElevation { get; set; } + [XmlElement(ElementName = "TerrainMinimumElevation")] + public int TerrainMinimumElevation { get; set; } - [XmlElement(ElementName="ADCCharacterization")] - public string ADCCharacterization { get; set; } + [XmlElement(ElementName = "ADCCharacterization")] + public string ADCCharacterization { get; set; } - [XmlElement(ElementName="ADCCompensation")] - public int ADCCompensation { get; set; } + [XmlElement(ElementName = "ADCCompensation")] + public int ADCCompensation { get; set; } - [XmlElement(ElementName="AntennaPatternCompensationReferenceSurface")] - public string AntennaPatternCompensationReferenceSurface { get; set; } + [XmlElement(ElementName = "AntennaPatternCompensationReferenceSurface")] + public string AntennaPatternCompensationReferenceSurface { get; set; } - [XmlElement(ElementName="AzimuthAntennaPatternCompensationGeometry")] - public string AzimuthAntennaPatternCompensationGeometry { get; set; } + [XmlElement(ElementName = "AzimuthAntennaPatternCompensationGeometry")] + public string AzimuthAntennaPatternCompensationGeometry { get; set; } - [XmlElement(ElementName="CalibrationConstantCompensationFlag")] - public int CalibrationConstantCompensationFlag { get; set; } + [XmlElement(ElementName = "CalibrationConstantCompensationFlag")] + public int CalibrationConstantCompensationFlag { get; set; } - [XmlElement(ElementName="IncidenceAngleCompensationGeometry")] - public string IncidenceAngleCompensationGeometry { get; set; } + [XmlElement(ElementName = "IncidenceAngleCompensationGeometry")] + public string IncidenceAngleCompensationGeometry { get; set; } - [XmlElement(ElementName="IncidenceAngleCompensationReferenceSurface")] - public string IncidenceAngleCompensationReferenceSurface { get; set; } + [XmlElement(ElementName = "IncidenceAngleCompensationReferenceSurface")] + public string IncidenceAngleCompensationReferenceSurface { get; set; } - [XmlElement(ElementName="RangeAntennaPatternCompensationGeometry")] - public string RangeAntennaPatternCompensationGeometry { get; set; } + [XmlElement(ElementName = "RangeAntennaPatternCompensationGeometry")] + public string RangeAntennaPatternCompensationGeometry { get; set; } - [XmlElement(ElementName="RangeSpreadingLossCompensationGeometry")] - public string RangeSpreadingLossCompensationGeometry { get; set; } + [XmlElement(ElementName = "RangeSpreadingLossCompensationGeometry")] + public string RangeSpreadingLossCompensationGeometry { get; set; } - [XmlElement(ElementName="ReferenceIncidenceAngle")] - public int ReferenceIncidenceAngle { get; set; } + [XmlElement(ElementName = "ReferenceIncidenceAngle")] + public int ReferenceIncidenceAngle { get; set; } - [XmlElement(ElementName="ReferenceSlantRange")] - public int ReferenceSlantRange { get; set; } + [XmlElement(ElementName = "ReferenceSlantRange")] + public int ReferenceSlantRange { get; set; } - [XmlElement(ElementName="ReferenceSlantRangeExponent")] - public double ReferenceSlantRangeExponent { get; set; } + [XmlElement(ElementName = "ReferenceSlantRangeExponent")] + public double ReferenceSlantRangeExponent { get; set; } - [XmlElement(ElementName="DopplerAmbiguityConfidenceMeasureThreshold")] - public double DopplerAmbiguityConfidenceMeasureThreshold { get; set; } + [XmlElement(ElementName = "DopplerAmbiguityConfidenceMeasureThreshold")] + public double DopplerAmbiguityConfidenceMeasureThreshold { get; set; } - [XmlElement(ElementName="DopplerAmbiguityThreshold")] - public int DopplerAmbiguityThreshold { get; set; } + [XmlElement(ElementName = "DopplerAmbiguityThreshold")] + public int DopplerAmbiguityThreshold { get; set; } - [XmlElement(ElementName="DopplerCentroidConfidenceMeasureThreshold")] - public double DopplerCentroidConfidenceMeasureThreshold { get; set; } + [XmlElement(ElementName = "DopplerCentroidConfidenceMeasureThreshold")] + public double DopplerCentroidConfidenceMeasureThreshold { get; set; } - [XmlElement(ElementName="DopplerCentroidEstimationAccuracyThreshold")] - public int DopplerCentroidEstimationAccuracyThreshold { get; set; } + [XmlElement(ElementName = "DopplerCentroidEstimationAccuracyThreshold")] + public int DopplerCentroidEstimationAccuracyThreshold { get; set; } - [XmlElement(ElementName="DopplerRateConfidenceMeasureThreshold")] - public double DopplerRateConfidenceMeasureThreshold { get; set; } + [XmlElement(ElementName = "DopplerRateConfidenceMeasureThreshold")] + public double DopplerRateConfidenceMeasureThreshold { get; set; } - [XmlElement(ElementName="DopplerRateEstimationAccuracyThreshold")] - public double DopplerRateEstimationAccuracyThreshold { get; set; } + [XmlElement(ElementName = "DopplerRateEstimationAccuracyThreshold")] + public double DopplerRateEstimationAccuracyThreshold { get; set; } - [XmlElement(ElementName="ImageOverSaturatedPercentageThreshold")] - public int ImageOverSaturatedPercentageThreshold { get; set; } + [XmlElement(ElementName = "ImageOverSaturatedPercentageThreshold")] + public int ImageOverSaturatedPercentageThreshold { get; set; } - [XmlElement(ElementName="ImageUnderSaturatedPercentageThreshold")] - public int ImageUnderSaturatedPercentageThreshold { get; set; } + [XmlElement(ElementName = "ImageUnderSaturatedPercentageThreshold")] + public int ImageUnderSaturatedPercentageThreshold { get; set; } - [XmlElement(ElementName="RAWBiasThreshold")] - public double RAWBiasThreshold { get; set; } + [XmlElement(ElementName = "RAWBiasThreshold")] + public double RAWBiasThreshold { get; set; } - [XmlElement(ElementName="RAWGainImbalanceThreshold")] - public double RAWGainImbalanceThreshold { get; set; } + [XmlElement(ElementName = "RAWGainImbalanceThreshold")] + public double RAWGainImbalanceThreshold { get; set; } - [XmlElement(ElementName="RAWIQNormalityThreshold")] - public double RAWIQNormalityThreshold { get; set; } + [XmlElement(ElementName = "RAWIQNormalityThreshold")] + public double RAWIQNormalityThreshold { get; set; } - [XmlElement(ElementName="RAWMissingLinesperBlockThreshold")] - public int RAWMissingLinesperBlockThreshold { get; set; } + [XmlElement(ElementName = "RAWMissingLinesperBlockThreshold")] + public int RAWMissingLinesperBlockThreshold { get; set; } - [XmlElement(ElementName="RAWMissingLinesPercentageThreshold")] - public double RAWMissingLinesPercentageThreshold { get; set; } + [XmlElement(ElementName = "RAWMissingLinesPercentageThreshold")] + public double RAWMissingLinesPercentageThreshold { get; set; } - [XmlElement(ElementName="RAWOverSaturatedPercentageThreshold")] - public double RAWOverSaturatedPercentageThreshold { get; set; } + [XmlElement(ElementName = "RAWOverSaturatedPercentageThreshold")] + public double RAWOverSaturatedPercentageThreshold { get; set; } - [XmlElement(ElementName="RAWPhaseUniformityThreshold")] - public double RAWPhaseUniformityThreshold { get; set; } + [XmlElement(ElementName = "RAWPhaseUniformityThreshold")] + public double RAWPhaseUniformityThreshold { get; set; } - [XmlElement(ElementName="RAWUnderSaturatedPercentageThreshold")] - public double RAWUnderSaturatedPercentageThreshold { get; set; } + [XmlElement(ElementName = "RAWUnderSaturatedPercentageThreshold")] + public double RAWUnderSaturatedPercentageThreshold { get; set; } - [XmlElement(ElementName="AttitudeProductCategory")] - public string AttitudeProductCategory { get; set; } + [XmlElement(ElementName = "AttitudeProductCategory")] + public string AttitudeProductCategory { get; set; } - [XmlElement(ElementName="DopplerAmbiguityConfidenceMeasure")] - public int DopplerAmbiguityConfidenceMeasure { get; set; } + [XmlElement(ElementName = "DopplerAmbiguityConfidenceMeasure")] + public int DopplerAmbiguityConfidenceMeasure { get; set; } - [XmlElement(ElementName="DopplerCentroidConfidenceMeasure")] - public double DopplerCentroidConfidenceMeasure { get; set; } + [XmlElement(ElementName = "DopplerCentroidConfidenceMeasure")] + public double DopplerCentroidConfidenceMeasure { get; set; } - [XmlElement(ElementName="DopplerCentroidEstimationAccuracy")] - public int DopplerCentroidEstimationAccuracy { get; set; } + [XmlElement(ElementName = "DopplerCentroidEstimationAccuracy")] + public int DopplerCentroidEstimationAccuracy { get; set; } - [XmlElement(ElementName="DopplerRateConfidenceMeasure")] - public double DopplerRateConfidenceMeasure { get; set; } + [XmlElement(ElementName = "DopplerRateConfidenceMeasure")] + public double DopplerRateConfidenceMeasure { get; set; } - [XmlElement(ElementName="DopplerRateEstimationAccuracy")] - public double DopplerRateEstimationAccuracy { get; set; } + [XmlElement(ElementName = "DopplerRateEstimationAccuracy")] + public double DopplerRateEstimationAccuracy { get; set; } - [XmlElement(ElementName="OrbitProductCategory")] - public string OrbitProductCategory { get; set; } + [XmlElement(ElementName = "OrbitProductCategory")] + public string OrbitProductCategory { get; set; } - [XmlElement(ElementName="SPFMeanIntensityRatio")] - public int SPFMeanIntensityRatio { get; set; } + [XmlElement(ElementName = "SPFMeanIntensityRatio")] + public int SPFMeanIntensityRatio { get; set; } - [XmlElement(ElementName="SPFStandardDeviationIntensityRatio")] - public int SPFStandardDeviationIntensityRatio { get; set; } + [XmlElement(ElementName = "SPFStandardDeviationIntensityRatio")] + public int SPFStandardDeviationIntensityRatio { get; set; } - [XmlElement(ElementName="SubSwaths")] - public SubSwaths SubSwaths { get; set; } + [XmlElement(ElementName = "SubSwaths")] + public SubSwaths SubSwaths { get; set; } - [XmlElement(ElementName="QLK")] - public QLK QLK { get; set; } + [XmlElement(ElementName = "QLK")] + public QLK QLK { get; set; } - [XmlElement(ElementName="MBI")] - public MBI MBI { get; set; } - } + [XmlElement(ElementName = "MBI")] + public MBI MBI { get; set; } + } - [XmlRoot(ElementName="Auxiliary")] - public class Auxiliary { + [XmlRoot(ElementName = "Auxiliary")] + public class Auxiliary + { - [XmlElement(ElementName="Root")] - public Root Root { get; set; } + [XmlElement(ElementName = "Root")] + public Root Root { get; set; } - [XmlAttribute(AttributeName="xsi")] - public string Xsi { get; set; } + [XmlAttribute(AttributeName = "xsi")] + public string Xsi { get; set; } - [XmlAttribute(AttributeName="xsd")] - public string Xsd { get; set; } + [XmlAttribute(AttributeName = "xsd")] + public string Xsd { get; set; } - [XmlAttribute(AttributeName="noNamespaceSchemaLocation")] - public string NoNamespaceSchemaLocation { get; set; } + [XmlAttribute(AttributeName = "noNamespaceSchemaLocation")] + public string NoNamespaceSchemaLocation { get; set; } - [XmlText] - public string Text { get; set; } - } + [XmlText] + public string Text { get; set; } + } - public class ACQUISITION_MODE + public class ACQUISITION_MODE { public const string HIGH_RESOLUTION = "HIGH RESOLUTION"; - public const string ENHANCED_HIGH_RESOLUTION = "ENHANCED HIGH RESOLUTION"; - public const string ULTRA_HIGH_RESOLUTION = "ULTRA HIGH RESOLUTION"; - public const string STANDARD = "STANDARD"; - public const string ENHANCED_STANDARD = "ENHANCED STANDARD"; - public const string WIDE_SWATH = "WIDE SWATH"; - public const string ENHANCED_WIDE_SWATH = "ENHANCED WIDE SWATH"; + public const string ENHANCED_HIGH_RESOLUTION = "ENHANCED HIGH RESOLUTION"; + public const string ULTRA_HIGH_RESOLUTION = "ULTRA HIGH RESOLUTION"; + public const string STANDARD = "STANDARD"; + public const string ENHANCED_STANDARD = "ENHANCED STANDARD"; + public const string WIDE_SWATH = "WIDE SWATH"; + public const string ENHANCED_WIDE_SWATH = "ENHANCED WIDE SWATH"; } - public class ORBIT_STATE - { - public const string ASCENDING = "ASCENDING"; + public class ORBIT_STATE + { + public const string ASCENDING = "ASCENDING"; public const string DESCENDING = "DESCENDING"; - } + } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Kompsat5/Kompsat5MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Kompsat5/Kompsat5MetadataExtractor.cs index 9006f278..3c4f0180 100644 --- a/src/Stars.Data/Model/Metadata/Kompsat5/Kompsat5MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Kompsat5/Kompsat5MetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -16,12 +16,11 @@ using Stac.Extensions.Sar; using Stac.Extensions.Sat; using Stac.Extensions.View; -using Stac; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services.Plugins; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Kompsat5 { @@ -46,12 +45,8 @@ public Kompsat5MetadataExtraction(ILogger logger, IR protected override async Task ExtractMetadata(IItem item, string suffix) { logger.LogDebug("Retrieving the metadata file in the product package"); - IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(Aux\\.xml)$"); - if (auxFile == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } - logger.LogDebug(String.Format("Metadata file is {0}", auxFile.Uri)); + IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(Aux\\.xml)$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); + logger.LogDebug(string.Format("Metadata file is {0}", auxFile.Uri)); IStreamResource auxFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(auxFile, System.Threading.CancellationToken.None); if (auxFileStreamable == null) @@ -95,7 +90,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi AddAssets(stacItem, auxiliary, item); - return StacItemNode.Create(stacItem, item.Uri);; + return StacItemNode.Create(stacItem, item.Uri); ; } @@ -162,7 +157,7 @@ private void AddOtherProperties(Auxiliary auxiliary, StacItem stacItem) { AddSingleProvider( stacItem.Properties, - "KARI", + "KARI", "KOMPSAT-5 has as primary mission objective the development, launch and operation of an Earth observation SAR (Synthetic Aperture Radar) satellite system to provide imagery for geographic information applications and to monitor environmental disasters.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.eoportal.org/satellite-missions/kompsat-5") @@ -471,7 +466,7 @@ private void FillDateTimeProperties(Auxiliary auxiliary, Dictionary properties) + private void FillBasicsProperties(Auxiliary auxiliary, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -537,8 +532,7 @@ public static async Task DeserializeAuxiliary(IStreamResource auxilia public override bool CanProcess(IResource route, IDestination destinations) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(Aux\\.xml)$"); try { @@ -560,4 +554,4 @@ public override bool CanProcess(IResource route, IDestination destinations) } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Landsat8/Auxiliary.cs b/src/Stars.Data/Model/Metadata/Landsat8/Auxiliary.cs index 921d5035..35acd545 100644 --- a/src/Stars.Data/Model/Metadata/Landsat8/Auxiliary.cs +++ b/src/Stars.Data/Model/Metadata/Landsat8/Auxiliary.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Humanizer; @@ -66,12 +66,12 @@ public double GSD public readonly double OffNadirAngle = 0; internal string ProductId => GetProperty("LANDSAT_PRODUCT_ID") ?? GetProperty("METADATA_FILE_NAME").Replace("_MTL.txt", ""); - public int Panchromatic_Lines => int.Parse(GetProperty("PANCHROMATIC_LINES")); - public int Panchromatic_Samples => int.Parse(GetProperty("PANCHROMATIC_SAMPLES")); - public int Reflective_Lines => int.Parse(GetProperty("REFLECTIVE_LINES")); - public int Reflective_Samples => int.Parse(GetProperty("REFLECTIVE_SAMPLES")); - public int Thermal_Lines => int.Parse(GetProperty("THERMAL_LINES")); - public int Thermal_Samples => int.Parse(GetProperty("THERMAL_SAMPLES")); + public int Panchromatic_Lines => int.Parse(GetProperty("PANCHROMATIC_LINES")); + public int Panchromatic_Samples => int.Parse(GetProperty("PANCHROMATIC_SAMPLES")); + public int Reflective_Lines => int.Parse(GetProperty("REFLECTIVE_LINES")); + public int Reflective_Samples => int.Parse(GetProperty("REFLECTIVE_SAMPLES")); + public int Thermal_Lines => int.Parse(GetProperty("THERMAL_LINES")); + public int Thermal_Samples => int.Parse(GetProperty("THERMAL_SAMPLES")); public string CollectionCategory => GetProperty("COLLECTION_CATEGORY"); @@ -150,4 +150,4 @@ public double CloudCoverLand } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Landsat8/AuxiliarySpatialResolution.cs b/src/Stars.Data/Model/Metadata/Landsat8/AuxiliarySpatialResolution.cs index 87d8fe30..83c638e3 100644 --- a/src/Stars.Data/Model/Metadata/Landsat8/AuxiliarySpatialResolution.cs +++ b/src/Stars.Data/Model/Metadata/Landsat8/AuxiliarySpatialResolution.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Humanizer; -using Kajabity.Tools.Java; +using Kajabity.Tools.Java; namespace Terradue.Stars.Data.Model.Metadata.Landsat8 { @@ -14,7 +10,7 @@ public class AuxiliarySpatialResolution : JavaProperties if (!string.IsNullOrEmpty(r)) r = r.Trim('"'); return r; } - + // Band public string PixelSize_Band1 => GetProperty("BAND01_PIXEL_SIZE"); public string PixelSize_Band2 => GetProperty("BAND02_PIXEL_SIZE"); @@ -28,10 +24,11 @@ public class AuxiliarySpatialResolution : JavaProperties public string PixelSize_Band10 => GetProperty("BAND10_PIXEL_SIZE"); public string PixelSize_Band11 => GetProperty("BAND11_PIXEL_SIZE"); - public double GetPixelSizeFromBand(string band) { + public double GetPixelSizeFromBand(string band) + { return double.Parse(GetProperty($"BAND{$"{band.PadLeft(2, '0')}"}_PIXEL_SIZE")); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Landsat8/Landsat8MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Landsat8/Landsat8MetadataExtractor.cs index 5fc76d7d..0084595d 100644 --- a/src/Stars.Data/Model/Metadata/Landsat8/Landsat8MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Landsat8/Landsat8MetadataExtractor.cs @@ -1,12 +1,9 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using System.Threading.Tasks; -using System.Xml; -using System.Xml.Serialization; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using ProjNet.CoordinateSystems; @@ -15,14 +12,13 @@ using Stac.Extensions.Processing; using Stac.Extensions.Projection; using Stac.Extensions.Raster; -using Stac.Extensions.Sar; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services.Plugins; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Landsat8 { @@ -43,29 +39,27 @@ public Landsat8MetadataExtraction(ILogger logger, IR protected override async Task ExtractMetadata(IItem item, string suffix) { logger.LogDebug("Retrieving the metadata file in the product package"); - IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(_MTL\\.txt)$"); - if (auxFile == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } - logger.LogDebug(String.Format("Metadata file is {0}", auxFile.Uri)); - + IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(_MTL\\.txt)$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); + logger.LogDebug(string.Format("Metadata file is {0}", auxFile.Uri)); + IStreamResource auxFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(auxFile, System.Threading.CancellationToken.None); if (auxFileStreamable == null) { logger.LogError("metadata file asset is not streamable, skipping metadata extraction"); return null; } - - - + + + logger.LogDebug("Retrieving the metadata file in the product package"); AuxiliarySpatialResolution auxiliarySpatialResolution = null; IAsset auxSpatialResolutionFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(_ANG\\.txt)$"); - if (auxSpatialResolutionFile != null) { - logger.LogDebug(String.Format("ANG.txt file is {0}", auxSpatialResolutionFile.Uri)); + if (auxSpatialResolutionFile != null) + { + logger.LogDebug(string.Format("ANG.txt file is {0}", auxSpatialResolutionFile.Uri)); IStreamResource auxSpatialiResolutionFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(auxSpatialResolutionFile, System.Threading.CancellationToken.None); - if (auxSpatialiResolutionFileStreamable == null) { + if (auxSpatialiResolutionFileStreamable == null) + { logger.LogError("metadata file asset is not streamable, skipping metadata extraction"); return null; } @@ -73,8 +67,8 @@ protected override async Task ExtractMetadata(IItem item, string suffi auxiliarySpatialResolution = await DeserializeAuxiliarySpatialResolution(auxSpatialiResolutionFileStreamable); logger.LogDebug("ANG file deserialized."); } - - + + logger.LogDebug("Deserializing metadata"); Auxiliary auxiliary = await DeserializeAuxiliary(auxFileStreamable); logger.LogDebug("Metadata file deserialized. Starting metadata generation"); @@ -162,10 +156,10 @@ private void AddbandAsset(StacItem stacItem, string assetKey, IAsset asset, EoBa var eo = stacItem.EoExtension(); stacAsset.ProjectionExtension().Shape = new int[2] { auxiliary.Reflective_Samples, auxiliary.Reflective_Lines }; - if ( assetKey == "B8" ) + if (assetKey == "B8") stacAsset.ProjectionExtension().Shape = new int[2] { auxiliary.Panchromatic_Samples, auxiliary.Panchromatic_Lines }; - if ( assetKey == "B10" || assetKey == "B11" ) + if (assetKey == "B10" || assetKey == "B11") stacAsset.ProjectionExtension().Shape = new int[2] { auxiliary.Thermal_Samples, auxiliary.Thermal_Lines }; EoBandObject eoBandObject = new EoBandObject(assetKey, common_name); @@ -174,20 +168,25 @@ private void AddbandAsset(StacItem stacItem, string assetKey, IAsset asset, EoBa stacAsset.SetProperty("gsd", gsd); stacAsset.EoExtension().Bands = new EoBandObject[1] { eoBandObject }; - + // adding raster band RasterBand rasterBand = new RasterBand(); - if (auxiliarySpatialResolution != null) { + if (auxiliarySpatialResolution != null) + { rasterBand.SpatialResolution = auxiliarySpatialResolution.GetPixelSizeFromBand(assetKey.Remove(0, 1)); - } else if ( assetKey == "B8" ) { + } + else if (assetKey == "B8") + { rasterBand.SpatialResolution = 30.0; - } else { + } + else + { rasterBand.SpatialResolution = 15.0; } if (JObject.FromObject(rasterBand).Children().Any()) stacAsset.RasterExtension().Bands = new RasterBand[1] { rasterBand }; - + stacItem.Assets.Add(assetKey, stacAsset); } @@ -208,7 +207,7 @@ private void AddOtherProperties(Auxiliary auxiliary, StacItem stacItem) { AddSingleProvider( stacItem.Properties, - "USGS/NASA", + "USGS/NASA", "Landsat 8, a collaboration between NASA and the U.S. Geological Survey, provides moderate-resolution (15 m–100 m, depending on spectral frequency) measurements of the Earth’s terrestrial and polar regions in the visible, near-infrared, short wave infrared, and thermal infrared.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.usgs.gov/landsat-missions/landsat-8") @@ -384,11 +383,10 @@ public static async Task DeserializeAuxiliarySpatial } return auxiliary; } - + public override bool CanProcess(IResource route, IDestination destinations) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(MTL\\.txt)$"); if (auxFile == null) { @@ -411,4 +409,4 @@ public override bool CanProcess(IResource route, IDestination destinations) } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Landsat9/Auxiliary.cs b/src/Stars.Data/Model/Metadata/Landsat9/Auxiliary.cs index cae857d1..5314b646 100644 --- a/src/Stars.Data/Model/Metadata/Landsat9/Auxiliary.cs +++ b/src/Stars.Data/Model/Metadata/Landsat9/Auxiliary.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Humanizer; @@ -66,12 +66,12 @@ public double GSD public readonly double OffNadirAngle = 0; internal string ProductId => GetProperty("LANDSAT_PRODUCT_ID") ?? GetProperty("METADATA_FILE_NAME").Replace("_MTL.txt", ""); - public int Panchromatic_Lines => int.Parse(GetProperty("PANCHROMATIC_LINES")); - public int Panchromatic_Samples => int.Parse(GetProperty("PANCHROMATIC_SAMPLES")); - public int Reflective_Lines => int.Parse(GetProperty("REFLECTIVE_LINES")); - public int Reflective_Samples => int.Parse(GetProperty("REFLECTIVE_SAMPLES")); - public int Thermal_Lines => int.Parse(GetProperty("THERMAL_LINES")); - public int Thermal_Samples => int.Parse(GetProperty("THERMAL_SAMPLES")); + public int Panchromatic_Lines => int.Parse(GetProperty("PANCHROMATIC_LINES")); + public int Panchromatic_Samples => int.Parse(GetProperty("PANCHROMATIC_SAMPLES")); + public int Reflective_Lines => int.Parse(GetProperty("REFLECTIVE_LINES")); + public int Reflective_Samples => int.Parse(GetProperty("REFLECTIVE_SAMPLES")); + public int Thermal_Lines => int.Parse(GetProperty("THERMAL_LINES")); + public int Thermal_Samples => int.Parse(GetProperty("THERMAL_SAMPLES")); public string CollectionCategory => GetProperty("COLLECTION_CATEGORY"); @@ -150,4 +150,4 @@ public double CloudCoverLand } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Landsat9/AuxiliarySpatialResolution.cs b/src/Stars.Data/Model/Metadata/Landsat9/AuxiliarySpatialResolution.cs index 8ebbb78e..f1323e91 100644 --- a/src/Stars.Data/Model/Metadata/Landsat9/AuxiliarySpatialResolution.cs +++ b/src/Stars.Data/Model/Metadata/Landsat9/AuxiliarySpatialResolution.cs @@ -1,18 +1,16 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Humanizer; -using Kajabity.Tools.Java; +using Kajabity.Tools.Java; namespace Terradue.Stars.Data.Model.Metadata.Landsat9 { - public class AuxiliarySpatialResolution : JavaProperties { - public new string GetProperty(string key) { + public class AuxiliarySpatialResolution : JavaProperties + { + public new string GetProperty(string key) + { var r = base.GetProperty(key); if (!string.IsNullOrEmpty(r)) r = r.Trim('"'); return r; } - + // band spatial resolution public string PixelSize_Band1 => GetProperty("BAND01_PIXEL_SIZE"); public string PixelSize_Band2 => GetProperty("BAND02_PIXEL_SIZE"); @@ -26,25 +24,33 @@ public class AuxiliarySpatialResolution : JavaProperties { public string PixelSize_Band10 => GetProperty("BAND10_PIXEL_SIZE"); public string PixelSize_Band11 => GetProperty("BAND11_PIXEL_SIZE"); - public double GetPixelSizeFromBand(string band) { + public double GetPixelSizeFromBand(string band) + { double pixelSizeBand; - try { + try + { pixelSizeBand = double.Parse(GetProperty($"BAND{$"{band.PadLeft(2, '0')}"}_PIXEL_SIZE")); } - catch { + catch + { // L1T product - if (band == "8") { - pixelSizeBand = double.Parse(GetProperty("GRID_CELL_SIZE_PANCHROMATIC")); - } else if (band == "10" || band == "11") { + if (band == "8") + { + pixelSizeBand = double.Parse(GetProperty("GRID_CELL_SIZE_PANCHROMATIC")); + } + else if (band == "10" || band == "11") + { pixelSizeBand = double.Parse(GetProperty("GRID_CELL_SIZE_THERMAL")); - } else { + } + else + { pixelSizeBand = double.Parse(GetProperty("GRID_CELL_SIZE_REFLECTIVE")); } - + } return pixelSizeBand; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Landsat9/Landsat9MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Landsat9/Landsat9MetadataExtractor.cs index 8aff53ab..1616a0bb 100644 --- a/src/Stars.Data/Model/Metadata/Landsat9/Landsat9MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Landsat9/Landsat9MetadataExtractor.cs @@ -1,12 +1,9 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using System.Threading.Tasks; -using System.Xml; -using System.Xml.Serialization; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using ProjNet.CoordinateSystems; @@ -15,14 +12,13 @@ using Stac.Extensions.Processing; using Stac.Extensions.Projection; using Stac.Extensions.Raster; -using Stac.Extensions.Sar; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services.Plugins; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Landsat9 { @@ -43,13 +39,9 @@ public Landsat9MetadataExtraction(ILogger logger, IR protected override async Task ExtractMetadata(IItem item, string suffix) { logger.LogDebug("Retrieving the metadata file in the product package"); - IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(_MTL\\.txt)$"); - if (auxFile == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } - logger.LogDebug(String.Format("Metadata file is {0}", auxFile.Uri)); - + IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(_MTL\\.txt)$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); + logger.LogDebug(string.Format("Metadata file is {0}", auxFile.Uri)); + IStreamResource auxFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(auxFile, System.Threading.CancellationToken.None); if (auxFileStreamable == null) { @@ -60,10 +52,12 @@ protected override async Task ExtractMetadata(IItem item, string suffi logger.LogDebug("Retrieving the metadata file in the product package"); AuxiliarySpatialResolution auxiliarySpatialResolution = null; IAsset auxSpatialResolutionFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(_ANG\\.txt)$"); - if (auxSpatialResolutionFile != null && auxSpatialResolutionFile.ContentLength != 0) { - logger.LogDebug(String.Format("ANG.txt file is {0}", auxSpatialResolutionFile.Uri)); + if (auxSpatialResolutionFile != null && auxSpatialResolutionFile.ContentLength != 0) + { + logger.LogDebug(string.Format("ANG.txt file is {0}", auxSpatialResolutionFile.Uri)); IStreamResource auxSpatialiResolutionFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(auxSpatialResolutionFile, System.Threading.CancellationToken.None); - if (auxSpatialiResolutionFileStreamable == null) { + if (auxSpatialiResolutionFileStreamable == null) + { logger.LogError("metadata file asset is not streamable, skipping metadata extraction"); return null; } @@ -71,13 +65,16 @@ protected override async Task ExtractMetadata(IItem item, string suffi auxiliarySpatialResolution = await DeserializeAuxiliarySpatialResolution(auxSpatialiResolutionFileStreamable); logger.LogDebug("ANG file deserialized."); } - else { + else + { // L1T products have an empty ANG.txt file, we will retrieve the spatial resolution from the MTL.txt file auxSpatialResolutionFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(_MTL\\.txt)$"); - if (auxSpatialResolutionFile != null) { - logger.LogDebug(String.Format(".txt file is {0}", auxSpatialResolutionFile.Uri)); + if (auxSpatialResolutionFile != null) + { + logger.LogDebug(string.Format(".txt file is {0}", auxSpatialResolutionFile.Uri)); IStreamResource auxSpatialiResolutionFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(auxSpatialResolutionFile, System.Threading.CancellationToken.None); - if (auxSpatialiResolutionFileStreamable == null) { + if (auxSpatialiResolutionFileStreamable == null) + { logger.LogError("metadata file asset is not streamable, skipping metadata extraction"); return null; } @@ -86,8 +83,8 @@ protected override async Task ExtractMetadata(IItem item, string suffi logger.LogDebug("file deserialized."); } } - - + + logger.LogDebug("Deserializing metadata"); Auxiliary auxiliary = await DeserializeAuxiliary(auxFileStreamable); @@ -176,10 +173,10 @@ private void AddbandAsset(StacItem stacItem, string assetKey, IAsset asset, EoBa var eo = stacItem.EoExtension(); stacAsset.ProjectionExtension().Shape = new int[2] { auxiliary.Reflective_Samples, auxiliary.Reflective_Lines }; - if ( assetKey == "B8" ) + if (assetKey == "B8") stacAsset.ProjectionExtension().Shape = new int[2] { auxiliary.Panchromatic_Samples, auxiliary.Panchromatic_Lines }; - if ( assetKey == "B10" || assetKey == "B11" ) + if (assetKey == "B10" || assetKey == "B11") stacAsset.ProjectionExtension().Shape = new int[2] { auxiliary.Thermal_Samples, auxiliary.Thermal_Lines }; EoBandObject eoBandObject = new EoBandObject(assetKey, common_name); @@ -188,20 +185,25 @@ private void AddbandAsset(StacItem stacItem, string assetKey, IAsset asset, EoBa stacAsset.SetProperty("gsd", gsd); stacAsset.EoExtension().Bands = new EoBandObject[1] { eoBandObject }; - + // adding raster band RasterBand rasterBand = new RasterBand(); - if (auxiliarySpatialResolution != null) { + if (auxiliarySpatialResolution != null) + { rasterBand.SpatialResolution = auxiliarySpatialResolution.GetPixelSizeFromBand(assetKey.Remove(0, 1)); - } else if ( assetKey == "B8" ) { + } + else if (assetKey == "B8") + { rasterBand.SpatialResolution = 15.0; - } else { + } + else + { rasterBand.SpatialResolution = 30.0; } if (JObject.FromObject(rasterBand).Children().Any()) stacAsset.RasterExtension().Bands = new RasterBand[1] { rasterBand }; - + stacItem.Assets.Add(assetKey, stacAsset); } @@ -222,7 +224,7 @@ private void AddOtherProperties(Auxiliary auxiliary, StacItem stacItem) { AddSingleProvider( stacItem.Properties, - "USGS/NASA", + "USGS/NASA", "Landsat 9 continues Landsat’s record of Earth’s land surface and largely replicates its predecessor Landsat 8.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.usgs.gov/landsat-missions/landsat-9") @@ -385,8 +387,8 @@ public static async Task DeserializeAuxiliary(IStreamResource auxilia } return auxiliary; } - - + + /// Deserialize Auxiliary from xml to class /// The instance linked to the metadata file. /// The deserialized metadata object. @@ -399,12 +401,11 @@ public static async Task DeserializeAuxiliarySpatial } return auxiliary; } - + public override bool CanProcess(IResource route, IDestination destinations) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(MTL\\.txt)$"); if (auxFile == null) { @@ -427,4 +428,4 @@ public override bool CanProcess(IResource route, IDestination destinations) } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/MetadataExtraction.cs b/src/Stars.Data/Model/Metadata/MetadataExtraction.cs index 4e1b2e0f..11217ece 100644 --- a/src/Stars.Data/Model/Metadata/MetadataExtraction.cs +++ b/src/Stars.Data/Model/Metadata/MetadataExtraction.cs @@ -1,22 +1,18 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; using System.Threading.Tasks; -using Terradue.Stars.Interface.Router; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; -using System.Text.RegularExpressions; -using Microsoft.Extensions.Configuration; -using Terradue.Stars.Interface.Processing; -using Terradue.Stars.Interface.Supplier.Destination; -using Terradue.Stars.Services.Supplier.Carrier; -using Terradue.Stars.Interface; -using Terradue.Stars.Services.Model.Stac; using Stac; using Stac.Extensions.Eo; using Stac.Extensions.Sar; -using System.Threading; +using Terradue.Stars.Interface; +using Terradue.Stars.Interface.Processing; +using Terradue.Stars.Interface.Supplier.Destination; +using Terradue.Stars.Services.Model.Stac; namespace Terradue.Stars.Data.Model.Metadata { @@ -30,7 +26,7 @@ public MetadataExtraction(ILogger logger, { this.logger = logger; this.resourceServiceProvider = resourceServiceProvider; - this.IncludeProviderProperty = true; + IncludeProviderProperty = true; } public int Priority { get; set; } @@ -51,8 +47,7 @@ public string GetRelativePath(IResource route, IDestination destination) public async Task ProcessAsync(IResource resource, IDestination destination, CancellationToken ct, string suffix = null) { - IItem item = resource as IItem; - if (item == null) return resource; + if (!(resource is IItem item)) return resource; return await ExtractMetadata(item, suffix); } @@ -98,7 +93,7 @@ protected IEnumerable FindAssetsFromFilePathRegex(IAssetsContainer asset return Regex.IsMatch(a.Uri.ToString(), pattern); }); } - + protected Dictionary FindAllAssetsFromFileNameRegex(IAssetsContainer assetsContainer, string pattern) { return assetsContainer.Assets.Where(a => @@ -123,12 +118,12 @@ public static string StylePlatform(string v) protected EoBandCommonName GetEoCommonName(string imageColor) { - EoBandCommonName eoBandCommonName = default(EoBandCommonName); - if ( Enum.TryParse(imageColor, true, out eoBandCommonName)) + if (Enum.TryParse(imageColor, true, out EoBandCommonName eoBandCommonName)) return eoBandCommonName; - - switch ( imageColor.ToLower()){ + + switch (imageColor.ToLower()) + { case "near infrared": return EoBandCommonName.nir; } @@ -139,7 +134,7 @@ protected EoBandCommonName GetEoCommonName(string imageColor) protected ObservationDirection? ParseObservationDirection(string lookDirection) { ObservationDirection observationDirection = ObservationDirection.Left; - if ( Enum.TryParse(lookDirection, out observationDirection) ) + if (Enum.TryParse(lookDirection, out observationDirection)) return observationDirection; if (lookDirection.ToLower().StartsWith("r")) @@ -159,4 +154,4 @@ protected void AddSingleProvider(IDictionary properties, string properties.Add("providers", new StacProvider[] { provider }); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/NewSat/NewSatMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/NewSat/NewSatMetadataExtractor.cs index b3611c5a..fba0694d 100644 --- a/src/Stars.Data/Model/Metadata/NewSat/NewSatMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/NewSat/NewSatMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.ObjectModel; using System.Globalization; using System.IO; @@ -15,87 +15,101 @@ using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -namespace Terradue.Stars.Data.Model.Metadata.NewSat { - public class NewSatMetadataExtractor : MetadataExtraction { +namespace Terradue.Stars.Data.Model.Metadata.NewSat +{ + public class NewSatMetadataExtractor : MetadataExtraction + { public override string Label => "NewSat (Satellogic) contellation product metadata extractor"; - public NewSatMetadataExtractor(ILogger logger, IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) { + public NewSatMetadataExtractor(ILogger logger, IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) + { } - public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + public override bool CanProcess(IResource route, IDestination destination) + { + if (!(route is IItem item)) return false; IAsset geojson = FindFirstAssetFromFileNameRegex(item, "^[0-9a-zA-Z_-]*(metadata_stac\\.geojson)$"); - if (geojson == null) { + if (geojson == null) + { return false; } IStreamResource geoJsonFileStreamable = resourceServiceProvider.GetStreamResourceAsync(geojson, System.Threading.CancellationToken.None).Result; - if (geoJsonFileStreamable == null) { + if (geoJsonFileStreamable == null) + { return false; } - try { - DeserializeProductMetadata(geoJsonFileStreamable,item).GetAwaiter().GetResult(); - } catch { + try + { + DeserializeProductMetadata(geoJsonFileStreamable, item).GetAwaiter().GetResult(); + } + catch + { return false; } return true; } - protected override async Task ExtractMetadata(IItem item, string suffix) { + protected override async Task ExtractMetadata(IItem item, string suffix) + { logger.LogDebug("Retrieving the geojson file in the product package"); - IAsset geojsonAsset = FindFirstAssetFromFileNameRegex(item, "^[0-9a-zA-Z_-]*(metadata_stac\\.geojson)$"); - if (geojsonAsset == null) { - throw new FileNotFoundException(String.Format("Unable to find the geojson file asset")); - } - logger.LogDebug(String.Format("geojson file is {0}", geojsonAsset.Uri)); + IAsset geojsonAsset = FindFirstAssetFromFileNameRegex(item, "^[0-9a-zA-Z_-]*(metadata_stac\\.geojson)$") ?? throw new FileNotFoundException(string.Format("Unable to find the geojson file asset")); + logger.LogDebug(string.Format("geojson file is {0}", geojsonAsset.Uri)); IStreamResource geoJsonFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(geojsonAsset, System.Threading.CancellationToken.None); - if (geoJsonFileStreamable == null) { + if (geoJsonFileStreamable == null) + { logger.LogError("geojson file asset is not streamable, skipping metadata extraction"); return null; } // deserialize existing geojson - StacItem stacItem = await DeserializeProductMetadata(geoJsonFileStreamable,item); - + StacItem stacItem = await DeserializeProductMetadata(geoJsonFileStreamable, item); + // modifies the URI of the original geojson // and changes the vrt assets to tif assets FixAssetPaths(stacItem, item); - + // Adds missing properties FillMissingProperties(stacItem); // Adds other properties (provider) AddOtherProperties(stacItem); - + // changes unit of measures in band properties UpdateBandsValues(stacItem); - + // add L3 visual tif asset - AddL3Assets(item,stacItem); - + AddL3Assets(item, stacItem); + return StacItemNode.Create(stacItem, item.Uri); } - private void FixAssetPaths(StacItem stacItem, IItem item) { - - foreach (var stacItemAsset in stacItem.Assets) { + private void FixAssetPaths(StacItem stacItem, IItem item) + { + + foreach (var stacItemAsset in stacItem.Assets) + { string filename = Path.GetFileName(stacItemAsset.Value.Uri.GetPath()); IAsset file; - if (filename.EndsWith(".vrt")) { - var filenameNoExtension = filename.Replace(".vrt",""); + if (filename.EndsWith(".vrt")) + { + var filenameNoExtension = filename.Replace(".vrt", ""); file = FindFirstAssetFromFileNameRegex(item, @".*" + filenameNoExtension + "_[0-9]\\.tif"); filename = Path.GetFileName(file.Uri.AbsolutePath); } - else { + else + { file = FindFirstAssetFromFileNameRegex(item, @".*" + filename); - if (file == null && stacItemAsset.Key == "preview") { + if (file == null && stacItemAsset.Key == "preview") + { file = FindFirstAssetFromFileNameRegex(item, @".*_preview.png"); } - else if (file == null && stacItemAsset.Key == "thumbnail") { + else if (file == null && stacItemAsset.Key == "thumbnail") + { file = FindFirstAssetFromFileNameRegex(item, @".*_thumbnail.png"); } - else if (file == null) { + else if (file == null) + { throw new FileNotFoundException("Unable to find " + stacItemAsset.Value.Uri); } } @@ -106,11 +120,13 @@ private void FixAssetPaths(StacItem stacItem, IItem item) { private static async Task DeserializeProductMetadata(IStreamResource geoJsonFileStreamable, - IItem item ) { + IItem item) + { StacItem stacItem; - using (var stream = new StreamReader(geoJsonFileStreamable.Uri.AbsolutePath, Encoding.UTF8, true)) { + using (var stream = new StreamReader(geoJsonFileStreamable.Uri.AbsolutePath, Encoding.UTF8, true)) + { var json = await stream.ReadToEndAsync(); - + // before deserializing we modify the instruments type from string to array of strings dynamic featureCollection = JsonConvert.DeserializeObject(json); @@ -122,10 +138,10 @@ private static async Task DeserializeProductMetadata(IStreamResource g featureCollection.features[0].properties.instruments = new JArray() as dynamic; featureCollection.features[0].properties.instruments.Add(instruments.ToLower()); } - + // retrieving first statItem of the collection string featureJson = featureCollection.features[0].ToString(); - + // deserializing stacItem stacItem = StacConvert.Deserialize(featureJson); } @@ -133,20 +149,23 @@ private static async Task DeserializeProductMetadata(IStreamResource g return stacItem; } - private void FillMissingProperties(StacItem stacItem) { + private void FillMissingProperties(StacItem stacItem) + { RemoveUnusedProperties(stacItem); FillProcessingLevelProperty(stacItem); FillTitleProperty(stacItem); FillGsdProperty(stacItem); FillMissionProperty(stacItem); } - - private void RemoveUnusedProperties(StacItem stacItem) { + + private void RemoveUnusedProperties(StacItem stacItem) + { stacItem.Properties.Remove("license"); stacItem.Properties.Remove("created"); } - - private void FillTitleProperty(StacItem stacItem) { + + private void FillTitleProperty(StacItem stacItem) + { CultureInfo culture = CultureInfo.InvariantCulture; var properties = stacItem.Properties; // title @@ -158,34 +177,42 @@ private void FillTitleProperty(StacItem stacItem) { properties.GetProperty("processing:level").ToUpper(), properties.GetProperty("datetime").ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", culture))); } - - - private void FillProcessingLevelProperty(StacItem stacItem) { + + + private void FillProcessingLevelProperty(StacItem stacItem) + { string itemId = stacItem.Id; string processingLevel = itemId.Split('_')[3].ToLower(); - stacItem.Properties.Add("processing:level",processingLevel); + stacItem.Properties.Add("processing:level", processingLevel); } - - - private void FillGsdProperty(StacItem stacItem) { + + + private void FillGsdProperty(StacItem stacItem) + { string itemId = stacItem.Id; string resolution = itemId.Split('_')[4].ToLower(); - if (resolution.Equals("sr")) { + if (resolution.Equals("sr")) + { stacItem.Gsd = 0.7; - } else { + } + else + { stacItem.Gsd = 1; } } - private void FillMissionProperty(StacItem stacItem) { + private void FillMissionProperty(StacItem stacItem) + { stacItem.Mission = stacItem.Platform; } - private void UpdateBandsValues(StacItem stacItem) { + private void UpdateBandsValues(StacItem stacItem) + { var bands = new Collection(); stacItem.Assets["analytic"].EoExtension().Bands.ToList().ForEach( - band => { + band => + { band.CenterWavelength /= 1000; band.FullWidthHalfMax /= 1000; bands.Add(band); @@ -195,33 +222,36 @@ private void UpdateBandsValues(StacItem stacItem) { stacItem.Assets["analytic"].Roles.Add("reflectance"); stacItem.Assets.Remove("quicklook"); } - + private void AddOtherProperties(StacItem stacItem) { if (IncludeProviderProperty && !stacItem.Properties.ContainsKey("providers")) { AddSingleProvider( stacItem.Properties, - "Satellogic", + "Satellogic", "Satellogic aims to provide real-time imaging of the entire planet on a daily basis.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://satellogic.com/technology/constellation/") ); } } - - private void AddL3Assets(IItem item,StacItem stacItem) { + + private void AddL3Assets(IItem item, StacItem stacItem) + { IAsset l3Tif = FindFirstAssetFromFileNameRegex(item, @".*L3.*\.tif"); var bands = new Collection(); stacItem.Assets["analytic"].EoExtension().Bands.ToList().ForEach( - band => { - if (!band.Name.Equals("band4")) { + band => + { + if (!band.Name.Equals("band4")) + { bands.Add(band); } }); - stacItem.Assets["visual"] = new StacAsset(stacItem,l3Tif.Uri);//stacItem.Assets["analytic"]; + stacItem.Assets["visual"] = new StacAsset(stacItem, l3Tif.Uri);//stacItem.Assets["analytic"]; stacItem.Assets["visual"].MediaType = new System.Net.Mime.ContentType("image/tiff"); stacItem.Assets["visual"].EoExtension().Bands = bands.ToArray(); stacItem.Assets["visual"].SetProperty("filename", Path.GetFileName(l3Tif.Uri.AbsolutePath)); @@ -230,4 +260,4 @@ private void AddL3Assets(IItem item,StacItem stacItem) { } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/PlanetScope/PlanetScopeMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/PlanetScope/PlanetScopeMetadataExtractor.cs index 3d185497..fc204ea5 100644 --- a/src/Stars.Data/Model/Metadata/PlanetScope/PlanetScopeMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/PlanetScope/PlanetScopeMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -16,34 +16,40 @@ using Stac.Extensions.Raster; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; -namespace Terradue.Stars.Data.Model.Metadata.PlanetScope { - public class PlanetScopeMetadataExtractor : MetadataExtraction { +namespace Terradue.Stars.Data.Model.Metadata.PlanetScope +{ + public class PlanetScopeMetadataExtractor : MetadataExtraction + { public override string Label => "Planet Imaging constellation product metadata extractor"; public PlanetScopeMetadataExtractor(ILogger logger, - IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) { + IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) + { } - public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; - try { + public override bool CanProcess(IResource route, IDestination destination) + { + if (!(route is IItem item)) return false; + try + { IAsset metadataAsset = GetMetadataAsset(item); PlanetScopeMetadata metadata = ReadMetadata(metadataAsset).GetAwaiter().GetResult(); return true; } - catch (Exception e) { + catch (Exception e) + { return false; } } - protected override async Task ExtractMetadata(IItem item, string suffix) { + protected override async Task ExtractMetadata(IItem item, string suffix) + { IAsset metadataAsset = GetMetadataAsset(item); PlanetScopeMetadata metadata = await ReadMetadata(metadataAsset); @@ -55,7 +61,8 @@ protected override async Task ExtractMetadata(IItem item, string suffi } - internal virtual StacItem CreateStacItem(PlanetScopeMetadata metadata, IItem item) { + internal virtual StacItem CreateStacItem(PlanetScopeMetadata metadata, IItem item) + { string identifier = FindFirstAssetFromFileNameRegex(item, @".*\.tif").Uri.ToString(); string filename = identifier.Substring(identifier.LastIndexOf('/') + 1).Split('.')[0]; @@ -70,7 +77,8 @@ internal virtual StacItem CreateStacItem(PlanetScopeMetadata metadata, IItem ite return stacItem; } - private void FillBasicsProperties(PlanetScopeMetadata metadata, IDictionary properties) { + private void FillBasicsProperties(PlanetScopeMetadata metadata, IDictionary properties) + { CultureInfo culture = new CultureInfo("fr-FR"); // title properties.Remove("title"); @@ -83,7 +91,8 @@ private void FillBasicsProperties(PlanetScopeMetadata metadata, IDictionary GetCommonMetadata(PlanetScopeMetadata metadata) { + private IDictionary GetCommonMetadata(PlanetScopeMetadata metadata) + { Dictionary properties = new Dictionary(); FillDateTimeProperties(metadata, properties); @@ -143,7 +156,8 @@ private IDictionary GetCommonMetadata(PlanetScopeMetadata metada } - private void FillDateTimeProperties(PlanetScopeMetadata metadata, Dictionary properties) { + private void FillDateTimeProperties(PlanetScopeMetadata metadata, Dictionary properties) + { properties.Remove("datetime"); properties.Remove("start_datetime"); properties.Remove("end_datetime"); @@ -163,7 +177,8 @@ private void FillDateTimeProperties(PlanetScopeMetadata metadata, Dictionary properties) { + private void FillPlatformDefinition(PlanetScopeMetadata metadata, Dictionary properties) + { properties.Remove("mission"); properties.Add("mission", metadata.nav @@ -192,62 +207,63 @@ private void FillPlatformDefinition(PlanetScopeMetadata metadata, Dictionary() / 1000; @@ -317,19 +340,21 @@ private void AddBandAsset(StacItem stacItem, PlanetScopeMetadata metadata, IAsse stacAsset.Properties.AddRange(asset.Properties); stacAsset.Roles.Add("dn"); List rasterbands = new List(); - while (bandSpecificMetadata.MoveNext()) { + while (bandSpecificMetadata.MoveNext()) + { // band Green I from sensor PSB.SD has to be skipped if (sensor == "PSB.SD" && numberOfBands == 7 && - bandSpecificMetadata.Current.SelectSingleNode("ps:bandNumber", metadata.nsmgr).Value == "3") { + bandSpecificMetadata.Current.SelectSingleNode("ps:bandNumber", metadata.nsmgr).Value == "3") + { bandSpecificMetadata.MoveNext(); } RasterBand rasterband = new RasterBand(); - rasterband.Scale = Double.Parse(bandSpecificMetadata.Current + rasterband.Scale = double.Parse(bandSpecificMetadata.Current .SelectSingleNode("ps:reflectanceCoefficient", metadata.nsmgr).Value); rasterband.Properties.Add("radiometric_scale", - Double.Parse(bandSpecificMetadata.Current + double.Parse(bandSpecificMetadata.Current .SelectSingleNode("ps:radiometricScaleFactor", metadata.nsmgr).Value)); rasterbands.Add(rasterband); } @@ -348,25 +373,30 @@ private void AddBandAsset(StacItem stacItem, PlanetScopeMetadata metadata, IAsse stacItem.Assets.Add("data", stacAsset); } - protected void AddAssets(StacItem stacItem, IItem item, PlanetScopeMetadata metadata) { + protected void AddAssets(StacItem stacItem, IItem item, PlanetScopeMetadata metadata) + { IAsset previewAsset = FindFirstAssetFromFileNameRegex(item, @".*PT.*\.jpg"); - if (previewAsset != null) { + if (previewAsset != null) + { if (stacItem.Assets.TryAdd("overview", StacAsset.CreateOverviewAsset(stacItem, previewAsset.Uri, - new ContentType(MimeTypes.GetMimeType(previewAsset.Uri.ToString()))))) { + new ContentType(MimeTypes.GetMimeType(previewAsset.Uri.ToString()))))) + { stacItem.Assets["overview"].Properties.AddRange(previewAsset.Properties); } } IAsset dataAsset = FindFirstAssetFromFileNameRegex(item, @".*\.tif"); - if (dataAsset != null) { + if (dataAsset != null) + { AddBandAsset(stacItem, metadata, dataAsset); } IAsset metadataAsset = GetMetadataAsset(item); - if (metadataAsset != null) { + if (metadataAsset != null) + { stacItem.Assets.Add("metadata", StacAsset.CreateMetadataAsset(stacItem, metadataAsset.Uri, new ContentType(MimeTypes.GetMimeType(metadataAsset.Uri.ToString())))); stacItem.Assets["metadata"].Properties.AddRange(metadataAsset.Properties); @@ -375,18 +405,15 @@ protected void AddAssets(StacItem stacItem, IItem item, PlanetScopeMetadata meta throw new FileNotFoundException(string.Format("PlanetScope metadata file not found ")); } - protected virtual IAsset GetMetadataAsset(IItem item) { - IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @".*Analytic(MS)?.*metadata.*\.xml"); - - if (manifestAsset == null) { - throw new FileNotFoundException(String.Format("Unable to find the summary file asset")); - } - + protected virtual IAsset GetMetadataAsset(IItem item) + { + IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @".*Analytic(MS)?.*metadata.*\.xml") ?? throw new FileNotFoundException(string.Format("Unable to find the summary file asset")); return manifestAsset; } - public virtual async Task ReadMetadata(IAsset manifestAsset) { + public virtual async Task ReadMetadata(IAsset manifestAsset) + { PlanetScopeMetadata metadata = new PlanetScopeMetadata(manifestAsset); await metadata.ReadMetadata(resourceServiceProvider); @@ -395,21 +422,26 @@ public virtual async Task ReadMetadata(IAsset manifestAsset } - public class PlanetScopeMetadata { + public class PlanetScopeMetadata + { private IAsset summaryAsset; public XmlNamespaceManager nsmgr { get; set; } public XPathNavigator nav { get; set; } - public PlanetScopeMetadata(IAsset summaryAsset) { + public PlanetScopeMetadata(IAsset summaryAsset) + { this.summaryAsset = summaryAsset; } - public async Task ReadMetadata(IResourceServiceProvider resourceServiceProvider) { + public async Task ReadMetadata(IResourceServiceProvider resourceServiceProvider) + { using (var stream = await resourceServiceProvider.GetAssetStreamAsync(summaryAsset, - System.Threading.CancellationToken.None)) { - using (XmlReader reader = XmlReader.Create(stream)) { + System.Threading.CancellationToken.None)) + { + using (XmlReader reader = XmlReader.Create(stream)) + { XPathDocument doc = new XPathDocument(reader); nav = doc.CreateNavigator(); nsmgr = new XmlNamespaceManager(nav.NameTable); @@ -426,4 +458,4 @@ await resourceServiceProvider.GetAssetStreamAsync(summaryAsset, } } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/RCM/Product.cs b/src/Stars.Data/Model/Metadata/RCM/Product.cs index d26e3a3b..99e7b4e9 100644 --- a/src/Stars.Data/Model/Metadata/RCM/Product.cs +++ b/src/Stars.Data/Model/Metadata/RCM/Product.cs @@ -1,1546 +1,1648 @@ -using System.Xml.Serialization; +using System; using System.Collections.Generic; -using System; +using System.Xml.Serialization; namespace Terradue.Stars.Data.Model.Metadata.Rcm { // using System.Xml.Serialization; -// XmlSerializer serializer = new XmlSerializer(typeof(Product)); -// using (StringReader reader = new StringReader(xml)) -// { -// var test = (Product)serializer.Deserialize(reader); -// } - -[XmlRoot(ElementName="securityAttributes", Namespace="rcmGsProductSchema")] -public class SecurityAttributes { + // XmlSerializer serializer = new XmlSerializer(typeof(Product)); + // using (StringReader reader = new StringReader(xml)) + // { + // var test = (Product)serializer.Deserialize(reader); + // } + + [XmlRoot(ElementName = "securityAttributes", Namespace = "rcmGsProductSchema")] + public class SecurityAttributes + { - [XmlElement(ElementName="securityClassification", Namespace="rcmGsProductSchema")] - public string SecurityClassification { get; set; } + [XmlElement(ElementName = "securityClassification", Namespace = "rcmGsProductSchema")] + public string SecurityClassification { get; set; } - [XmlElement(ElementName="specialHandlingRequired", Namespace="rcmGsProductSchema")] - public bool SpecialHandlingRequired { get; set; } + [XmlElement(ElementName = "specialHandlingRequired", Namespace = "rcmGsProductSchema")] + public bool SpecialHandlingRequired { get; set; } - [XmlElement(ElementName="specialHandlingInstructions", Namespace="rcmGsProductSchema")] - public string SpecialHandlingInstructions { get; set; } -} + [XmlElement(ElementName = "specialHandlingInstructions", Namespace = "rcmGsProductSchema")] + public string SpecialHandlingInstructions { get; set; } + } -[XmlRoot(ElementName="rank", Namespace="rcmGsProductSchema")] -public class Rank { + [XmlRoot(ElementName = "rank", Namespace = "rcmGsProductSchema")] + public class Rank + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlText] - public int Text { get; set; } -} + [XmlText] + public int Text { get; set; } + } -[XmlRoot(ElementName="settableGain", Namespace="rcmGsProductSchema")] -public class SettableGain { + [XmlRoot(ElementName = "settableGain", Namespace = "rcmGsProductSchema")] + public class SettableGain + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="radarCenterFrequency", Namespace="rcmGsProductSchema")] -public class RadarCenterFrequency { + [XmlRoot(ElementName = "radarCenterFrequency", Namespace = "rcmGsProductSchema")] + public class RadarCenterFrequency + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="pulseRepetitionFrequency", Namespace="rcmGsProductSchema")] -public class PulseRepetitionFrequency { + [XmlRoot(ElementName = "pulseRepetitionFrequency", Namespace = "rcmGsProductSchema")] + public class PulseRepetitionFrequency + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="prfInformation", Namespace="rcmGsProductSchema")] -public class PrfInformation { + [XmlRoot(ElementName = "prfInformation", Namespace = "rcmGsProductSchema")] + public class PrfInformation + { - [XmlElement(ElementName="rawLine", Namespace="rcmGsProductSchema")] - public int RawLine { get; set; } + [XmlElement(ElementName = "rawLine", Namespace = "rcmGsProductSchema")] + public int RawLine { get; set; } - [XmlElement(ElementName="pulseRepetitionFrequency", Namespace="rcmGsProductSchema")] - public PulseRepetitionFrequency PulseRepetitionFrequency { get; set; } + [XmlElement(ElementName = "pulseRepetitionFrequency", Namespace = "rcmGsProductSchema")] + public PulseRepetitionFrequency PulseRepetitionFrequency { get; set; } - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="pulseLength", Namespace="rcmGsProductSchema")] -public class PulseLength { + [XmlRoot(ElementName = "pulseLength", Namespace = "rcmGsProductSchema")] + public class PulseLength + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="pulseBandwidth", Namespace="rcmGsProductSchema")] -public class PulseBandwidth { + [XmlRoot(ElementName = "pulseBandwidth", Namespace = "rcmGsProductSchema")] + public class PulseBandwidth + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="samplingWindowStartTimeFirstRawLine", Namespace="rcmGsProductSchema")] -public class SamplingWindowStartTimeFirstRawLine { + [XmlRoot(ElementName = "samplingWindowStartTimeFirstRawLine", Namespace = "rcmGsProductSchema")] + public class SamplingWindowStartTimeFirstRawLine + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="samplingWindowStartTimeLastRawLine", Namespace="rcmGsProductSchema")] -public class SamplingWindowStartTimeLastRawLine { + [XmlRoot(ElementName = "samplingWindowStartTimeLastRawLine", Namespace = "rcmGsProductSchema")] + public class SamplingWindowStartTimeLastRawLine + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="numberOfSwstChanges", Namespace="rcmGsProductSchema")] -public class NumberOfSwstChanges { + [XmlRoot(ElementName = "numberOfSwstChanges", Namespace = "rcmGsProductSchema")] + public class NumberOfSwstChanges + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlText] - public int Text { get; set; } -} + [XmlText] + public int Text { get; set; } + } -[XmlRoot(ElementName="adcSamplingRate", Namespace="rcmGsProductSchema")] -public class AdcSamplingRate { + [XmlRoot(ElementName = "adcSamplingRate", Namespace = "rcmGsProductSchema")] + public class AdcSamplingRate + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="samplesPerEchoLine", Namespace="rcmGsProductSchema")] -public class SamplesPerEchoLine { + [XmlRoot(ElementName = "samplesPerEchoLine", Namespace = "rcmGsProductSchema")] + public class SamplesPerEchoLine + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlText] - public int Text { get; set; } -} + [XmlText] + public int Text { get; set; } + } -[XmlRoot(ElementName="radarParameters", Namespace="rcmGsProductSchema")] -public class RadarParameters { + [XmlRoot(ElementName = "radarParameters", Namespace = "rcmGsProductSchema")] + public class RadarParameters + { - [XmlElement(ElementName="acquisitionType", Namespace="rcmGsProductSchema")] - public string AcquisitionType { get; set; } + [XmlElement(ElementName = "acquisitionType", Namespace = "rcmGsProductSchema")] + public string AcquisitionType { get; set; } - [XmlElement(ElementName="beams", Namespace="rcmGsProductSchema")] - public string Beams { get; set; } + [XmlElement(ElementName = "beams", Namespace = "rcmGsProductSchema")] + public string Beams { get; set; } - [XmlElement(ElementName="polarizations", Namespace="rcmGsProductSchema")] - public string Polarizations { get; set; } + [XmlElement(ElementName = "polarizations", Namespace = "rcmGsProductSchema")] + public string Polarizations { get; set; } - [XmlElement(ElementName="pulses", Namespace="rcmGsProductSchema")] - public string Pulses { get; set; } + [XmlElement(ElementName = "pulses", Namespace = "rcmGsProductSchema")] + public string Pulses { get; set; } - [XmlElement(ElementName="rank", Namespace="rcmGsProductSchema")] - public Rank Rank { get; set; } + [XmlElement(ElementName = "rank", Namespace = "rcmGsProductSchema")] + public Rank Rank { get; set; } - [XmlElement(ElementName="settableGain", Namespace="rcmGsProductSchema")] - public List SettableGain { get; set; } + [XmlElement(ElementName = "settableGain", Namespace = "rcmGsProductSchema")] + public List SettableGain { get; set; } - [XmlElement(ElementName="radarCenterFrequency", Namespace="rcmGsProductSchema")] - public RadarCenterFrequency RadarCenterFrequency { get; set; } + [XmlElement(ElementName = "radarCenterFrequency", Namespace = "rcmGsProductSchema")] + public RadarCenterFrequency RadarCenterFrequency { get; set; } - [XmlElement(ElementName="prfInformation", Namespace="rcmGsProductSchema")] - public PrfInformation PrfInformation { get; set; } + [XmlElement(ElementName = "prfInformation", Namespace = "rcmGsProductSchema")] + public PrfInformation PrfInformation { get; set; } - [XmlElement(ElementName="pulseLength", Namespace="rcmGsProductSchema")] - public PulseLength PulseLength { get; set; } + [XmlElement(ElementName = "pulseLength", Namespace = "rcmGsProductSchema")] + public PulseLength PulseLength { get; set; } - [XmlElement(ElementName="pulseBandwidth", Namespace="rcmGsProductSchema")] - public PulseBandwidth PulseBandwidth { get; set; } + [XmlElement(ElementName = "pulseBandwidth", Namespace = "rcmGsProductSchema")] + public PulseBandwidth PulseBandwidth { get; set; } - [XmlElement(ElementName="samplingWindowStartTimeFirstRawLine", Namespace="rcmGsProductSchema")] - public List SamplingWindowStartTimeFirstRawLine { get; set; } + [XmlElement(ElementName = "samplingWindowStartTimeFirstRawLine", Namespace = "rcmGsProductSchema")] + public List SamplingWindowStartTimeFirstRawLine { get; set; } - [XmlElement(ElementName="samplingWindowStartTimeLastRawLine", Namespace="rcmGsProductSchema")] - public List SamplingWindowStartTimeLastRawLine { get; set; } + [XmlElement(ElementName = "samplingWindowStartTimeLastRawLine", Namespace = "rcmGsProductSchema")] + public List SamplingWindowStartTimeLastRawLine { get; set; } - [XmlElement(ElementName="numberOfSwstChanges", Namespace="rcmGsProductSchema")] - public List NumberOfSwstChanges { get; set; } + [XmlElement(ElementName = "numberOfSwstChanges", Namespace = "rcmGsProductSchema")] + public List NumberOfSwstChanges { get; set; } - [XmlElement(ElementName="antennaPointing", Namespace="rcmGsProductSchema")] - public string AntennaPointing { get; set; } + [XmlElement(ElementName = "antennaPointing", Namespace = "rcmGsProductSchema")] + public string AntennaPointing { get; set; } - [XmlElement(ElementName="adcSamplingRate", Namespace="rcmGsProductSchema")] - public AdcSamplingRate AdcSamplingRate { get; set; } + [XmlElement(ElementName = "adcSamplingRate", Namespace = "rcmGsProductSchema")] + public AdcSamplingRate AdcSamplingRate { get; set; } - [XmlElement(ElementName="zeroDopplerSteeringFlag", Namespace="rcmGsProductSchema")] - public string ZeroDopplerSteeringFlag { get; set; } + [XmlElement(ElementName = "zeroDopplerSteeringFlag", Namespace = "rcmGsProductSchema")] + public string ZeroDopplerSteeringFlag { get; set; } - [XmlElement(ElementName="satOrientationRefFrame", Namespace="rcmGsProductSchema")] - public string SatOrientationRefFrame { get; set; } + [XmlElement(ElementName = "satOrientationRefFrame", Namespace = "rcmGsProductSchema")] + public string SatOrientationRefFrame { get; set; } - [XmlElement(ElementName="rawBitsPerSample", Namespace="rcmGsProductSchema")] - public int RawBitsPerSample { get; set; } + [XmlElement(ElementName = "rawBitsPerSample", Namespace = "rcmGsProductSchema")] + public int RawBitsPerSample { get; set; } - [XmlElement(ElementName="samplesPerEchoLine", Namespace="rcmGsProductSchema")] - public SamplesPerEchoLine SamplesPerEchoLine { get; set; } + [XmlElement(ElementName = "samplesPerEchoLine", Namespace = "rcmGsProductSchema")] + public SamplesPerEchoLine SamplesPerEchoLine { get; set; } - [XmlElement(ElementName="steppedReceiveMode", Namespace="rcmGsProductSchema")] - public bool SteppedReceiveMode { get; set; } -} + [XmlElement(ElementName = "steppedReceiveMode", Namespace = "rcmGsProductSchema")] + public bool SteppedReceiveMode { get; set; } + } -[XmlRoot(ElementName="numberOfMissingLines", Namespace="rcmGsProductSchema")] -public class NumberOfMissingLines { + [XmlRoot(ElementName = "numberOfMissingLines", Namespace = "rcmGsProductSchema")] + public class NumberOfMissingLines + { - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlText] - public int Text { get; set; } -} + [XmlText] + public int Text { get; set; } + } -[XmlRoot(ElementName="bias", Namespace="rcmGsProductSchema")] -public class Bias { + [XmlRoot(ElementName = "bias", Namespace = "rcmGsProductSchema")] + public class Bias + { - [XmlAttribute(AttributeName="dataStream", Namespace="")] - public string DataStream { get; set; } + [XmlAttribute(AttributeName = "dataStream", Namespace = "")] + public string DataStream { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="standardDeviation", Namespace="rcmGsProductSchema")] -public class StandardDeviation { + [XmlRoot(ElementName = "standardDeviation", Namespace = "rcmGsProductSchema")] + public class StandardDeviation + { - [XmlAttribute(AttributeName="dataStream", Namespace="")] - public string DataStream { get; set; } + [XmlAttribute(AttributeName = "dataStream", Namespace = "")] + public string DataStream { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="phaseOrthogonality", Namespace="rcmGsProductSchema")] -public class PhaseOrthogonality { + [XmlRoot(ElementName = "phaseOrthogonality", Namespace = "rcmGsProductSchema")] + public class PhaseOrthogonality + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="rawDataHistogram", Namespace="rcmGsProductSchema")] -public class RawDataHistogram { + [XmlRoot(ElementName = "rawDataHistogram", Namespace = "rcmGsProductSchema")] + public class RawDataHistogram + { - [XmlAttribute(AttributeName="dataStream", Namespace="")] - public string DataStream { get; set; } + [XmlAttribute(AttributeName = "dataStream", Namespace = "")] + public string DataStream { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="rawDataAnalysis", Namespace="rcmGsProductSchema")] -public class RawDataAnalysis { + [XmlRoot(ElementName = "rawDataAnalysis", Namespace = "rcmGsProductSchema")] + public class RawDataAnalysis + { - [XmlElement(ElementName="bias", Namespace="rcmGsProductSchema")] - public List Bias { get; set; } + [XmlElement(ElementName = "bias", Namespace = "rcmGsProductSchema")] + public List Bias { get; set; } - [XmlElement(ElementName="standardDeviation", Namespace="rcmGsProductSchema")] - public List StandardDeviation { get; set; } + [XmlElement(ElementName = "standardDeviation", Namespace = "rcmGsProductSchema")] + public List StandardDeviation { get; set; } - [XmlElement(ElementName="gainImbalance", Namespace="rcmGsProductSchema")] - public double GainImbalance { get; set; } + [XmlElement(ElementName = "gainImbalance", Namespace = "rcmGsProductSchema")] + public double GainImbalance { get; set; } - [XmlElement(ElementName="phaseOrthogonality", Namespace="rcmGsProductSchema")] - public PhaseOrthogonality PhaseOrthogonality { get; set; } + [XmlElement(ElementName = "phaseOrthogonality", Namespace = "rcmGsProductSchema")] + public PhaseOrthogonality PhaseOrthogonality { get; set; } - [XmlElement(ElementName="rawDataHistogram", Namespace="rcmGsProductSchema")] - public List RawDataHistogram { get; set; } + [XmlElement(ElementName = "rawDataHistogram", Namespace = "rcmGsProductSchema")] + public List RawDataHistogram { get; set; } - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="rawDataAttributes", Namespace="rcmGsProductSchema")] -public class RawDataAttributes { + [XmlRoot(ElementName = "rawDataAttributes", Namespace = "rcmGsProductSchema")] + public class RawDataAttributes + { - [XmlElement(ElementName="numberOfInputDataGaps", Namespace="rcmGsProductSchema")] - public int NumberOfInputDataGaps { get; set; } + [XmlElement(ElementName = "numberOfInputDataGaps", Namespace = "rcmGsProductSchema")] + public int NumberOfInputDataGaps { get; set; } - [XmlElement(ElementName="gapSize", Namespace="rcmGsProductSchema")] - public int GapSize { get; set; } + [XmlElement(ElementName = "gapSize", Namespace = "rcmGsProductSchema")] + public int GapSize { get; set; } - [XmlElement(ElementName="numberOfMissingLines", Namespace="rcmGsProductSchema")] - public List NumberOfMissingLines { get; set; } + [XmlElement(ElementName = "numberOfMissingLines", Namespace = "rcmGsProductSchema")] + public List NumberOfMissingLines { get; set; } - [XmlElement(ElementName="rawDataAnalysis", Namespace="rcmGsProductSchema")] - public List RawDataAnalysis { get; set; } -} + [XmlElement(ElementName = "rawDataAnalysis", Namespace = "rcmGsProductSchema")] + public List RawDataAnalysis { get; set; } + } -[XmlRoot(ElementName="xPosition", Namespace="rcmGsProductSchema")] -public class XPosition { + [XmlRoot(ElementName = "xPosition", Namespace = "rcmGsProductSchema")] + public class XPosition + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="yPosition", Namespace="rcmGsProductSchema")] -public class YPosition { + [XmlRoot(ElementName = "yPosition", Namespace = "rcmGsProductSchema")] + public class YPosition + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="zPosition", Namespace="rcmGsProductSchema")] -public class ZPosition { + [XmlRoot(ElementName = "zPosition", Namespace = "rcmGsProductSchema")] + public class ZPosition + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="xVelocity", Namespace="rcmGsProductSchema")] -public class XVelocity { + [XmlRoot(ElementName = "xVelocity", Namespace = "rcmGsProductSchema")] + public class XVelocity + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="yVelocity", Namespace="rcmGsProductSchema")] -public class YVelocity { + [XmlRoot(ElementName = "yVelocity", Namespace = "rcmGsProductSchema")] + public class YVelocity + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="zVelocity", Namespace="rcmGsProductSchema")] -public class ZVelocity { + [XmlRoot(ElementName = "zVelocity", Namespace = "rcmGsProductSchema")] + public class ZVelocity + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="stateVector", Namespace="rcmGsProductSchema")] -public class StateVector { + [XmlRoot(ElementName = "stateVector", Namespace = "rcmGsProductSchema")] + public class StateVector + { - [XmlElement(ElementName="timeStamp", Namespace="rcmGsProductSchema")] - public DateTime TimeStamp { get; set; } + [XmlElement(ElementName = "timeStamp", Namespace = "rcmGsProductSchema")] + public DateTime TimeStamp { get; set; } - [XmlElement(ElementName="xPosition", Namespace="rcmGsProductSchema")] - public XPosition XPosition { get; set; } + [XmlElement(ElementName = "xPosition", Namespace = "rcmGsProductSchema")] + public XPosition XPosition { get; set; } - [XmlElement(ElementName="yPosition", Namespace="rcmGsProductSchema")] - public YPosition YPosition { get; set; } + [XmlElement(ElementName = "yPosition", Namespace = "rcmGsProductSchema")] + public YPosition YPosition { get; set; } - [XmlElement(ElementName="zPosition", Namespace="rcmGsProductSchema")] - public ZPosition ZPosition { get; set; } + [XmlElement(ElementName = "zPosition", Namespace = "rcmGsProductSchema")] + public ZPosition ZPosition { get; set; } - [XmlElement(ElementName="xVelocity", Namespace="rcmGsProductSchema")] - public XVelocity XVelocity { get; set; } + [XmlElement(ElementName = "xVelocity", Namespace = "rcmGsProductSchema")] + public XVelocity XVelocity { get; set; } - [XmlElement(ElementName="yVelocity", Namespace="rcmGsProductSchema")] - public YVelocity YVelocity { get; set; } + [XmlElement(ElementName = "yVelocity", Namespace = "rcmGsProductSchema")] + public YVelocity YVelocity { get; set; } - [XmlElement(ElementName="zVelocity", Namespace="rcmGsProductSchema")] - public ZVelocity ZVelocity { get; set; } -} + [XmlElement(ElementName = "zVelocity", Namespace = "rcmGsProductSchema")] + public ZVelocity ZVelocity { get; set; } + } -[XmlRoot(ElementName="orbitInformation", Namespace="rcmGsProductSchema")] -public class OrbitInformation { + [XmlRoot(ElementName = "orbitInformation", Namespace = "rcmGsProductSchema")] + public class OrbitInformation + { - [XmlElement(ElementName="passDirection", Namespace="rcmGsProductSchema")] - public string PassDirection { get; set; } + [XmlElement(ElementName = "passDirection", Namespace = "rcmGsProductSchema")] + public string PassDirection { get; set; } - [XmlElement(ElementName="orbitDataSource", Namespace="rcmGsProductSchema")] - public string OrbitDataSource { get; set; } + [XmlElement(ElementName = "orbitDataSource", Namespace = "rcmGsProductSchema")] + public string OrbitDataSource { get; set; } - [XmlElement(ElementName="withinOrbitTube", Namespace="rcmGsProductSchema")] - public bool WithinOrbitTube { get; set; } + [XmlElement(ElementName = "withinOrbitTube", Namespace = "rcmGsProductSchema")] + public bool WithinOrbitTube { get; set; } - [XmlElement(ElementName="orbitDataFileName", Namespace="rcmGsProductSchema")] - public string OrbitDataFileName { get; set; } + [XmlElement(ElementName = "orbitDataFileName", Namespace = "rcmGsProductSchema")] + public string OrbitDataFileName { get; set; } - [XmlElement(ElementName="stateVector", Namespace="rcmGsProductSchema")] - public List StateVector { get; set; } -} + [XmlElement(ElementName = "stateVector", Namespace = "rcmGsProductSchema")] + public List StateVector { get; set; } + } -[XmlRoot(ElementName="yaw", Namespace="rcmGsProductSchema")] -public class Yaw { + [XmlRoot(ElementName = "yaw", Namespace = "rcmGsProductSchema")] + public class Yaw + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="roll", Namespace="rcmGsProductSchema")] -public class Roll { + [XmlRoot(ElementName = "roll", Namespace = "rcmGsProductSchema")] + public class Roll + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="pitch", Namespace="rcmGsProductSchema")] -public class Pitch { + [XmlRoot(ElementName = "pitch", Namespace = "rcmGsProductSchema")] + public class Pitch + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="attitudeAngles", Namespace="rcmGsProductSchema")] -public class AttitudeAngles { + [XmlRoot(ElementName = "attitudeAngles", Namespace = "rcmGsProductSchema")] + public class AttitudeAngles + { - [XmlElement(ElementName="timeStamp", Namespace="rcmGsProductSchema")] - public DateTime TimeStamp { get; set; } + [XmlElement(ElementName = "timeStamp", Namespace = "rcmGsProductSchema")] + public DateTime TimeStamp { get; set; } - [XmlElement(ElementName="yaw", Namespace="rcmGsProductSchema")] - public Yaw Yaw { get; set; } + [XmlElement(ElementName = "yaw", Namespace = "rcmGsProductSchema")] + public Yaw Yaw { get; set; } - [XmlElement(ElementName="roll", Namespace="rcmGsProductSchema")] - public Roll Roll { get; set; } + [XmlElement(ElementName = "roll", Namespace = "rcmGsProductSchema")] + public Roll Roll { get; set; } - [XmlElement(ElementName="pitch", Namespace="rcmGsProductSchema")] - public Pitch Pitch { get; set; } -} + [XmlElement(ElementName = "pitch", Namespace = "rcmGsProductSchema")] + public Pitch Pitch { get; set; } + } -[XmlRoot(ElementName="attitudeInformation", Namespace="rcmGsProductSchema")] -public class AttitudeInformation { + [XmlRoot(ElementName = "attitudeInformation", Namespace = "rcmGsProductSchema")] + public class AttitudeInformation + { - [XmlElement(ElementName="attitudeDataSource", Namespace="rcmGsProductSchema")] - public string AttitudeDataSource { get; set; } + [XmlElement(ElementName = "attitudeDataSource", Namespace = "rcmGsProductSchema")] + public string AttitudeDataSource { get; set; } - [XmlElement(ElementName="attitudeOffsetsApplied", Namespace="rcmGsProductSchema")] - public bool AttitudeOffsetsApplied { get; set; } + [XmlElement(ElementName = "attitudeOffsetsApplied", Namespace = "rcmGsProductSchema")] + public bool AttitudeOffsetsApplied { get; set; } - [XmlElement(ElementName="attitudeAngles", Namespace="rcmGsProductSchema")] - public List AttitudeAngles { get; set; } -} + [XmlElement(ElementName = "attitudeAngles", Namespace = "rcmGsProductSchema")] + public List AttitudeAngles { get; set; } + } -[XmlRoot(ElementName="orbitAndAttitude", Namespace="rcmGsProductSchema")] -public class OrbitAndAttitude { + [XmlRoot(ElementName = "orbitAndAttitude", Namespace = "rcmGsProductSchema")] + public class OrbitAndAttitude + { - [XmlElement(ElementName="orbitInformation", Namespace="rcmGsProductSchema")] - public OrbitInformation OrbitInformation { get; set; } + [XmlElement(ElementName = "orbitInformation", Namespace = "rcmGsProductSchema")] + public OrbitInformation OrbitInformation { get; set; } - [XmlElement(ElementName="attitudeInformation", Namespace="rcmGsProductSchema")] - public AttitudeInformation AttitudeInformation { get; set; } -} + [XmlElement(ElementName = "attitudeInformation", Namespace = "rcmGsProductSchema")] + public AttitudeInformation AttitudeInformation { get; set; } + } -[XmlRoot(ElementName="sourceAttributes", Namespace="rcmGsProductSchema")] -public class SourceAttributes { + [XmlRoot(ElementName = "sourceAttributes", Namespace = "rcmGsProductSchema")] + public class SourceAttributes + { - [XmlElement(ElementName="satellite", Namespace="rcmGsProductSchema")] - public string Satellite { get; set; } + [XmlElement(ElementName = "satellite", Namespace = "rcmGsProductSchema")] + public string Satellite { get; set; } - [XmlElement(ElementName="sensor", Namespace="rcmGsProductSchema")] - public string Sensor { get; set; } + [XmlElement(ElementName = "sensor", Namespace = "rcmGsProductSchema")] + public string Sensor { get; set; } - [XmlElement(ElementName="polarizationDataMode", Namespace="rcmGsProductSchema")] - public string PolarizationDataMode { get; set; } + [XmlElement(ElementName = "polarizationDataMode", Namespace = "rcmGsProductSchema")] + public string PolarizationDataMode { get; set; } - [XmlElement(ElementName="downlinkSegmentId", Namespace="rcmGsProductSchema")] - public string DownlinkSegmentId { get; set; } + [XmlElement(ElementName = "downlinkSegmentId", Namespace = "rcmGsProductSchema")] + public string DownlinkSegmentId { get; set; } - [XmlElement(ElementName="inputDatasetFacilityId", Namespace="rcmGsProductSchema")] - public string InputDatasetFacilityId { get; set; } + [XmlElement(ElementName = "inputDatasetFacilityId", Namespace = "rcmGsProductSchema")] + public string InputDatasetFacilityId { get; set; } - [XmlElement(ElementName="beamMode", Namespace="rcmGsProductSchema")] - public string BeamMode { get; set; } + [XmlElement(ElementName = "beamMode", Namespace = "rcmGsProductSchema")] + public string BeamMode { get; set; } - [XmlElement(ElementName="beamModeDefinitionId", Namespace="rcmGsProductSchema")] - public int BeamModeDefinitionId { get; set; } + [XmlElement(ElementName = "beamModeDefinitionId", Namespace = "rcmGsProductSchema")] + public int BeamModeDefinitionId { get; set; } - [XmlElement(ElementName="beamModeVersion", Namespace="rcmGsProductSchema")] - public int BeamModeVersion { get; set; } + [XmlElement(ElementName = "beamModeVersion", Namespace = "rcmGsProductSchema")] + public int BeamModeVersion { get; set; } - [XmlElement(ElementName="beamModeMnemonic", Namespace="rcmGsProductSchema")] - public string BeamModeMnemonic { get; set; } + [XmlElement(ElementName = "beamModeMnemonic", Namespace = "rcmGsProductSchema")] + public string BeamModeMnemonic { get; set; } - [XmlElement(ElementName="rawDataStartTime", Namespace="rcmGsProductSchema")] - public DateTime RawDataStartTime { get; set; } + [XmlElement(ElementName = "rawDataStartTime", Namespace = "rcmGsProductSchema")] + public DateTime RawDataStartTime { get; set; } - [XmlElement(ElementName="radarParameters", Namespace="rcmGsProductSchema")] - public RadarParameters RadarParameters { get; set; } + [XmlElement(ElementName = "radarParameters", Namespace = "rcmGsProductSchema")] + public RadarParameters RadarParameters { get; set; } - [XmlElement(ElementName="rawDataAttributes", Namespace="rcmGsProductSchema")] - public RawDataAttributes RawDataAttributes { get; set; } + [XmlElement(ElementName = "rawDataAttributes", Namespace = "rcmGsProductSchema")] + public RawDataAttributes RawDataAttributes { get; set; } - [XmlElement(ElementName="orbitAndAttitude", Namespace="rcmGsProductSchema")] - public OrbitAndAttitude OrbitAndAttitude { get; set; } -} + [XmlElement(ElementName = "orbitAndAttitude", Namespace = "rcmGsProductSchema")] + public OrbitAndAttitude OrbitAndAttitude { get; set; } + } -[XmlRoot(ElementName="generalProcessingInformation", Namespace="rcmGsProductSchema")] -public class GeneralProcessingInformation { + [XmlRoot(ElementName = "generalProcessingInformation", Namespace = "rcmGsProductSchema")] + public class GeneralProcessingInformation + { - [XmlElement(ElementName="productType", Namespace="rcmGsProductSchema")] - public string ProductType { get; set; } + [XmlElement(ElementName = "productType", Namespace = "rcmGsProductSchema")] + public string ProductType { get; set; } - [XmlElement(ElementName="polarizationsInProduct", Namespace="rcmGsProductSchema")] - public string PolarizationsInProduct { get; set; } + [XmlElement(ElementName = "polarizationsInProduct", Namespace = "rcmGsProductSchema")] + public string PolarizationsInProduct { get; set; } - [XmlElement(ElementName="processingFacility", Namespace="rcmGsProductSchema")] - public string ProcessingFacility { get; set; } + [XmlElement(ElementName = "processingFacility", Namespace = "rcmGsProductSchema")] + public string ProcessingFacility { get; set; } - [XmlElement(ElementName="processingTime", Namespace="rcmGsProductSchema")] - public DateTime ProcessingTime { get; set; } + [XmlElement(ElementName = "processingTime", Namespace = "rcmGsProductSchema")] + public DateTime ProcessingTime { get; set; } - [XmlElement(ElementName="softwareVersion", Namespace="rcmGsProductSchema")] - public string SoftwareVersion { get; set; } + [XmlElement(ElementName = "softwareVersion", Namespace = "rcmGsProductSchema")] + public string SoftwareVersion { get; set; } - [XmlElement(ElementName="processingMode", Namespace="rcmGsProductSchema")] - public string ProcessingMode { get; set; } + [XmlElement(ElementName = "processingMode", Namespace = "rcmGsProductSchema")] + public string ProcessingMode { get; set; } - [XmlElement(ElementName="processingPriority", Namespace="rcmGsProductSchema")] - public string ProcessingPriority { get; set; } -} + [XmlElement(ElementName = "processingPriority", Namespace = "rcmGsProductSchema")] + public string ProcessingPriority { get; set; } + } -[XmlRoot(ElementName="atmosphericPropagationDelay", Namespace="rcmGsProductSchema")] -public class AtmosphericPropagationDelay { + [XmlRoot(ElementName = "atmosphericPropagationDelay", Namespace = "rcmGsProductSchema")] + public class AtmosphericPropagationDelay + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="numberOfLinesProcessed", Namespace="rcmGsProductSchema")] -public class NumberOfLinesProcessed { + [XmlRoot(ElementName = "numberOfLinesProcessed", Namespace = "rcmGsProductSchema")] + public class NumberOfLinesProcessed + { - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlText] - public int Text { get; set; } -} + [XmlText] + public int Text { get; set; } + } -[XmlRoot(ElementName="rangeLookBandwidth", Namespace="rcmGsProductSchema")] -public class RangeLookBandwidth { + [XmlRoot(ElementName = "rangeLookBandwidth", Namespace = "rcmGsProductSchema")] + public class RangeLookBandwidth + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="totalProcessedRangeBandwidth", Namespace="rcmGsProductSchema")] -public class TotalProcessedRangeBandwidth { + [XmlRoot(ElementName = "totalProcessedRangeBandwidth", Namespace = "rcmGsProductSchema")] + public class TotalProcessedRangeBandwidth + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="azimuthLookBandwidth", Namespace="rcmGsProductSchema")] -public class AzimuthLookBandwidth { + [XmlRoot(ElementName = "azimuthLookBandwidth", Namespace = "rcmGsProductSchema")] + public class AzimuthLookBandwidth + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="totalProcessedAzimuthBandwidth", Namespace="rcmGsProductSchema")] -public class TotalProcessedAzimuthBandwidth { + [XmlRoot(ElementName = "totalProcessedAzimuthBandwidth", Namespace = "rcmGsProductSchema")] + public class TotalProcessedAzimuthBandwidth + { - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="azimuthWindow", Namespace="rcmGsProductSchema")] -public class AzimuthWindow { + [XmlRoot(ElementName = "azimuthWindow", Namespace = "rcmGsProductSchema")] + public class AzimuthWindow + { - [XmlElement(ElementName="windowName", Namespace="rcmGsProductSchema")] - public string WindowName { get; set; } + [XmlElement(ElementName = "windowName", Namespace = "rcmGsProductSchema")] + public string WindowName { get; set; } - [XmlElement(ElementName="windowCoefficient", Namespace="rcmGsProductSchema")] - public double WindowCoefficient { get; set; } + [XmlElement(ElementName = "windowCoefficient", Namespace = "rcmGsProductSchema")] + public double WindowCoefficient { get; set; } - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="rangeWindow", Namespace="rcmGsProductSchema")] -public class RangeWindow { + [XmlRoot(ElementName = "rangeWindow", Namespace = "rcmGsProductSchema")] + public class RangeWindow + { - [XmlElement(ElementName="windowName", Namespace="rcmGsProductSchema")] - public string WindowName { get; set; } + [XmlElement(ElementName = "windowName", Namespace = "rcmGsProductSchema")] + public string WindowName { get; set; } - [XmlElement(ElementName="windowCoefficient", Namespace="rcmGsProductSchema")] - public double WindowCoefficient { get; set; } -} + [XmlElement(ElementName = "windowCoefficient", Namespace = "rcmGsProductSchema")] + public double WindowCoefficient { get; set; } + } -[XmlRoot(ElementName="satelliteHeight", Namespace="rcmGsProductSchema")] -public class SatelliteHeight { + [XmlRoot(ElementName = "satelliteHeight", Namespace = "rcmGsProductSchema")] + public class SatelliteHeight + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="sarProcessingInformation", Namespace="rcmGsProductSchema")] -public class SarProcessingInformation { + [XmlRoot(ElementName = "sarProcessingInformation", Namespace = "rcmGsProductSchema")] + public class SarProcessingInformation + { - [XmlElement(ElementName="lutApplied", Namespace="rcmGsProductSchema")] - public string LutApplied { get; set; } + [XmlElement(ElementName = "lutApplied", Namespace = "rcmGsProductSchema")] + public string LutApplied { get; set; } - [XmlElement(ElementName="perPolarizationScaling", Namespace="rcmGsProductSchema")] - public bool PerPolarizationScaling { get; set; } + [XmlElement(ElementName = "perPolarizationScaling", Namespace = "rcmGsProductSchema")] + public bool PerPolarizationScaling { get; set; } - [XmlElement(ElementName="atmosphericCorrection", Namespace="rcmGsProductSchema")] - public bool AtmosphericCorrection { get; set; } + [XmlElement(ElementName = "atmosphericCorrection", Namespace = "rcmGsProductSchema")] + public bool AtmosphericCorrection { get; set; } - [XmlElement(ElementName="elevationPatternCorrection", Namespace="rcmGsProductSchema")] - public bool ElevationPatternCorrection { get; set; } + [XmlElement(ElementName = "elevationPatternCorrection", Namespace = "rcmGsProductSchema")] + public bool ElevationPatternCorrection { get; set; } - [XmlElement(ElementName="rangeSpreadingLossCorrection", Namespace="rcmGsProductSchema")] - public bool RangeSpreadingLossCorrection { get; set; } + [XmlElement(ElementName = "rangeSpreadingLossCorrection", Namespace = "rcmGsProductSchema")] + public bool RangeSpreadingLossCorrection { get; set; } - [XmlElement(ElementName="pulseDependentGainCorrection", Namespace="rcmGsProductSchema")] - public bool PulseDependentGainCorrection { get; set; } + [XmlElement(ElementName = "pulseDependentGainCorrection", Namespace = "rcmGsProductSchema")] + public bool PulseDependentGainCorrection { get; set; } - [XmlElement(ElementName="receiverSettableGainCorrection", Namespace="rcmGsProductSchema")] - public bool ReceiverSettableGainCorrection { get; set; } + [XmlElement(ElementName = "receiverSettableGainCorrection", Namespace = "rcmGsProductSchema")] + public bool ReceiverSettableGainCorrection { get; set; } - [XmlElement(ElementName="rawDataCorrection", Namespace="rcmGsProductSchema")] - public bool RawDataCorrection { get; set; } + [XmlElement(ElementName = "rawDataCorrection", Namespace = "rcmGsProductSchema")] + public bool RawDataCorrection { get; set; } - [XmlElement(ElementName="bistaticCorrectionApplied", Namespace="rcmGsProductSchema")] - public bool BistaticCorrectionApplied { get; set; } + [XmlElement(ElementName = "bistaticCorrectionApplied", Namespace = "rcmGsProductSchema")] + public bool BistaticCorrectionApplied { get; set; } - [XmlElement(ElementName="rangeReferenceFunctionSource", Namespace="rcmGsProductSchema")] - public string RangeReferenceFunctionSource { get; set; } + [XmlElement(ElementName = "rangeReferenceFunctionSource", Namespace = "rcmGsProductSchema")] + public string RangeReferenceFunctionSource { get; set; } - [XmlElement(ElementName="atmosphericPropagationDelay", Namespace="rcmGsProductSchema")] - public AtmosphericPropagationDelay AtmosphericPropagationDelay { get; set; } + [XmlElement(ElementName = "atmosphericPropagationDelay", Namespace = "rcmGsProductSchema")] + public AtmosphericPropagationDelay AtmosphericPropagationDelay { get; set; } - [XmlElement(ElementName="dopplerSource", Namespace="rcmGsProductSchema")] - public string DopplerSource { get; set; } + [XmlElement(ElementName = "dopplerSource", Namespace = "rcmGsProductSchema")] + public string DopplerSource { get; set; } - [XmlElement(ElementName="estimatedRollAngleUsed", Namespace="rcmGsProductSchema")] - public bool EstimatedRollAngleUsed { get; set; } + [XmlElement(ElementName = "estimatedRollAngleUsed", Namespace = "rcmGsProductSchema")] + public bool EstimatedRollAngleUsed { get; set; } - [XmlElement(ElementName="zeroDopplerTimeFirstLine", Namespace="rcmGsProductSchema")] - public DateTime ZeroDopplerTimeFirstLine { get; set; } + [XmlElement(ElementName = "zeroDopplerTimeFirstLine", Namespace = "rcmGsProductSchema")] + public DateTime ZeroDopplerTimeFirstLine { get; set; } - [XmlElement(ElementName="zeroDopplerTimeLastLine", Namespace="rcmGsProductSchema")] - public DateTime ZeroDopplerTimeLastLine { get; set; } + [XmlElement(ElementName = "zeroDopplerTimeLastLine", Namespace = "rcmGsProductSchema")] + public DateTime ZeroDopplerTimeLastLine { get; set; } - [XmlElement(ElementName="numberOfLinesProcessed", Namespace="rcmGsProductSchema")] - public List NumberOfLinesProcessed { get; set; } + [XmlElement(ElementName = "numberOfLinesProcessed", Namespace = "rcmGsProductSchema")] + public List NumberOfLinesProcessed { get; set; } - [XmlElement(ElementName="numberOfRangeLooks", Namespace="rcmGsProductSchema")] - public int NumberOfRangeLooks { get; set; } + [XmlElement(ElementName = "numberOfRangeLooks", Namespace = "rcmGsProductSchema")] + public int NumberOfRangeLooks { get; set; } - [XmlElement(ElementName="rangeLookBandwidth", Namespace="rcmGsProductSchema")] - public RangeLookBandwidth RangeLookBandwidth { get; set; } + [XmlElement(ElementName = "rangeLookBandwidth", Namespace = "rcmGsProductSchema")] + public RangeLookBandwidth RangeLookBandwidth { get; set; } - [XmlElement(ElementName="totalProcessedRangeBandwidth", Namespace="rcmGsProductSchema")] - public TotalProcessedRangeBandwidth TotalProcessedRangeBandwidth { get; set; } + [XmlElement(ElementName = "totalProcessedRangeBandwidth", Namespace = "rcmGsProductSchema")] + public TotalProcessedRangeBandwidth TotalProcessedRangeBandwidth { get; set; } - [XmlElement(ElementName="numberOfAzimuthLooks", Namespace="rcmGsProductSchema")] - public int NumberOfAzimuthLooks { get; set; } + [XmlElement(ElementName = "numberOfAzimuthLooks", Namespace = "rcmGsProductSchema")] + public int NumberOfAzimuthLooks { get; set; } - [XmlElement(ElementName="scalarLookWeights", Namespace="rcmGsProductSchema")] - public string ScalarLookWeights { get; set; } + [XmlElement(ElementName = "scalarLookWeights", Namespace = "rcmGsProductSchema")] + public string ScalarLookWeights { get; set; } - [XmlElement(ElementName="azimuthLookBandwidth", Namespace="rcmGsProductSchema")] - public AzimuthLookBandwidth AzimuthLookBandwidth { get; set; } + [XmlElement(ElementName = "azimuthLookBandwidth", Namespace = "rcmGsProductSchema")] + public AzimuthLookBandwidth AzimuthLookBandwidth { get; set; } - [XmlElement(ElementName="totalProcessedAzimuthBandwidth", Namespace="rcmGsProductSchema")] - public TotalProcessedAzimuthBandwidth TotalProcessedAzimuthBandwidth { get; set; } + [XmlElement(ElementName = "totalProcessedAzimuthBandwidth", Namespace = "rcmGsProductSchema")] + public TotalProcessedAzimuthBandwidth TotalProcessedAzimuthBandwidth { get; set; } - [XmlElement(ElementName="azimuthWindow", Namespace="rcmGsProductSchema")] - public AzimuthWindow AzimuthWindow { get; set; } + [XmlElement(ElementName = "azimuthWindow", Namespace = "rcmGsProductSchema")] + public AzimuthWindow AzimuthWindow { get; set; } - [XmlElement(ElementName="rangeWindow", Namespace="rcmGsProductSchema")] - public RangeWindow RangeWindow { get; set; } + [XmlElement(ElementName = "rangeWindow", Namespace = "rcmGsProductSchema")] + public RangeWindow RangeWindow { get; set; } - [XmlElement(ElementName="satelliteHeight", Namespace="rcmGsProductSchema")] - public SatelliteHeight SatelliteHeight { get; set; } -} + [XmlElement(ElementName = "satelliteHeight", Namespace = "rcmGsProductSchema")] + public SatelliteHeight SatelliteHeight { get; set; } + } -[XmlRoot(ElementName="sideLobeLevel", Namespace="rcmGsProductSchema")] -public class SideLobeLevel { + [XmlRoot(ElementName = "sideLobeLevel", Namespace = "rcmGsProductSchema")] + public class SideLobeLevel + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="integratedSideLobeRatio", Namespace="rcmGsProductSchema")] -public class IntegratedSideLobeRatio { + [XmlRoot(ElementName = "integratedSideLobeRatio", Namespace = "rcmGsProductSchema")] + public class IntegratedSideLobeRatio + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="chirpQuality", Namespace="rcmGsProductSchema")] -public class ChirpQuality { + [XmlRoot(ElementName = "chirpQuality", Namespace = "rcmGsProductSchema")] + public class ChirpQuality + { - [XmlElement(ElementName="replicaQualityValid", Namespace="rcmGsProductSchema")] - public bool ReplicaQualityValid { get; set; } + [XmlElement(ElementName = "replicaQualityValid", Namespace = "rcmGsProductSchema")] + public bool ReplicaQualityValid { get; set; } - [XmlElement(ElementName="crossCorrelationWidth", Namespace="rcmGsProductSchema")] - public double CrossCorrelationWidth { get; set; } + [XmlElement(ElementName = "crossCorrelationWidth", Namespace = "rcmGsProductSchema")] + public double CrossCorrelationWidth { get; set; } - [XmlElement(ElementName="sideLobeLevel", Namespace="rcmGsProductSchema")] - public SideLobeLevel SideLobeLevel { get; set; } + [XmlElement(ElementName = "sideLobeLevel", Namespace = "rcmGsProductSchema")] + public SideLobeLevel SideLobeLevel { get; set; } - [XmlElement(ElementName="integratedSideLobeRatio", Namespace="rcmGsProductSchema")] - public IntegratedSideLobeRatio IntegratedSideLobeRatio { get; set; } + [XmlElement(ElementName = "integratedSideLobeRatio", Namespace = "rcmGsProductSchema")] + public IntegratedSideLobeRatio IntegratedSideLobeRatio { get; set; } - [XmlElement(ElementName="crossCorrelationPeakLoc", Namespace="rcmGsProductSchema")] - public double CrossCorrelationPeakLoc { get; set; } -} + [XmlElement(ElementName = "crossCorrelationPeakLoc", Namespace = "rcmGsProductSchema")] + public double CrossCorrelationPeakLoc { get; set; } + } -[XmlRoot(ElementName="chirpPower", Namespace="rcmGsProductSchema")] -public class ChirpPower { + [XmlRoot(ElementName = "chirpPower", Namespace = "rcmGsProductSchema")] + public class ChirpPower + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="chirp", Namespace="rcmGsProductSchema")] -public class Chirp { + [XmlRoot(ElementName = "chirp", Namespace = "rcmGsProductSchema")] + public class Chirp + { - [XmlElement(ElementName="chirpQuality", Namespace="rcmGsProductSchema")] - public ChirpQuality ChirpQuality { get; set; } + [XmlElement(ElementName = "chirpQuality", Namespace = "rcmGsProductSchema")] + public ChirpQuality ChirpQuality { get; set; } - [XmlElement(ElementName="chirpPower", Namespace="rcmGsProductSchema")] - public ChirpPower ChirpPower { get; set; } + [XmlElement(ElementName = "chirpPower", Namespace = "rcmGsProductSchema")] + public ChirpPower ChirpPower { get; set; } - [XmlElement(ElementName="amplitudeCoefficients", Namespace="rcmGsProductSchema")] - public string AmplitudeCoefficients { get; set; } + [XmlElement(ElementName = "amplitudeCoefficients", Namespace = "rcmGsProductSchema")] + public string AmplitudeCoefficients { get; set; } - [XmlElement(ElementName="phaseCoefficients", Namespace="rcmGsProductSchema")] - public string PhaseCoefficients { get; set; } + [XmlElement(ElementName = "phaseCoefficients", Namespace = "rcmGsProductSchema")] + public string PhaseCoefficients { get; set; } - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlAttribute(AttributeName="pulse", Namespace="")] - public int Pulse { get; set; } + [XmlAttribute(AttributeName = "pulse", Namespace = "")] + public int Pulse { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="slantRangeTimeToFirstRangeSample", Namespace="rcmGsProductSchema")] -public class SlantRangeTimeToFirstRangeSample { + [XmlRoot(ElementName = "slantRangeTimeToFirstRangeSample", Namespace = "rcmGsProductSchema")] + public class SlantRangeTimeToFirstRangeSample + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="groundRangeOrigin", Namespace="rcmGsProductSchema")] -public class GroundRangeOrigin { + [XmlRoot(ElementName = "groundRangeOrigin", Namespace = "rcmGsProductSchema")] + public class GroundRangeOrigin + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="slantRangeToGroundRange", Namespace="rcmGsProductSchema")] -public class SlantRangeToGroundRange { + [XmlRoot(ElementName = "slantRangeToGroundRange", Namespace = "rcmGsProductSchema")] + public class SlantRangeToGroundRange + { - [XmlElement(ElementName="zeroDopplerAzimuthTime", Namespace="rcmGsProductSchema")] - public DateTime ZeroDopplerAzimuthTime { get; set; } + [XmlElement(ElementName = "zeroDopplerAzimuthTime", Namespace = "rcmGsProductSchema")] + public DateTime ZeroDopplerAzimuthTime { get; set; } - [XmlElement(ElementName="slantRangeTimeToFirstRangeSample", Namespace="rcmGsProductSchema")] - public SlantRangeTimeToFirstRangeSample SlantRangeTimeToFirstRangeSample { get; set; } + [XmlElement(ElementName = "slantRangeTimeToFirstRangeSample", Namespace = "rcmGsProductSchema")] + public SlantRangeTimeToFirstRangeSample SlantRangeTimeToFirstRangeSample { get; set; } - [XmlElement(ElementName="groundRangeOrigin", Namespace="rcmGsProductSchema")] - public GroundRangeOrigin GroundRangeOrigin { get; set; } + [XmlElement(ElementName = "groundRangeOrigin", Namespace = "rcmGsProductSchema")] + public GroundRangeOrigin GroundRangeOrigin { get; set; } - [XmlElement(ElementName="groundToSlantRangeCoefficients", Namespace="rcmGsProductSchema")] - public string GroundToSlantRangeCoefficients { get; set; } -} + [XmlElement(ElementName = "groundToSlantRangeCoefficients", Namespace = "rcmGsProductSchema")] + public string GroundToSlantRangeCoefficients { get; set; } + } -[XmlRoot(ElementName="imageGenerationParameters", Namespace="rcmGsProductSchema")] -public class ImageGenerationParameters { + [XmlRoot(ElementName = "imageGenerationParameters", Namespace = "rcmGsProductSchema")] + public class ImageGenerationParameters + { - [XmlElement(ElementName="generalProcessingInformation", Namespace="rcmGsProductSchema")] - public GeneralProcessingInformation GeneralProcessingInformation { get; set; } + [XmlElement(ElementName = "generalProcessingInformation", Namespace = "rcmGsProductSchema")] + public GeneralProcessingInformation GeneralProcessingInformation { get; set; } - [XmlElement(ElementName="sarProcessingInformation", Namespace="rcmGsProductSchema")] - public SarProcessingInformation SarProcessingInformation { get; set; } + [XmlElement(ElementName = "sarProcessingInformation", Namespace = "rcmGsProductSchema")] + public SarProcessingInformation SarProcessingInformation { get; set; } - [XmlElement(ElementName="chirp", Namespace="rcmGsProductSchema")] - public List Chirp { get; set; } + [XmlElement(ElementName = "chirp", Namespace = "rcmGsProductSchema")] + public List Chirp { get; set; } - [XmlElement(ElementName="slantRangeToGroundRange", Namespace="rcmGsProductSchema")] - public SlantRangeToGroundRange SlantRangeToGroundRange { get; set; } + [XmlElement(ElementName = "slantRangeToGroundRange", Namespace = "rcmGsProductSchema")] + public SlantRangeToGroundRange SlantRangeToGroundRange { get; set; } - [XmlElement(ElementName="dynamicProcessingParameterFile", Namespace="rcmGsProductSchema")] - public List DynamicProcessingParameterFile { get; set; } -} + [XmlElement(ElementName = "dynamicProcessingParameterFile", Namespace = "rcmGsProductSchema")] + public List DynamicProcessingParameterFile { get; set; } + } -[XmlRoot(ElementName="lookupTableFileName", Namespace="rcmGsProductSchema")] -public class LookupTableFileName { + [XmlRoot(ElementName = "lookupTableFileName", Namespace = "rcmGsProductSchema")] + public class LookupTableFileName + { - [XmlAttribute(AttributeName="sarCalibrationType", Namespace="")] - public string SarCalibrationType { get; set; } + [XmlAttribute(AttributeName = "sarCalibrationType", Namespace = "")] + public string SarCalibrationType { get; set; } - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="noiseLevelFileName", Namespace="rcmGsProductSchema")] -public class NoiseLevelFileName { + [XmlRoot(ElementName = "noiseLevelFileName", Namespace = "rcmGsProductSchema")] + public class NoiseLevelFileName + { - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="bitsPerSample", Namespace="rcmGsProductSchema")] -public class BitsPerSample { + [XmlRoot(ElementName = "bitsPerSample", Namespace = "rcmGsProductSchema")] + public class BitsPerSample + { - [XmlAttribute(AttributeName="dataStream", Namespace="")] - public string DataStream { get; set; } + [XmlAttribute(AttributeName = "dataStream", Namespace = "")] + public string DataStream { get; set; } - [XmlText] - public int Text { get; set; } -} + [XmlText] + public int Text { get; set; } + } -[XmlRoot(ElementName="sampledPixelSpacing", Namespace="rcmGsProductSchema")] -public class SampledPixelSpacing { + [XmlRoot(ElementName = "sampledPixelSpacing", Namespace = "rcmGsProductSchema")] + public class SampledPixelSpacing + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="sampledLineSpacing", Namespace="rcmGsProductSchema")] -public class SampledLineSpacing { + [XmlRoot(ElementName = "sampledLineSpacing", Namespace = "rcmGsProductSchema")] + public class SampledLineSpacing + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="sampledPixelSpacingTime", Namespace="rcmGsProductSchema")] -public class SampledPixelSpacingTime { + [XmlRoot(ElementName = "sampledPixelSpacingTime", Namespace = "rcmGsProductSchema")] + public class SampledPixelSpacingTime + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="sampledLineSpacingTime", Namespace="rcmGsProductSchema")] -public class SampledLineSpacingTime { + [XmlRoot(ElementName = "sampledLineSpacingTime", Namespace = "rcmGsProductSchema")] + public class SampledLineSpacingTime + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="rasterAttributes", Namespace="rcmGsProductSchema")] -public class RasterAttributes { + [XmlRoot(ElementName = "rasterAttributes", Namespace = "rcmGsProductSchema")] + public class RasterAttributes + { - [XmlElement(ElementName="sampleType", Namespace="rcmGsProductSchema")] - public string SampleType { get; set; } + [XmlElement(ElementName = "sampleType", Namespace = "rcmGsProductSchema")] + public string SampleType { get; set; } - [XmlElement(ElementName="dataType", Namespace="rcmGsProductSchema")] - public string DataType { get; set; } + [XmlElement(ElementName = "dataType", Namespace = "rcmGsProductSchema")] + public string DataType { get; set; } - [XmlElement(ElementName="bitsPerSample", Namespace="rcmGsProductSchema")] - public BitsPerSample BitsPerSample { get; set; } + [XmlElement(ElementName = "bitsPerSample", Namespace = "rcmGsProductSchema")] + public BitsPerSample BitsPerSample { get; set; } - [XmlElement(ElementName="sampledPixelSpacing", Namespace="rcmGsProductSchema")] - public SampledPixelSpacing SampledPixelSpacing { get; set; } + [XmlElement(ElementName = "sampledPixelSpacing", Namespace = "rcmGsProductSchema")] + public SampledPixelSpacing SampledPixelSpacing { get; set; } - [XmlElement(ElementName="sampledLineSpacing", Namespace="rcmGsProductSchema")] - public SampledLineSpacing SampledLineSpacing { get; set; } + [XmlElement(ElementName = "sampledLineSpacing", Namespace = "rcmGsProductSchema")] + public SampledLineSpacing SampledLineSpacing { get; set; } - [XmlElement(ElementName="sampledPixelSpacingTime", Namespace="rcmGsProductSchema")] - public SampledPixelSpacingTime SampledPixelSpacingTime { get; set; } + [XmlElement(ElementName = "sampledPixelSpacingTime", Namespace = "rcmGsProductSchema")] + public SampledPixelSpacingTime SampledPixelSpacingTime { get; set; } - [XmlElement(ElementName="sampledLineSpacingTime", Namespace="rcmGsProductSchema")] - public SampledLineSpacingTime SampledLineSpacingTime { get; set; } + [XmlElement(ElementName = "sampledLineSpacingTime", Namespace = "rcmGsProductSchema")] + public SampledLineSpacingTime SampledLineSpacingTime { get; set; } - [XmlElement(ElementName="lineTimeOrdering", Namespace="rcmGsProductSchema")] - public string LineTimeOrdering { get; set; } + [XmlElement(ElementName = "lineTimeOrdering", Namespace = "rcmGsProductSchema")] + public string LineTimeOrdering { get; set; } - [XmlElement(ElementName="pixelTimeOrdering", Namespace="rcmGsProductSchema")] - public string PixelTimeOrdering { get; set; } -} + [XmlElement(ElementName = "pixelTimeOrdering", Namespace = "rcmGsProductSchema")] + public string PixelTimeOrdering { get; set; } + } -[XmlRoot(ElementName="semiMajorAxis", Namespace="rcmGsProductSchema")] -public class SemiMajorAxis { + [XmlRoot(ElementName = "semiMajorAxis", Namespace = "rcmGsProductSchema")] + public class SemiMajorAxis + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="semiMinorAxis", Namespace="rcmGsProductSchema")] -public class SemiMinorAxis { + [XmlRoot(ElementName = "semiMinorAxis", Namespace = "rcmGsProductSchema")] + public class SemiMinorAxis + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="datumShiftParameters", Namespace="rcmGsProductSchema")] -public class DatumShiftParameters { + [XmlRoot(ElementName = "datumShiftParameters", Namespace = "rcmGsProductSchema")] + public class DatumShiftParameters + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="geodeticTerrainHeight", Namespace="rcmGsProductSchema")] -public class GeodeticTerrainHeight { + [XmlRoot(ElementName = "geodeticTerrainHeight", Namespace = "rcmGsProductSchema")] + public class GeodeticTerrainHeight + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="ellipsoidParameters", Namespace="rcmGsProductSchema")] -public class EllipsoidParameters { + [XmlRoot(ElementName = "ellipsoidParameters", Namespace = "rcmGsProductSchema")] + public class EllipsoidParameters + { - [XmlElement(ElementName="ellipsoidName", Namespace="rcmGsProductSchema")] - public string EllipsoidName { get; set; } + [XmlElement(ElementName = "ellipsoidName", Namespace = "rcmGsProductSchema")] + public string EllipsoidName { get; set; } - [XmlElement(ElementName="semiMajorAxis", Namespace="rcmGsProductSchema")] - public SemiMajorAxis SemiMajorAxis { get; set; } + [XmlElement(ElementName = "semiMajorAxis", Namespace = "rcmGsProductSchema")] + public SemiMajorAxis SemiMajorAxis { get; set; } - [XmlElement(ElementName="semiMinorAxis", Namespace="rcmGsProductSchema")] - public SemiMinorAxis SemiMinorAxis { get; set; } + [XmlElement(ElementName = "semiMinorAxis", Namespace = "rcmGsProductSchema")] + public SemiMinorAxis SemiMinorAxis { get; set; } - [XmlElement(ElementName="datumShiftParameters", Namespace="rcmGsProductSchema")] - public DatumShiftParameters DatumShiftParameters { get; set; } + [XmlElement(ElementName = "datumShiftParameters", Namespace = "rcmGsProductSchema")] + public DatumShiftParameters DatumShiftParameters { get; set; } - [XmlElement(ElementName="geodeticTerrainHeight", Namespace="rcmGsProductSchema")] - public GeodeticTerrainHeight GeodeticTerrainHeight { get; set; } -} + [XmlElement(ElementName = "geodeticTerrainHeight", Namespace = "rcmGsProductSchema")] + public GeodeticTerrainHeight GeodeticTerrainHeight { get; set; } + } -[XmlRoot(ElementName="imageCoordinate", Namespace="rcmGsProductSchema")] -public class ImageCoordinate { + [XmlRoot(ElementName = "imageCoordinate", Namespace = "rcmGsProductSchema")] + public class ImageCoordinate + { - [XmlElement(ElementName="line", Namespace="rcmGsProductSchema")] - public double Line { get; set; } + [XmlElement(ElementName = "line", Namespace = "rcmGsProductSchema")] + public double Line { get; set; } - [XmlElement(ElementName="pixel", Namespace="rcmGsProductSchema")] - public double Pixel { get; set; } -} + [XmlElement(ElementName = "pixel", Namespace = "rcmGsProductSchema")] + public double Pixel { get; set; } + } -[XmlRoot(ElementName="latitude", Namespace="rcmGsProductSchema")] -public class Latitude { + [XmlRoot(ElementName = "latitude", Namespace = "rcmGsProductSchema")] + public class Latitude + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="longitude", Namespace="rcmGsProductSchema")] -public class Longitude { + [XmlRoot(ElementName = "longitude", Namespace = "rcmGsProductSchema")] + public class Longitude + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="height", Namespace="rcmGsProductSchema")] -public class Height { + [XmlRoot(ElementName = "height", Namespace = "rcmGsProductSchema")] + public class Height + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="geodeticCoordinate", Namespace="rcmGsProductSchema")] -public class GeodeticCoordinate { + [XmlRoot(ElementName = "geodeticCoordinate", Namespace = "rcmGsProductSchema")] + public class GeodeticCoordinate + { - [XmlElement(ElementName="latitude", Namespace="rcmGsProductSchema")] - public Latitude Latitude { get; set; } + [XmlElement(ElementName = "latitude", Namespace = "rcmGsProductSchema")] + public Latitude Latitude { get; set; } - [XmlElement(ElementName="longitude", Namespace="rcmGsProductSchema")] - public Longitude Longitude { get; set; } + [XmlElement(ElementName = "longitude", Namespace = "rcmGsProductSchema")] + public Longitude Longitude { get; set; } - [XmlElement(ElementName="height", Namespace="rcmGsProductSchema")] - public Height Height { get; set; } -} + [XmlElement(ElementName = "height", Namespace = "rcmGsProductSchema")] + public Height Height { get; set; } + } -[XmlRoot(ElementName="imageTiePoint", Namespace="rcmGsProductSchema")] -public class ImageTiePoint { + [XmlRoot(ElementName = "imageTiePoint", Namespace = "rcmGsProductSchema")] + public class ImageTiePoint + { - [XmlElement(ElementName="imageCoordinate", Namespace="rcmGsProductSchema")] - public ImageCoordinate ImageCoordinate { get; set; } + [XmlElement(ElementName = "imageCoordinate", Namespace = "rcmGsProductSchema")] + public ImageCoordinate ImageCoordinate { get; set; } - [XmlElement(ElementName="geodeticCoordinate", Namespace="rcmGsProductSchema")] - public GeodeticCoordinate GeodeticCoordinate { get; set; } -} + [XmlElement(ElementName = "geodeticCoordinate", Namespace = "rcmGsProductSchema")] + public GeodeticCoordinate GeodeticCoordinate { get; set; } + } -[XmlRoot(ElementName="geolocationGrid", Namespace="rcmGsProductSchema")] -public class GeolocationGrid { + [XmlRoot(ElementName = "geolocationGrid", Namespace = "rcmGsProductSchema")] + public class GeolocationGrid + { - [XmlElement(ElementName="imageTiePoint", Namespace="rcmGsProductSchema")] - public List ImageTiePoint { get; set; } -} + [XmlElement(ElementName = "imageTiePoint", Namespace = "rcmGsProductSchema")] + public List ImageTiePoint { get; set; } + } -[XmlRoot(ElementName="biasError", Namespace="rcmGsProductSchema")] -public class BiasError { + [XmlRoot(ElementName = "biasError", Namespace = "rcmGsProductSchema")] + public class BiasError + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="randomError", Namespace="rcmGsProductSchema")] -public class RandomError { + [XmlRoot(ElementName = "randomError", Namespace = "rcmGsProductSchema")] + public class RandomError + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="latitudeOffset", Namespace="rcmGsProductSchema")] -public class LatitudeOffset { + [XmlRoot(ElementName = "latitudeOffset", Namespace = "rcmGsProductSchema")] + public class LatitudeOffset + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="longitudeOffset", Namespace="rcmGsProductSchema")] -public class LongitudeOffset { + [XmlRoot(ElementName = "longitudeOffset", Namespace = "rcmGsProductSchema")] + public class LongitudeOffset + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="heightOffset", Namespace="rcmGsProductSchema")] -public class HeightOffset { + [XmlRoot(ElementName = "heightOffset", Namespace = "rcmGsProductSchema")] + public class HeightOffset + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="rationalFunctions", Namespace="rcmGsProductSchema")] -public class RationalFunctions { + [XmlRoot(ElementName = "rationalFunctions", Namespace = "rcmGsProductSchema")] + public class RationalFunctions + { - [XmlElement(ElementName="biasError", Namespace="rcmGsProductSchema")] - public BiasError BiasError { get; set; } + [XmlElement(ElementName = "biasError", Namespace = "rcmGsProductSchema")] + public BiasError BiasError { get; set; } - [XmlElement(ElementName="randomError", Namespace="rcmGsProductSchema")] - public RandomError RandomError { get; set; } + [XmlElement(ElementName = "randomError", Namespace = "rcmGsProductSchema")] + public RandomError RandomError { get; set; } - [XmlElement(ElementName="lineFitQuality", Namespace="rcmGsProductSchema")] - public double LineFitQuality { get; set; } + [XmlElement(ElementName = "lineFitQuality", Namespace = "rcmGsProductSchema")] + public double LineFitQuality { get; set; } - [XmlElement(ElementName="pixelFitQuality", Namespace="rcmGsProductSchema")] - public double PixelFitQuality { get; set; } + [XmlElement(ElementName = "pixelFitQuality", Namespace = "rcmGsProductSchema")] + public double PixelFitQuality { get; set; } - [XmlElement(ElementName="lineOffset", Namespace="rcmGsProductSchema")] - public int LineOffset { get; set; } + [XmlElement(ElementName = "lineOffset", Namespace = "rcmGsProductSchema")] + public int LineOffset { get; set; } - [XmlElement(ElementName="pixelOffset", Namespace="rcmGsProductSchema")] - public int PixelOffset { get; set; } + [XmlElement(ElementName = "pixelOffset", Namespace = "rcmGsProductSchema")] + public int PixelOffset { get; set; } - [XmlElement(ElementName="latitudeOffset", Namespace="rcmGsProductSchema")] - public LatitudeOffset LatitudeOffset { get; set; } + [XmlElement(ElementName = "latitudeOffset", Namespace = "rcmGsProductSchema")] + public LatitudeOffset LatitudeOffset { get; set; } - [XmlElement(ElementName="longitudeOffset", Namespace="rcmGsProductSchema")] - public LongitudeOffset LongitudeOffset { get; set; } + [XmlElement(ElementName = "longitudeOffset", Namespace = "rcmGsProductSchema")] + public LongitudeOffset LongitudeOffset { get; set; } - [XmlElement(ElementName="heightOffset", Namespace="rcmGsProductSchema")] - public HeightOffset HeightOffset { get; set; } + [XmlElement(ElementName = "heightOffset", Namespace = "rcmGsProductSchema")] + public HeightOffset HeightOffset { get; set; } - [XmlElement(ElementName="lineScale", Namespace="rcmGsProductSchema")] - public int LineScale { get; set; } + [XmlElement(ElementName = "lineScale", Namespace = "rcmGsProductSchema")] + public int LineScale { get; set; } - [XmlElement(ElementName="pixelScale", Namespace="rcmGsProductSchema")] - public int PixelScale { get; set; } + [XmlElement(ElementName = "pixelScale", Namespace = "rcmGsProductSchema")] + public int PixelScale { get; set; } - [XmlElement(ElementName="latitudeScale", Namespace="rcmGsProductSchema")] - public double LatitudeScale { get; set; } + [XmlElement(ElementName = "latitudeScale", Namespace = "rcmGsProductSchema")] + public double LatitudeScale { get; set; } - [XmlElement(ElementName="longitudeScale", Namespace="rcmGsProductSchema")] - public double LongitudeScale { get; set; } + [XmlElement(ElementName = "longitudeScale", Namespace = "rcmGsProductSchema")] + public double LongitudeScale { get; set; } - [XmlElement(ElementName="heightScale", Namespace="rcmGsProductSchema")] - public double HeightScale { get; set; } + [XmlElement(ElementName = "heightScale", Namespace = "rcmGsProductSchema")] + public double HeightScale { get; set; } - [XmlElement(ElementName="lineNumeratorCoefficients", Namespace="rcmGsProductSchema")] - public string LineNumeratorCoefficients { get; set; } + [XmlElement(ElementName = "lineNumeratorCoefficients", Namespace = "rcmGsProductSchema")] + public string LineNumeratorCoefficients { get; set; } - [XmlElement(ElementName="lineDenominatorCoefficients", Namespace="rcmGsProductSchema")] - public string LineDenominatorCoefficients { get; set; } + [XmlElement(ElementName = "lineDenominatorCoefficients", Namespace = "rcmGsProductSchema")] + public string LineDenominatorCoefficients { get; set; } - [XmlElement(ElementName="pixelNumeratorCoefficients", Namespace="rcmGsProductSchema")] - public string PixelNumeratorCoefficients { get; set; } + [XmlElement(ElementName = "pixelNumeratorCoefficients", Namespace = "rcmGsProductSchema")] + public string PixelNumeratorCoefficients { get; set; } - [XmlElement(ElementName="pixelDenominatorCoefficients", Namespace="rcmGsProductSchema")] - public string PixelDenominatorCoefficients { get; set; } -} + [XmlElement(ElementName = "pixelDenominatorCoefficients", Namespace = "rcmGsProductSchema")] + public string PixelDenominatorCoefficients { get; set; } + } -[XmlRoot(ElementName="geographicInformation", Namespace="rcmGsProductSchema")] -public class GeographicInformation { + [XmlRoot(ElementName = "geographicInformation", Namespace = "rcmGsProductSchema")] + public class GeographicInformation + { - [XmlElement(ElementName="ellipsoidParameters", Namespace="rcmGsProductSchema")] - public EllipsoidParameters EllipsoidParameters { get; set; } + [XmlElement(ElementName = "ellipsoidParameters", Namespace = "rcmGsProductSchema")] + public EllipsoidParameters EllipsoidParameters { get; set; } - [XmlElement(ElementName="geolocationGrid", Namespace="rcmGsProductSchema")] - public GeolocationGrid GeolocationGrid { get; set; } + [XmlElement(ElementName = "geolocationGrid", Namespace = "rcmGsProductSchema")] + public GeolocationGrid GeolocationGrid { get; set; } - [XmlElement(ElementName="rationalFunctions", Namespace="rcmGsProductSchema")] - public RationalFunctions RationalFunctions { get; set; } + [XmlElement(ElementName = "rationalFunctions", Namespace = "rcmGsProductSchema")] + public RationalFunctions RationalFunctions { get; set; } - [XmlElement(ElementName="mapProjection", Namespace="rcmGsProductSchema")] - public MapProjection mapProjection { get; set; } -} + [XmlElement(ElementName = "mapProjection", Namespace = "rcmGsProductSchema")] + public MapProjection mapProjection { get; set; } + } -[XmlRoot(ElementName="mapProjection", Namespace="rcmGsProductSchema")] -public class MapProjection { + [XmlRoot(ElementName = "mapProjection", Namespace = "rcmGsProductSchema")] + public class MapProjection + { - [XmlElement(ElementName="utmProjectionParameters", Namespace="rcmGsProductSchema")] - public UtmProjectionParameters utmProjectionParameters { get; set; } -} + [XmlElement(ElementName = "utmProjectionParameters", Namespace = "rcmGsProductSchema")] + public UtmProjectionParameters utmProjectionParameters { get; set; } + } -[XmlRoot(ElementName="utmProjectionParameters", Namespace="rcmGsProductSchema")] -public class UtmProjectionParameters { + [XmlRoot(ElementName = "utmProjectionParameters", Namespace = "rcmGsProductSchema")] + public class UtmProjectionParameters + { - [XmlElement(ElementName="utmZone", Namespace="rcmGsProductSchema")] - public int utmZone { get; set; } + [XmlElement(ElementName = "utmZone", Namespace = "rcmGsProductSchema")] + public int utmZone { get; set; } - [XmlElement(ElementName="hemisphere", Namespace="rcmGsProductSchema")] - public string hemisphere { get; set; } -} + [XmlElement(ElementName = "hemisphere", Namespace = "rcmGsProductSchema")] + public string hemisphere { get; set; } + } -[XmlRoot(ElementName="imageReferenceAttributes", Namespace="rcmGsProductSchema")] -public class ImageReferenceAttributes { + [XmlRoot(ElementName = "imageReferenceAttributes", Namespace = "rcmGsProductSchema")] + public class ImageReferenceAttributes + { - [XmlElement(ElementName="productFormat", Namespace="rcmGsProductSchema")] - public string ProductFormat { get; set; } + [XmlElement(ElementName = "productFormat", Namespace = "rcmGsProductSchema")] + public string ProductFormat { get; set; } - [XmlElement(ElementName="outputMediaInterleaving", Namespace="rcmGsProductSchema")] - public string OutputMediaInterleaving { get; set; } + [XmlElement(ElementName = "outputMediaInterleaving", Namespace = "rcmGsProductSchema")] + public string OutputMediaInterleaving { get; set; } - [XmlElement(ElementName="lookupTableFileName", Namespace="rcmGsProductSchema")] - public List LookupTableFileName { get; set; } + [XmlElement(ElementName = "lookupTableFileName", Namespace = "rcmGsProductSchema")] + public List LookupTableFileName { get; set; } - [XmlElement(ElementName="incidenceAngleFileName", Namespace="rcmGsProductSchema")] - public string IncidenceAngleFileName { get; set; } + [XmlElement(ElementName = "incidenceAngleFileName", Namespace = "rcmGsProductSchema")] + public string IncidenceAngleFileName { get; set; } - [XmlElement(ElementName="noiseLevelFileName", Namespace="rcmGsProductSchema")] - public List NoiseLevelFileName { get; set; } + [XmlElement(ElementName = "noiseLevelFileName", Namespace = "rcmGsProductSchema")] + public List NoiseLevelFileName { get; set; } - [XmlElement(ElementName="rasterAttributes", Namespace="rcmGsProductSchema")] - public RasterAttributes RasterAttributes { get; set; } + [XmlElement(ElementName = "rasterAttributes", Namespace = "rcmGsProductSchema")] + public RasterAttributes RasterAttributes { get; set; } - [XmlElement(ElementName="geographicInformation", Namespace="rcmGsProductSchema")] - public GeographicInformation GeographicInformation { get; set; } -} + [XmlElement(ElementName = "geographicInformation", Namespace = "rcmGsProductSchema")] + public GeographicInformation GeographicInformation { get; set; } + } -[XmlRoot(ElementName="ipdf", Namespace="rcmGsProductSchema")] -public class Ipdf { + [XmlRoot(ElementName = "ipdf", Namespace = "rcmGsProductSchema")] + public class Ipdf + { - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="incAngNearRng", Namespace="rcmGsProductSchema")] -public class IncAngNearRng { + [XmlRoot(ElementName = "incAngNearRng", Namespace = "rcmGsProductSchema")] + public class IncAngNearRng + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="incAngFarRng", Namespace="rcmGsProductSchema")] -public class IncAngFarRng { + [XmlRoot(ElementName = "incAngFarRng", Namespace = "rcmGsProductSchema")] + public class IncAngFarRng + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="slantRangeNearEdge", Namespace="rcmGsProductSchema")] -public class SlantRangeNearEdge { + [XmlRoot(ElementName = "slantRangeNearEdge", Namespace = "rcmGsProductSchema")] + public class SlantRangeNearEdge + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="slantRangeFarEdge", Namespace="rcmGsProductSchema")] -public class SlantRangeFarEdge { + [XmlRoot(ElementName = "slantRangeFarEdge", Namespace = "rcmGsProductSchema")] + public class SlantRangeFarEdge + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="mean", Namespace="rcmGsProductSchema")] -public class Mean { + [XmlRoot(ElementName = "mean", Namespace = "rcmGsProductSchema")] + public class Mean + { - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="sigma", Namespace="rcmGsProductSchema")] -public class Sigma { + [XmlRoot(ElementName = "sigma", Namespace = "rcmGsProductSchema")] + public class Sigma + { - [XmlAttribute(AttributeName="pole", Namespace="")] - public string Pole { get; set; } + [XmlAttribute(AttributeName = "pole", Namespace = "")] + public string Pole { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="imageAttributes", Namespace="rcmGsProductSchema")] -public class ImageAttributes { + [XmlRoot(ElementName = "imageAttributes", Namespace = "rcmGsProductSchema")] + public class ImageAttributes + { - [XmlElement(ElementName="ipdf", Namespace="rcmGsProductSchema")] - public List Ipdf { get; set; } + [XmlElement(ElementName = "ipdf", Namespace = "rcmGsProductSchema")] + public List Ipdf { get; set; } - [XmlElement(ElementName="pixelOffset", Namespace="rcmGsProductSchema")] - public int PixelOffset { get; set; } + [XmlElement(ElementName = "pixelOffset", Namespace = "rcmGsProductSchema")] + public int PixelOffset { get; set; } - [XmlElement(ElementName="lineOffset", Namespace="rcmGsProductSchema")] - public int LineOffset { get; set; } + [XmlElement(ElementName = "lineOffset", Namespace = "rcmGsProductSchema")] + public int LineOffset { get; set; } - [XmlElement(ElementName="numLines", Namespace="rcmGsProductSchema")] - public int NumLines { get; set; } + [XmlElement(ElementName = "numLines", Namespace = "rcmGsProductSchema")] + public int NumLines { get; set; } - [XmlElement(ElementName="samplesPerLine", Namespace="rcmGsProductSchema")] - public int SamplesPerLine { get; set; } + [XmlElement(ElementName = "samplesPerLine", Namespace = "rcmGsProductSchema")] + public int SamplesPerLine { get; set; } - [XmlElement(ElementName="incAngNearRng", Namespace="rcmGsProductSchema")] - public IncAngNearRng IncAngNearRng { get; set; } + [XmlElement(ElementName = "incAngNearRng", Namespace = "rcmGsProductSchema")] + public IncAngNearRng IncAngNearRng { get; set; } - [XmlElement(ElementName="incAngFarRng", Namespace="rcmGsProductSchema")] - public IncAngFarRng IncAngFarRng { get; set; } + [XmlElement(ElementName = "incAngFarRng", Namespace = "rcmGsProductSchema")] + public IncAngFarRng IncAngFarRng { get; set; } - [XmlElement(ElementName="slantRangeNearEdge", Namespace="rcmGsProductSchema")] - public SlantRangeNearEdge SlantRangeNearEdge { get; set; } + [XmlElement(ElementName = "slantRangeNearEdge", Namespace = "rcmGsProductSchema")] + public SlantRangeNearEdge SlantRangeNearEdge { get; set; } - [XmlElement(ElementName="slantRangeFarEdge", Namespace="rcmGsProductSchema")] - public SlantRangeFarEdge SlantRangeFarEdge { get; set; } + [XmlElement(ElementName = "slantRangeFarEdge", Namespace = "rcmGsProductSchema")] + public SlantRangeFarEdge SlantRangeFarEdge { get; set; } - [XmlElement(ElementName="mean", Namespace="rcmGsProductSchema")] - public List Mean { get; set; } + [XmlElement(ElementName = "mean", Namespace = "rcmGsProductSchema")] + public List Mean { get; set; } - [XmlElement(ElementName="sigma", Namespace="rcmGsProductSchema")] - public List Sigma { get; set; } + [XmlElement(ElementName = "sigma", Namespace = "rcmGsProductSchema")] + public List Sigma { get; set; } - [XmlAttribute(AttributeName="sampleType", Namespace="")] - public string SampleType { get; set; } + [XmlAttribute(AttributeName = "sampleType", Namespace = "")] + public string SampleType { get; set; } - [XmlAttribute(AttributeName="beam", Namespace="")] - public string Beam { get; set; } + [XmlAttribute(AttributeName = "beam", Namespace = "")] + public string Beam { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="sceneAttributes", Namespace="rcmGsProductSchema")] -public class SceneAttributes { + [XmlRoot(ElementName = "sceneAttributes", Namespace = "rcmGsProductSchema")] + public class SceneAttributes + { - [XmlElement(ElementName="numberOfEntries", Namespace="rcmGsProductSchema")] - public int NumberOfEntries { get; set; } + [XmlElement(ElementName = "numberOfEntries", Namespace = "rcmGsProductSchema")] + public int NumberOfEntries { get; set; } - [XmlElement(ElementName="imageAttributes", Namespace="rcmGsProductSchema")] - public ImageAttributes ImageAttributes { get; set; } -} + [XmlElement(ElementName = "imageAttributes", Namespace = "rcmGsProductSchema")] + public ImageAttributes ImageAttributes { get; set; } + } -[XmlRoot(ElementName="dopplerCentroidReferenceTime", Namespace="rcmGsProductSchema")] -public class DopplerCentroidReferenceTime { + [XmlRoot(ElementName = "dopplerCentroidReferenceTime", Namespace = "rcmGsProductSchema")] + public class DopplerCentroidReferenceTime + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="dopplerCentroidEstimate", Namespace="rcmGsProductSchema")] -public class DopplerCentroidEstimate { + [XmlRoot(ElementName = "dopplerCentroidEstimate", Namespace = "rcmGsProductSchema")] + public class DopplerCentroidEstimate + { - [XmlElement(ElementName="timeOfDopplerCentroidEstimate", Namespace="rcmGsProductSchema")] - public DateTime TimeOfDopplerCentroidEstimate { get; set; } + [XmlElement(ElementName = "timeOfDopplerCentroidEstimate", Namespace = "rcmGsProductSchema")] + public DateTime TimeOfDopplerCentroidEstimate { get; set; } - [XmlElement(ElementName="dopplerAmbiguity", Namespace="rcmGsProductSchema")] - public int DopplerAmbiguity { get; set; } + [XmlElement(ElementName = "dopplerAmbiguity", Namespace = "rcmGsProductSchema")] + public int DopplerAmbiguity { get; set; } - [XmlElement(ElementName="dopplerCentroidReferenceTime", Namespace="rcmGsProductSchema")] - public DopplerCentroidReferenceTime DopplerCentroidReferenceTime { get; set; } + [XmlElement(ElementName = "dopplerCentroidReferenceTime", Namespace = "rcmGsProductSchema")] + public DopplerCentroidReferenceTime DopplerCentroidReferenceTime { get; set; } - [XmlElement(ElementName="dopplerCentroidCoefficients", Namespace="rcmGsProductSchema")] - public string DopplerCentroidCoefficients { get; set; } + [XmlElement(ElementName = "dopplerCentroidCoefficients", Namespace = "rcmGsProductSchema")] + public string DopplerCentroidCoefficients { get; set; } - [XmlElement(ElementName="dopplerCentroidConfidence", Namespace="rcmGsProductSchema")] - public double DopplerCentroidConfidence { get; set; } -} + [XmlElement(ElementName = "dopplerCentroidConfidence", Namespace = "rcmGsProductSchema")] + public double DopplerCentroidConfidence { get; set; } + } -[XmlRoot(ElementName="dopplerCentroid", Namespace="rcmGsProductSchema")] -public class DopplerCentroid { + [XmlRoot(ElementName = "dopplerCentroid", Namespace = "rcmGsProductSchema")] + public class DopplerCentroid + { - [XmlElement(ElementName="numberOfEstimates", Namespace="rcmGsProductSchema")] - public int NumberOfEstimates { get; set; } + [XmlElement(ElementName = "numberOfEstimates", Namespace = "rcmGsProductSchema")] + public int NumberOfEstimates { get; set; } - [XmlElement(ElementName="dopplerCentroidEstimate", Namespace="rcmGsProductSchema")] - public DopplerCentroidEstimate DopplerCentroidEstimate { get; set; } -} + [XmlElement(ElementName = "dopplerCentroidEstimate", Namespace = "rcmGsProductSchema")] + public DopplerCentroidEstimate DopplerCentroidEstimate { get; set; } + } -[XmlRoot(ElementName="dopplerRateReferenceTime", Namespace="rcmGsProductSchema")] -public class DopplerRateReferenceTime { + [XmlRoot(ElementName = "dopplerRateReferenceTime", Namespace = "rcmGsProductSchema")] + public class DopplerRateReferenceTime + { - [XmlAttribute(AttributeName="units", Namespace="")] - public string Units { get; set; } + [XmlAttribute(AttributeName = "units", Namespace = "")] + public string Units { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } -[XmlRoot(ElementName="dopplerRateEstimate", Namespace="rcmGsProductSchema")] -public class DopplerRateEstimate { + [XmlRoot(ElementName = "dopplerRateEstimate", Namespace = "rcmGsProductSchema")] + public class DopplerRateEstimate + { - [XmlElement(ElementName="timeOfDopplerRateEstimate", Namespace="rcmGsProductSchema")] - public DateTime TimeOfDopplerRateEstimate { get; set; } + [XmlElement(ElementName = "timeOfDopplerRateEstimate", Namespace = "rcmGsProductSchema")] + public DateTime TimeOfDopplerRateEstimate { get; set; } - [XmlElement(ElementName="dopplerRateReferenceTime", Namespace="rcmGsProductSchema")] - public DopplerRateReferenceTime DopplerRateReferenceTime { get; set; } + [XmlElement(ElementName = "dopplerRateReferenceTime", Namespace = "rcmGsProductSchema")] + public DopplerRateReferenceTime DopplerRateReferenceTime { get; set; } - [XmlElement(ElementName="dopplerRateCoefficients", Namespace="rcmGsProductSchema")] - public string DopplerRateCoefficients { get; set; } -} + [XmlElement(ElementName = "dopplerRateCoefficients", Namespace = "rcmGsProductSchema")] + public string DopplerRateCoefficients { get; set; } + } -[XmlRoot(ElementName="dopplerRate", Namespace="rcmGsProductSchema")] -public class DopplerRate { + [XmlRoot(ElementName = "dopplerRate", Namespace = "rcmGsProductSchema")] + public class DopplerRate + { - [XmlElement(ElementName="numberOfEstimates", Namespace="rcmGsProductSchema")] - public int NumberOfEstimates { get; set; } + [XmlElement(ElementName = "numberOfEstimates", Namespace = "rcmGsProductSchema")] + public int NumberOfEstimates { get; set; } - [XmlElement(ElementName="dopplerRateEstimate", Namespace="rcmGsProductSchema")] - public DopplerRateEstimate DopplerRateEstimate { get; set; } -} + [XmlElement(ElementName = "dopplerRateEstimate", Namespace = "rcmGsProductSchema")] + public DopplerRateEstimate DopplerRateEstimate { get; set; } + } -[XmlRoot(ElementName="product", Namespace="rcmGsProductSchema")] -public class Product { + [XmlRoot(ElementName = "product", Namespace = "rcmGsProductSchema")] + public class Product + { - [XmlElement(ElementName="productId", Namespace="rcmGsProductSchema")] - public string ProductId { get; set; } + [XmlElement(ElementName = "productId", Namespace = "rcmGsProductSchema")] + public string ProductId { get; set; } - [XmlElement(ElementName="productAnnotation", Namespace="rcmGsProductSchema")] - public string ProductAnnotation { get; set; } + [XmlElement(ElementName = "productAnnotation", Namespace = "rcmGsProductSchema")] + public string ProductAnnotation { get; set; } - [XmlElement(ElementName="productApplication", Namespace="rcmGsProductSchema")] - public string ProductApplication { get; set; } + [XmlElement(ElementName = "productApplication", Namespace = "rcmGsProductSchema")] + public string ProductApplication { get; set; } - [XmlElement(ElementName="documentIdentifier", Namespace="rcmGsProductSchema")] - public string DocumentIdentifier { get; set; } + [XmlElement(ElementName = "documentIdentifier", Namespace = "rcmGsProductSchema")] + public string DocumentIdentifier { get; set; } - [XmlElement(ElementName="securityAttributes", Namespace="rcmGsProductSchema")] - public SecurityAttributes SecurityAttributes { get; set; } + [XmlElement(ElementName = "securityAttributes", Namespace = "rcmGsProductSchema")] + public SecurityAttributes SecurityAttributes { get; set; } - [XmlElement(ElementName="sourceAttributes", Namespace="rcmGsProductSchema")] - public SourceAttributes SourceAttributes { get; set; } + [XmlElement(ElementName = "sourceAttributes", Namespace = "rcmGsProductSchema")] + public SourceAttributes SourceAttributes { get; set; } - [XmlElement(ElementName="imageGenerationParameters", Namespace="rcmGsProductSchema")] - public ImageGenerationParameters ImageGenerationParameters { get; set; } + [XmlElement(ElementName = "imageGenerationParameters", Namespace = "rcmGsProductSchema")] + public ImageGenerationParameters ImageGenerationParameters { get; set; } - [XmlElement(ElementName="imageReferenceAttributes", Namespace="rcmGsProductSchema")] - public ImageReferenceAttributes ImageReferenceAttributes { get; set; } + [XmlElement(ElementName = "imageReferenceAttributes", Namespace = "rcmGsProductSchema")] + public ImageReferenceAttributes ImageReferenceAttributes { get; set; } - [XmlElement(ElementName="sceneAttributes", Namespace="rcmGsProductSchema")] - public SceneAttributes SceneAttributes { get; set; } + [XmlElement(ElementName = "sceneAttributes", Namespace = "rcmGsProductSchema")] + public SceneAttributes SceneAttributes { get; set; } - [XmlElement(ElementName="dopplerCentroid", Namespace="rcmGsProductSchema")] - public DopplerCentroid DopplerCentroid { get; set; } + [XmlElement(ElementName = "dopplerCentroid", Namespace = "rcmGsProductSchema")] + public DopplerCentroid DopplerCentroid { get; set; } - [XmlElement(ElementName="dopplerRate", Namespace="rcmGsProductSchema")] - public DopplerRate DopplerRate { get; set; } + [XmlElement(ElementName = "dopplerRate", Namespace = "rcmGsProductSchema")] + public DopplerRate DopplerRate { get; set; } - [XmlAttribute(AttributeName="xmlns", Namespace="")] - public string Xmlns { get; set; } + [XmlAttribute(AttributeName = "xmlns", Namespace = "")] + public string Xmlns { get; set; } - [XmlAttribute(AttributeName="copyright", Namespace="")] - public string Copyright { get; set; } + [XmlAttribute(AttributeName = "copyright", Namespace = "")] + public string Copyright { get; set; } - [XmlAttribute(AttributeName="xsi", Namespace="http://www.w3.org/2000/xmlns/")] - public string Xsi { get; set; } + [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")] + public string Xsi { get; set; } - [XmlAttribute(AttributeName="schemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")] - public string SchemaLocation { get; set; } + [XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")] + public string SchemaLocation { get; set; } - [XmlText] - public string Text { get; set; } -} + [XmlText] + public string Text { get; set; } + } @@ -1554,16 +1656,16 @@ public class BEAM_MODE public const string MEDIUM_RESOLUTION_16 = "Medium Resolution 16 m"; public const string HIGH_RESOLUTION_5 = "High Resolution 5 m"; public const string VERY_HIGH_RESOLUTION_3 = "Very High Resolution 3 m"; - public const string LOW_NOISE = "Low Noise"; - public const string SHIP_DETECTION = "Ship Detection"; - public const string SPOTLIGHT = "Spotlight"; - public const string QUAD_POLARIZATION = "Quad-Polarization"; + public const string LOW_NOISE = "Low Noise"; + public const string SHIP_DETECTION = "Ship Detection"; + public const string SPOTLIGHT = "Spotlight"; + public const string QUAD_POLARIZATION = "Quad-Polarization"; } - public class ORBIT_STATE - { - public const string ASCENDING = "Ascending"; + public class ORBIT_STATE + { + public const string ASCENDING = "Ascending"; public const string DESCENDING = "Descending"; - } + } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/RCM/RcmMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/RCM/RcmMetadataExtractor.cs index 185b05a8..83521326 100644 --- a/src/Stars.Data/Model/Metadata/RCM/RcmMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/RCM/RcmMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -16,12 +16,12 @@ using Stac.Extensions.Sar; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Data.Model.Shared; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; using Terradue.Stars.Services.Plugins; -using Terradue.Stars.Geometry.GeoJson; -using Terradue.Stars.Data.Model.Shared; namespace Terradue.Stars.Data.Model.Metadata.Rcm { @@ -51,9 +51,9 @@ protected override async Task ExtractMetadata(IItem item, string suffi IAsset kmlFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(mapOverlay.kml)$"); if (auxFile == null) { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); + throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); } - logger.LogDebug(String.Format("Metadata file is {0}", auxFile.Uri)); + logger.LogDebug(string.Format("Metadata file is {0}", auxFile.Uri)); IStreamResource auxFileStreamable = await resourceServiceProvider.GetStreamResourceAsync(auxFile, System.Threading.CancellationToken.None); if (auxFileStreamable == null) @@ -162,7 +162,7 @@ private void AddOtherProperties(Product auxiliary, StacItem stacItem) { AddSingleProvider( stacItem.Properties, - "CSA", + "CSA", "The RADARSAT Constellation Mission (RCM) is Canada's new generation of Earth observation satellites. The RCM uses a trio of satellites to take daily scans of the country and its waters.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.asc-csa.gc.ca/eng/satellites/radarsat/what-is-rcm.asp") @@ -248,9 +248,12 @@ private string GetInstrumentMode(Product auxiliary) //That since the beginning to the (eventual) first letter after the number group string inputString = auxiliary.SourceAttributes.BeamModeMnemonic; Match match = Regex.Match(inputString, @"^([^0-9]*\d+[^A-Za-z]*[A-Za-z]?)|([^0-9]+)"); - if (match.Success) { + if (match.Success) + { return match.Groups[1].Value != "" ? match.Groups[1].Value : match.Groups[2].Value; - } else { + } + else + { return inputString; } } @@ -385,7 +388,7 @@ private void FillDateTimeProperties(Product auxiliary, Dictionary properties) + private void FillBasicsProperties(Product auxiliary, IDictionary properties) { // title properties.Remove("title"); @@ -394,7 +397,7 @@ private void FillBasicsProperties(Product auxiliary, IDictionary protected string GetTitle(Product auxiliary, IDictionary properties) { - return string.Format("{0} {1} {2} {3}", + return string.Format("{0} {1} {2} {3}", //StylePlatform(properties.GetProperty("platform")), properties.GetProperty("platform").ToUpper(), GetProductType(auxiliary), @@ -466,8 +469,7 @@ public static async Task DeserializeKml(IStreamResource auxiliaryFile) public override bool CanProcess(IResource route, IDestination destinations) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; IAsset auxFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(product.xml)$"); try { @@ -488,4 +490,4 @@ public override bool CanProcess(IResource route, IDestination destinations) } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Resursp/ResurspMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Resursp/ResurspMetadataExtractor.cs index 0274dfe5..81812038 100644 --- a/src/Stars.Data/Model/Metadata/Resursp/ResurspMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Resursp/ResurspMetadataExtractor.cs @@ -21,37 +21,45 @@ using Terradue.Stars.Services.Model.Stac; using Polygon = GeoJSON.Net.Geometry.Polygon; -namespace Terradue.Stars.Data.Model.Metadata.Resursp { - public class ResurspMetadataExtractor : MetadataExtraction { +namespace Terradue.Stars.Data.Model.Metadata.Resursp +{ + public class ResurspMetadataExtractor : MetadataExtraction + { public override string Label => "Resursp (Roscosmos) missions product metadata extractor"; private readonly string GDALFILE_REGEX = @".*\.(shp)$"; - public ResurspMetadataExtractor(ILogger logger, IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) { + public ResurspMetadataExtractor(ILogger logger, IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) + { } - public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + public override bool CanProcess(IResource route, IDestination destination) + { + if (!(route is IItem item)) return false; IAsset metadataFile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(\\.xml)$"); - if (metadataFile == null) { + if (metadataFile == null) + { return false; } // deserialize product medatadata SPP_ROOT productMetadata = DeserializeProductMetadata(resourceServiceProvider.GetStreamResourceAsync(metadataFile, System.Threading.CancellationToken.None).GetAwaiter().GetResult()).GetAwaiter().GetResult(); - if (productMetadata == null) { + if (productMetadata == null) + { return false; } return true; } - public static async Task DeserializeProductMetadata(IStreamResource productMetadataFile) { + public static async Task DeserializeProductMetadata(IStreamResource productMetadataFile) + { XmlSerializer ser = new XmlSerializer(typeof(SPP_ROOT)); SPP_ROOT auxiliary; - using (var stream = new StreamReader(productMetadataFile.Uri.AbsolutePath, Encoding.UTF8, true)) { - using (XmlReader reader = XmlReader.Create(stream)) { + using (var stream = new StreamReader(productMetadataFile.Uri.AbsolutePath, Encoding.UTF8, true)) + { + using (XmlReader reader = XmlReader.Create(stream)) + { auxiliary = (SPP_ROOT)ser.Deserialize(reader); } } @@ -60,28 +68,23 @@ public static async Task DeserializeProductMetadata(IStreamResource pr } - protected override async Task ExtractMetadata(IItem item, string suffix) { + protected override async Task ExtractMetadata(IItem item, string suffix) + { logger.LogDebug("Retrieving the metadata files in the product package"); - IAsset metadatafile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(\\.xml)$"); - if (metadatafile == null) { - throw new FileNotFoundException("Unable to find any metadata file asset"); - } + IAsset metadatafile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(\\.xml)$") ?? throw new FileNotFoundException("Unable to find any metadata file asset"); // deserialize product medatadata SPP_ROOT productMetadata = await DeserializeProductMetadata(await resourceServiceProvider.GetStreamResourceAsync(metadatafile, System.Threading.CancellationToken.None)); logger.LogDebug("Retrieving the shapefile in the product package"); - IAsset shapefile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(\\.shp)$"); - if (shapefile == null) { - throw new FileNotFoundException("Unable to find any shapefile asset"); - } + IAsset shapefile = FindFirstAssetFromFileNameRegex(item, "[0-9a-zA-Z_-]*(\\.shp)$") ?? throw new FileNotFoundException("Unable to find any shapefile asset"); // retrieving id from filename // GF2_PMS1_W91.0_N17.6_20200510_L1A0004793969-MSS1.xml string stacItemId = Path.GetFileNameWithoutExtension(metadatafile.Uri.OriginalString).Split('-')[0]; // retrieve lowest gsd - double gsd = Double.Parse(productMetadata.Normal.NPixelImg); + double gsd = double.Parse(productMetadata.Normal.NPixelImg); // to retrieve the properties, any product metadata is ok var stacItem = GetStacItemWithProperties(productMetadata, stacItemId, gsd, shapefile); @@ -94,12 +97,11 @@ protected override async Task ExtractMetadata(IItem item, string suffi return StacItemNode.Create(stacItem, item.Uri); } - private GeoJSON.Net.Geometry.IGeometryObject GetGeometryFromShpFileAsset(IAsset shapeFileAsset) { + private GeoJSON.Net.Geometry.IGeometryObject GetGeometryFromShpFileAsset(IAsset shapeFileAsset) + { // load the shapefile in a datasource var shapefilePath = shapeFileAsset.Title; - DataSource shpDatasource = Ogr.Open(shapefilePath, 0); - if (shpDatasource == null) - throw new InvalidDataException("Not valid shapefile"); + DataSource shpDatasource = Ogr.Open(shapefilePath, 0) ?? throw new InvalidDataException("Not valid shapefile"); // load the shapefile layer Layer shpLayer = shpDatasource.GetLayerByIndex(0); @@ -117,7 +119,8 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometryFromShpFileAsset(IAsset } private StacItem GetStacItemWithProperties(SPP_ROOT productMetadata, string stacItemId, double gsd, - IAsset shapefile) { + IAsset shapefile) + { // retrieve geometry from shapefile var geometryObject = GetGeometryFromShpFileAsset(shapefile); @@ -134,18 +137,20 @@ private StacItem GetStacItemWithProperties(SPP_ROOT productMetadata, string stac } - private string ConvertDegreeAngleToDegreeString(string coordinate) { + private string ConvertDegreeAngleToDegreeString(string coordinate) + { return ConvertDegreeAngleToDegreeDouble(coordinate).ToString(); } - private double ConvertDegreeAngleToDegreeDouble(string coordinate) { + private double ConvertDegreeAngleToDegreeDouble(string coordinate) + { // example 0:15:22.185719 string[] coordinateArray = coordinate.Split(':'); - double degrees = Double.Parse(coordinateArray[0]); - double minutes = Double.Parse(coordinateArray[1]); - double seconds = Double.Parse(coordinateArray[2]); + double degrees = double.Parse(coordinateArray[0]); + double minutes = double.Parse(coordinateArray[1]); + double seconds = double.Parse(coordinateArray[2]); //Decimal degrees = // whole number of degrees, // plus minutes divided by 60, @@ -154,7 +159,8 @@ private double ConvertDegreeAngleToDegreeDouble(string coordinate) { return degrees + (minutes / 60) + (seconds / 3600); } - private IDictionary GetCommonMetadata(SPP_ROOT productMetadata, double gsd) { + private IDictionary GetCommonMetadata(SPP_ROOT productMetadata, double gsd) + { Dictionary properties = new Dictionary(); FillBitProperties(productMetadata, properties); FillDateTimeProperties(productMetadata, properties); @@ -163,29 +169,33 @@ private IDictionary GetCommonMetadata(SPP_ROOT productMetadata, return properties; } - private void AddRasterBands(SPP_ROOT productMetadata, StacAsset stacAsset) { + private void AddRasterBands(SPP_ROOT productMetadata, StacAsset stacAsset) + { var gains = productMetadata.AbsoluteCalibr.BMult.Split(','); var offsets = productMetadata.AbsoluteCalibr.BAdd.Split(','); RasterBand[] rasterBands = new RasterBand[gains.Length]; - for (int i = 0; i < gains.Length; i++) { - rasterBands[i] = CreateRasterBandObject(Double.Parse(offsets[i]), Double.Parse(gains[i])); + for (int i = 0; i < gains.Length; i++) + { + rasterBands[i] = CreateRasterBandObject(double.Parse(offsets[i]), double.Parse(gains[i])); } stacAsset.RasterExtension().Bands = rasterBands; } - private void FillBitProperties(SPP_ROOT productMetadata, Dictionary properties) { + private void FillBitProperties(SPP_ROOT productMetadata, Dictionary properties) + { properties.Remove("bit"); properties.Add("bit", productMetadata.Normal.NBitsPerPixel); } - private void FillDateTimeProperties(SPP_ROOT productMetadata, Dictionary properties) { + private void FillDateTimeProperties(SPP_ROOT productMetadata, Dictionary properties) + { CultureInfo provider = CultureInfo.InvariantCulture; string format = "dd/MM/yyyy HH:mm:ss.ffffff"; DateTime.TryParseExact( - String.Format("{0} {1}", productMetadata.Normal.DSceneDate, productMetadata.Normal.TSceneTime), format, + string.Format("{0} {1}", productMetadata.Normal.DSceneDate, productMetadata.Normal.TSceneTime), format, provider, DateTimeStyles.AssumeUniversal, out var startDate); - double deltaTime = Double.Parse(productMetadata.Normal.NDeltaTime); + double deltaTime = double.Parse(productMetadata.Normal.NDeltaTime); var endDate = startDate.AddMinutes(deltaTime); Itenso.TimePeriod.TimeInterval dateInterval = new Itenso.TimePeriod.TimeInterval(startDate, endDate); @@ -196,14 +206,17 @@ private void FillDateTimeProperties(SPP_ROOT productMetadata, Dictionary properties, double gsd) { + Dictionary properties, double gsd) + { string platformName = "resurs-p"; //productMetadata.CCodeKA; - if (!string.IsNullOrEmpty(platformName)) { + if (!string.IsNullOrEmpty(platformName)) + { properties.Remove("platform"); properties.Add("platform", platformName); properties.Remove("mission"); properties.Add("mission", platformName); } - else { + else + { throw new InvalidDataException("Platform id not found or not recognized"); } // instruments var instrumentName = ""; - if (productMetadata.Passport.CDeviceName.ToLower().Equals("geotonp")) { + if (productMetadata.Passport.CDeviceName.ToLower().Equals("geotonp")) + { instrumentName = "geoton"; } - else { + else + { instrumentName = "kshmsa"; } @@ -256,12 +275,14 @@ private void FillInstrument(SPP_ROOT productMetadata, } - private void AddProcessingStacExtension(SPP_ROOT productMetadata, StacItem stacItem) { + private void AddProcessingStacExtension(SPP_ROOT productMetadata, StacItem stacItem) + { var proc = stacItem.ProcessingExtension(); proc.Level = productMetadata.Normal.CLevel; } - private void AddViewStacExtension(SPP_ROOT productMetadata, StacItem stacItem) { + private void AddViewStacExtension(SPP_ROOT productMetadata, StacItem stacItem) + { var view = new ViewStacExtension(stacItem); view.Azimuth = ConvertDegreeAngleToDegreeDouble(productMetadata.Normal.AAzimutScan); @@ -269,25 +290,30 @@ private void AddViewStacExtension(SPP_ROOT productMetadata, StacItem stacItem) { view.SunElevation = ConvertDegreeAngleToDegreeDouble(productMetadata.Normal.ASunElevC); } - private void AddProjStacExtension(SPP_ROOT productMetaData, StacItem stacItem) { + private void AddProjStacExtension(SPP_ROOT productMetaData, StacItem stacItem) + { ProjectionStacExtension proj = stacItem.ProjectionExtension(); proj.Epsg = long.Parse(productMetaData.CoordinateSystem.NCoordSystCode); } private async Task AddAssetsAsync(StacItem stacItem, IAssetsContainer assetsContainer, double gsd, - SPP_ROOT productMetadata) { - foreach (var asset in assetsContainer.Assets.Values.OrderBy(a => a.Uri.ToString())) { + SPP_ROOT productMetadata) + { + foreach (var asset in assetsContainer.Assets.Values.OrderBy(a => a.Uri.ToString())) + { await AddAssetAsync(stacItem, asset, assetsContainer, gsd, productMetadata); } } private async Task AddAssetAsync(StacItem stacItem, IAsset asset, - IAssetsContainer assetsContainer, double gsd, SPP_ROOT productMetadata) { + IAssetsContainer assetsContainer, double gsd, SPP_ROOT productMetadata) + { string filename = Path.GetFileName(asset.Uri.ToString()); string sensorName = filename.Split('_')[1]; // thumbnail - if (filename.EndsWith(".jpg", true, CultureInfo.InvariantCulture)) { + if (filename.EndsWith(".jpg", true, CultureInfo.InvariantCulture)) + { stacItem.Assets.Add("thumbnail", GetGenericAsset(stacItem, asset.Uri, "thumbnail")); stacItem.Assets["thumbnail"].Properties.AddRange(asset.Properties); @@ -296,7 +322,8 @@ private async Task AddAssetAsync(StacItem stacItem, IAsset asset, // metadata - if (filename.EndsWith(".xml", true, CultureInfo.InvariantCulture)) { + if (filename.EndsWith(".xml", true, CultureInfo.InvariantCulture)) + { stacItem.Assets.Add("metadata", GetGenericAsset(stacItem, asset.Uri, "metadata")); stacItem.Assets["metadata"].Properties.AddRange(asset.Properties); @@ -304,13 +331,16 @@ private async Task AddAssetAsync(StacItem stacItem, IAsset asset, } - if (filename.EndsWith(".tiff", true, CultureInfo.InvariantCulture)) { + if (filename.EndsWith(".tiff", true, CultureInfo.InvariantCulture)) + { string mssBandName; - if (asset.Uri.ToString().Contains("Geoton")) { + if (asset.Uri.ToString().Contains("Geoton")) + { mssBandName = "MSS"; } - else { + else + { mssBandName = "PMS"; } @@ -320,7 +350,8 @@ private async Task AddAssetAsync(StacItem stacItem, IAsset asset, stacItem.Assets.Add(mssBandName, bandAsset); // add raster bands only if product is Geoton - if (asset.Uri.ToString().Contains("Geoton")) { + if (asset.Uri.ToString().Contains("Geoton")) + { AddRasterBands(productMetadata, bandAsset); } @@ -329,7 +360,8 @@ private async Task AddAssetAsync(StacItem stacItem, IAsset asset, } } - private StacAsset GetGenericAsset(StacItem stacItem, Uri uri, string role) { + private StacAsset GetGenericAsset(StacItem stacItem, Uri uri, string role) + { StacAsset stacAsset = new StacAsset(stacItem, uri); stacAsset.Roles.Add(role); stacAsset.MediaType = @@ -338,14 +370,16 @@ private StacAsset GetGenericAsset(StacItem stacItem, Uri uri, string role) { } - private StacAsset GetBandAsset(StacItem stacItem, IAsset asset, double gsd) { + private StacAsset GetBandAsset(StacItem stacItem, IAsset asset, double gsd) + { StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, asset.Uri, new System.Net.Mime.ContentType(MimeTypes.GetMimeType(asset.Uri.ToString())) ); stacAsset.Properties.AddRange(asset.Properties); stacAsset.SetProperty("gsd", gsd); - if (asset.Uri.ToString().Contains("Geoton")) { + if (asset.Uri.ToString().Contains("Geoton")) + { //geoton EoBandObject b01EoBandObject = CreateEoBandObject("channel-1", EoBandCommonName.blue, 0.5045, 0.045); @@ -358,7 +392,8 @@ private StacAsset GetBandAsset(StacItem stacItem, IAsset asset, double gsd) { stacAsset.EoExtension().Bands = new[] { b01EoBandObject, b02EoBandObject, b03EoBandObject, b04EoBandObject }; } - else { + else + { //KShMSA EoBandObject b01EoBandObject = CreateEoBandObject("channel-1", EoBandCommonName.blue, 0.47, 0.08); @@ -378,10 +413,12 @@ private StacAsset GetBandAsset(StacItem stacItem, IAsset asset, double gsd) { } private EoBandObject CreateEoBandObject(string name, EoBandCommonName eoBandCommonName, double centerWaveLength, - double fullWidthHalfMax, double? eai = null) { + double fullWidthHalfMax, double? eai = null) + { EoBandObject eoBandObject = new EoBandObject(name, eoBandCommonName); eoBandObject.Properties.Add("full_width_half_max", fullWidthHalfMax); - if (eai != null) { + if (eai != null) + { eoBandObject.SolarIllumination = eai; } @@ -389,7 +426,8 @@ private EoBandObject CreateEoBandObject(string name, EoBandCommonName eoBandComm return eoBandObject; } - private RasterBand CreateRasterBandObject(double offset, double gain) { + private RasterBand CreateRasterBandObject(double offset, double gain) + { RasterBand rasterBandObject = new RasterBand(); rasterBandObject.Offset = offset; rasterBandObject.Scale = gain; @@ -397,7 +435,8 @@ private RasterBand CreateRasterBandObject(double offset, double gain) { } - private void FillBasicsProperties(IDictionary properties) { + private void FillBasicsProperties(IDictionary properties) + { CultureInfo culture = CultureInfo.InvariantCulture; // title properties.Remove("title"); @@ -410,12 +449,13 @@ private void FillBasicsProperties(IDictionary properties) { } - private void AddOtherProperties(IDictionary properties) { + private void AddOtherProperties(IDictionary properties) + { if (IncludeProviderProperty) { AddSingleProvider( properties, - "Roscosmos", + "Roscosmos", "Resurs-P is a series of Russian commercial Earth observation satellites capable of acquiring high-resolution hyperspectral, wide-field multispectral, and panchromatic imagery.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.eoportal.org/satellite-missions/resurs-p") @@ -423,4 +463,4 @@ private void AddOtherProperties(IDictionary properties) { } } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Resursp/Schema.cs b/src/Stars.Data/Model/Metadata/Resursp/Schema.cs index af1c5cf1..c8f6d7a4 100644 --- a/src/Stars.Data/Model/Metadata/Resursp/Schema.cs +++ b/src/Stars.Data/Model/Metadata/Resursp/Schema.cs @@ -1,10 +1,10 @@ -using System; -using System.Xml.Serialization; -using System.Collections.Generic; +using System.Xml.Serialization; -namespace Terradue.Stars.Data.Model.Metadata.Resursp { +namespace Terradue.Stars.Data.Model.Metadata.Resursp +{ [XmlRoot(ElementName = "Passport")] - public class Passport { + public class Passport + { [XmlElement(ElementName = "cDeviceName")] public string CDeviceName { get; set; } @@ -13,7 +13,8 @@ public class Passport { } [XmlRoot(ElementName = "Geographic")] - public class Geographic { + public class Geographic + { [XmlElement(ElementName = "aNWLat")] public string ANWLat { get; set; } [XmlElement(ElementName = "aNWLong")] public string ANWLong { get; set; } [XmlElement(ElementName = "aNELat")] public string ANELat { get; set; } @@ -27,7 +28,8 @@ public class Geographic { } [XmlRoot(ElementName = "CoordinateSystem")] - public class CoordinateSystem { + public class CoordinateSystem + { [XmlElement(ElementName = "cCoordSystName")] public string CCoordSystName { get; set; } @@ -132,7 +134,8 @@ public class CoordinateSystem { } [XmlRoot(ElementName = "Normal")] - public class Normal { + public class Normal + { [XmlElement(ElementName = "nBitsPerPixel")] public string NBitsPerPixel { get; set; } @@ -225,21 +228,23 @@ public class Normal { [XmlElement(ElementName = "nLDownEast")] public string NLDownEast { get; set; } } - - [XmlRoot(ElementName="AbsoluteCalibr")] - public class AbsoluteCalibr { - [XmlElement(ElementName="cFormula")] + + [XmlRoot(ElementName = "AbsoluteCalibr")] + public class AbsoluteCalibr + { + [XmlElement(ElementName = "cFormula")] public string CFormula { get; set; } - [XmlElement(ElementName="nDone")] + [XmlElement(ElementName = "nDone")] public string NDone { get; set; } - [XmlElement(ElementName="bMult")] + [XmlElement(ElementName = "bMult")] public string BMult { get; set; } - [XmlElement(ElementName="bAdd")] + [XmlElement(ElementName = "bAdd")] public string BAdd { get; set; } } [XmlRoot(ElementName = "SPP_ROOT")] - public class SPP_ROOT { + public class SPP_ROOT + { [XmlElement(ElementName = "Version")] public string Version { get; set; } [XmlElement(ElementName = "nNumberKA")] @@ -274,10 +279,10 @@ public class SPP_ROOT { [XmlElement(ElementName = "CoordinateSystem")] public CoordinateSystem CoordinateSystem { get; set; } - [XmlElement(ElementName = "Normal")] + [XmlElement(ElementName = "Normal")] public Normal Normal { get; set; } - - [XmlElement(ElementName="AbsoluteCalibr")] + + [XmlElement(ElementName = "AbsoluteCalibr")] public AbsoluteCalibr AbsoluteCalibr { get; set; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Saocom1/Saocom1MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Saocom1/Saocom1MetadataExtractor.cs index d1fecd8c..f08cad7d 100644 --- a/src/Stars.Data/Model/Metadata/Saocom1/Saocom1MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Saocom1/Saocom1MetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -13,21 +13,19 @@ using Stac; using Stac.Extensions.Processing; using Stac.Extensions.Projection; -using Stac.Extensions.Sat; using Stac.Extensions.Sar; +using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Data.Model.Shared; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; +using Terradue.Stars.Services; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; -using Terradue.Stars.Data.Model.Shared; using Terradue.Stars.Services.Processing; - -using Microsoft.Extensions.DependencyInjection; -using Terradue.Stars.Services.Supplier.Destination; -using Terradue.Stars.Services.Supplier.Carrier; -using Terradue.Stars.Services; using Terradue.Stars.Services.Supplier; +using Terradue.Stars.Services.Supplier.Carrier; +using Terradue.Stars.Services.Supplier.Destination; namespace Terradue.Stars.Data.Model.Metadata.Saocom1 { @@ -50,8 +48,7 @@ public Saocom1MetadataExtractor(ILogger logger, IResou public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset metadataAsset = GetMetadataAsset(item); @@ -60,7 +57,7 @@ public override bool CanProcess(IResource route, IDestination destination) IAsset zipAsset = GetZipAsset(item); return (zipAsset != null); } - else + else { SAOCOM_XMLProduct metadata = ReadMetadata(metadataAsset).GetAwaiter().GetResult(); } @@ -102,9 +99,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi innerStacItem = new ItemContainerNode(item, mergedAssets, "merged"); } - IAsset metadataAsset = GetMetadataAsset(innerStacItem); - if (metadataAsset == null) throw new Exception("No metadata asset found"); - + IAsset metadataAsset = GetMetadataAsset(innerStacItem) ?? throw new Exception("No metadata asset found"); SAOCOM_XMLProduct metadata = await ReadMetadata(metadataAsset); IAsset kmlAsset = FindFirstAssetFromFileNameRegex(innerStacItem, @"(slc|di|gec|gtc)-.*\.kml"); @@ -244,8 +239,7 @@ private double GetIncidenceAngle(XEMT manifest) private void AddSatStacExtension(SAOCOM_XMLProduct metadata, StacItem stacItem) { var sat = new SatStacExtension(stacItem); - int orbit = 0; - int.TryParse(metadata.Channel[0].StateVectorData.OrbitNumber, out orbit); + int.TryParse(metadata.Channel[0].StateVectorData.OrbitNumber, out int orbit); if (orbit > 0) sat.AbsoluteOrbit = orbit; orbit = 0; @@ -254,8 +248,7 @@ private void AddSatStacExtension(SAOCOM_XMLProduct metadata, StacItem stacItem) sat.RelativeOrbit = orbit; sat.OrbitState = metadata.Channel[0].StateVectorData.OrbitDirection.ToLower(); - int absOrbit; - if (int.TryParse(metadata.Channel[0].StateVectorData.OrbitNumber, out absOrbit)) + if (int.TryParse(metadata.Channel[0].StateVectorData.OrbitNumber, out int absOrbit)) sat.AbsoluteOrbit = absOrbit; } @@ -282,8 +275,8 @@ private void AddOrbitInformation(SAOCOM_XMLProduct metadata, XEMT manifest, Stac { foreach (Parameter p in parameters.Inputs.Parameters) { - if (p.Name == "Path" && Int32.TryParse(p.Value, out int path))stacItem.Properties["saocom:path"] = path; - if (p.Name == "Row" && Int32.TryParse(p.Value, out int row)) stacItem.Properties["saocom:row"] = row; + if (p.Name == "Path" && int.TryParse(p.Value, out int path)) stacItem.Properties["saocom:path"] = path; + if (p.Name == "Row" && int.TryParse(p.Value, out int row)) stacItem.Properties["saocom:row"] = row; } } } @@ -342,32 +335,37 @@ private void AddSarStacExtension(SAOCOM_XMLProduct metadata, StacItem stacItem, string acquisitionMode = fileName.Split('-')[3].ToUpper().Substring(0, 2); double resolutionRange; double resolutionAzimuth; - - switch (acquisitionMode) { + + switch (acquisitionMode) + { case "SM": resolutionRange = 10; resolutionAzimuth = 10; break; case "TW": // full polarization - if (polarizations.Length == 4) { + if (polarizations.Length == 4) + { resolutionRange = 100; resolutionAzimuth = 100; } // single or dual polarization - else { + else + { resolutionRange = 50; resolutionAzimuth = 50; } break; case "TN": // full polarization - if (polarizations.Length == 4) { + if (polarizations.Length == 4) + { resolutionRange = 50; resolutionAzimuth = 50; } // single or dual polarization - else { + else + { resolutionRange = 30; resolutionAzimuth = 30; } @@ -393,7 +391,7 @@ private void AddSarStacExtension(SAOCOM_XMLProduct metadata, StacItem stacItem, sar.ResolutionRange = resolutionRange; sar.ResolutionAzimuth = resolutionAzimuth; - + } private IDictionary GetCommonMetadata(SAOCOM_XMLProduct metadata, XEMT manifest, Dictionary properties, IItem item) @@ -406,7 +404,7 @@ private IDictionary GetCommonMetadata(SAOCOM_XMLProduct metadata return properties; } - private void FillBasicsProperties(SAOCOM_XMLProduct metadata, IDictionary properties, IItem item) + private void FillBasicsProperties(SAOCOM_XMLProduct metadata, IDictionary properties, IItem item) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -424,8 +422,8 @@ private void FillInstrument(SAOCOM_XMLProduct metadata, XEMT manifest, Dictionar { properties.Remove("platform"); string sensorName = metadata.Channel[0].DataSetInfo.SensorName; - string serialNumber = (sensorName.Substring(0, 3) == "SAO" ? sensorName.Substring(3) : String.Empty); - properties.Add("platform", String.Format("saocom-{0}", serialNumber).ToLower()); + string serialNumber = (sensorName.Substring(0, 3) == "SAO" ? sensorName.Substring(3) : string.Empty); + properties.Add("platform", string.Format("saocom-{0}", serialNumber).ToLower()); properties.Remove("mission"); properties.Add("mission", "saocom-1"); @@ -465,13 +463,13 @@ private void FillDateTimeProperties(SAOCOM_XMLProduct metadata, Dictionary properties, IItem item) + private void AddOtherProperties(SAOCOM_XMLProduct metadata, IDictionary properties, IItem item) { if (IncludeProviderProperty) { AddSingleProvider( properties, - "CONAE", + "CONAE", "The SAOCOM satellite series represents Argentina's approved polarimetric L-band SAR (Synthetic Aperture Radar) constellation of two spacecraft. The SAOCOM-1 mission is composed of two satellites (SAOCOM-1A and -1B) launched consecutively. The overall objective of SAOCOM is to provide an effective Earth observation and disaster monitoring capability.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("http://saocom.invap.com.ar") @@ -509,8 +507,8 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometry(IItem item, Kml kml, SA }; for (int i = 0; i < coordinates.Length; i++) { - double lat = Double.Parse(coordinates[i].Point.Val[0].Text); - double lon = Double.Parse(coordinates[i].Point.Val[1].Text); + double lat = double.Parse(coordinates[i].Point.Val[0].Text); + double lon = double.Parse(coordinates[i].Point.Val[1].Text); lineStringPositions[i] = new GeoJSON.Net.Geometry.Position(lat, lon); } lineStringPositions[coordinates.Length] = lineStringPositions[0]; @@ -525,8 +523,8 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometry(IItem item, Kml kml, SA for (int i = 0; i < coordStrArray.Length; i++) { string[] parts = coordStrArray[i].Split(','); - double lon = Double.Parse(parts[0]); - double lat = Double.Parse(parts[1]); + double lon = double.Parse(parts[0]); + double lat = double.Parse(parts[1]); lineStringPositions[i] = new GeoJSON.Net.Geometry.Position(lat, lon); } lineStringPositions[coordStrArray.Length] = lineStringPositions[0]; @@ -558,7 +556,7 @@ private string ReadFilename(IItem item, SAOCOM_XMLProduct metadata) if (!value.Contains("AN")) { var nameField = node.Descendants(nName).FirstOrDefault().Value; - if (value.Contains(String.Format("_{0}_", processingLevel))) + if (value.Contains(string.Format("_{0}_", processingLevel))) { output = value.Substring(value.LastIndexOf('/') + 1, value.IndexOf(".") - value.IndexOf('/') - 1); break; @@ -577,7 +575,7 @@ protected async Task AddAssets(StacItem stacItem, IItem item, IAsset manifestAss IAsset dataAsset, metadataAsset; KeyValuePair bandStacAsset; StacAsset stacAsset; - + if (manifestAsset != null) { stacItem.Assets.Add("manifest", StacAsset.CreateMetadataAsset(stacItem, manifestAsset.Uri, new ContentType("application/xml"), "Manifest (XEMT)")); @@ -604,7 +602,8 @@ protected async Task AddAssets(StacItem stacItem, IItem item, IAsset manifestAss } var overview = FindFirstAssetFromFileNameRegex(item, @".*(gtc)-acqId.*\.png"); - if (overview != null){ + if (overview != null) + { stacItem.Assets.Add("overview", StacAsset.CreateOverviewAsset(stacItem, overview.Uri, new ContentType(MimeTypes.GetMimeType(overview.Uri.ToString())))); stacItem.Assets["overview"].Properties.AddRange(overview.Properties); @@ -635,7 +634,7 @@ private double GetGroundSampleDistance(SAOCOM_XMLProduct metadata, XEMT manifest { AcquisitionParameters parameters = null; - if (manifest != null && manifest.Product != null && manifest.Product.Features != null && + if (manifest != null && manifest.Product != null && manifest.Product.Features != null && manifest.Product.Features.Acquisition != null && manifest.Product.Features.Acquisition.Parameters != null) { parameters = manifest.Product.Features.Acquisition.Parameters; @@ -660,7 +659,8 @@ private double GetGroundSampleDistance(SAOCOM_XMLProduct metadata, XEMT manifest { string fileName = GetInstrumentMode(metadata); string acquisitionMode = fileName.Split('-')[3].ToUpper().Substring(0, 2); - if (acquisitionMode == "SM") { + if (acquisitionMode == "SM") + { return 10; } return 0; @@ -727,4 +727,4 @@ public virtual async Task ReadManifest(IAsset manifestAsset) } } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Saocom1/Schema.cs b/src/Stars.Data/Model/Metadata/Saocom1/Schema.cs index a377dadd..456bed95 100644 --- a/src/Stars.Data/Model/Metadata/Saocom1/Schema.cs +++ b/src/Stars.Data/Model/Metadata/Saocom1/Schema.cs @@ -1,6 +1,6 @@ -using System; -using System.Xml.Serialization; +using System; using System.Collections.Generic; +using System.Xml.Serialization; namespace Terradue.Stars.Data.Model.Metadata.Saocom1 { @@ -515,4 +515,4 @@ public class Parameter } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1AssetPreview.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1AssetPreview.cs index 06de64e5..158aab4d 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1AssetPreview.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1AssetPreview.cs @@ -1,8 +1,6 @@ -using System; +using System; using System.IO; using System.Net.Mime; -using System.Threading.Tasks; -using System.Xml.Serialization; using Stac; using Terradue.Stars.Interface; @@ -32,12 +30,12 @@ public override StacAsset CreateDataAsset(IStacObject stacObject) var filename = Path.GetFileName(previewAsset.Uri.ToString()); - if ( filename == "quick-look.png") - stacAsset.Roles.Add("thumbnail"); - if ( filename == "map-overlay.kml") - stacAsset.Roles.Add("kml"); - if ( filename == "logo.png") - stacAsset.Roles.Add("logo"); + if (filename == "quick-look.png") + stacAsset.Roles.Add("thumbnail"); + if (filename == "map-overlay.kml") + stacAsset.Roles.Add("kml"); + if (filename == "logo.png") + stacAsset.Roles.Add("logo"); return stacAsset; } @@ -78,7 +76,7 @@ public override string GetAnnotationId() public override StacAsset CreateMetadataAsset(IStacObject stacObject) { throw new NotImplementedException(); - + } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1AssetSupport.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1AssetSupport.cs index 2c04d586..e103ac9c 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1AssetSupport.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1AssetSupport.cs @@ -1,7 +1,5 @@ -using System; +using System; using System.IO; -using System.Threading.Tasks; -using System.Xml.Serialization; using Stac; using Terradue.Stars.Interface; @@ -59,4 +57,4 @@ public override StacAsset CreateMetadataAsset(IStacObject stacObject) return stacAsset; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetCalibration.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetCalibration.cs index a2abc581..72c230c2 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetCalibration.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetCalibration.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System; using System.Threading.Tasks; using System.Xml.Serialization; using Stac; @@ -15,7 +14,7 @@ public class S1L1AssetCalibration : SentinelAssetFactory private readonly IAsset calibrationAsset; - public S1L1AssetCalibration(l1CalibrationType l1Calibration, IAsset calibrationAsset, IResourceServiceProvider resourceServiceProvider): base(resourceServiceProvider) + public S1L1AssetCalibration(l1CalibrationType l1Calibration, IAsset calibrationAsset, IResourceServiceProvider resourceServiceProvider) : base(resourceServiceProvider) { this.l1Calibration = l1Calibration; this.calibrationAsset = calibrationAsset; @@ -60,7 +59,7 @@ public override double GetGroundSampleDistance() public override string GetId() { - return String.Format("calibration-{0}-{1}-{2}", GetPolarization(), GetSwath(), GetStripe()).ToLower(); + return string.Format("calibration-{0}-{1}-{2}", GetPolarization(), GetSwath(), GetStripe()).ToLower(); } private object GetStripe() @@ -83,4 +82,4 @@ public override StacAsset CreateMetadataAsset(IStacObject stacObject) throw new NotImplementedException(); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetNoise.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetNoise.cs index bcfc53ac..3fecc55f 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetNoise.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetNoise.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System; using System.Threading.Tasks; using System.Xml.Serialization; using Stac; @@ -17,8 +16,8 @@ public class S1L1AssetNoise : SentinelAssetFactory public S1L1AssetNoise(l1NoiseVectorType l1Calibration, IAsset calibrationAsset, IResourceServiceProvider resourceServiceProvider) : base(resourceServiceProvider) { - this.l1Noise = l1Calibration; - this.noiseAsset = calibrationAsset; + l1Noise = l1Calibration; + noiseAsset = calibrationAsset; } public async static Task Create(IAsset calibrationAsset, IResourceServiceProvider resourceServiceProvider) @@ -60,7 +59,7 @@ public override double GetGroundSampleDistance() public override string GetId() { - return String.Format("noise-{0}-{1}-{2}", GetPolarization(), GetSwath(), GetStripe()).ToLower(); + return string.Format("noise-{0}-{1}-{2}", GetPolarization(), GetSwath(), GetStripe()).ToLower(); } private object GetStripe() @@ -83,4 +82,4 @@ public override StacAsset CreateMetadataAsset(IStacObject stacObject) throw new NotImplementedException(); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetProduct.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetProduct.cs index 1dda72e5..5a76ba61 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetProduct.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L1AssetProduct.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System; using System.Threading.Tasks; using System.Xml.Serialization; using Stac; @@ -12,14 +11,14 @@ namespace Terradue.Stars.Data.Model.Metadata.Sentinels.Sentinel1 public class S1L1AssetProduct : SentinelAssetFactory { - public static XmlSerializer s1L1ProductSerializer = new XmlSerializer(typeof(Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S1.Level1.Product.l1ProductType)); + public static XmlSerializer s1L1ProductSerializer = new XmlSerializer(typeof(l1ProductType)); private readonly l1ProductType l1Product; private readonly IAsset annotationAsset; private readonly IAsset dataAsset; - public S1L1AssetProduct(l1ProductType l1ProductType, IAsset annotationAsset, IAsset dataAsset, IResourceServiceProvider resourceServiceProvider): base(resourceServiceProvider) + public S1L1AssetProduct(l1ProductType l1ProductType, IAsset annotationAsset, IAsset dataAsset, IResourceServiceProvider resourceServiceProvider) : base(resourceServiceProvider) { - this.l1Product = l1ProductType; + l1Product = l1ProductType; this.annotationAsset = annotationAsset; this.dataAsset = dataAsset; } @@ -78,7 +77,7 @@ public override double GetGroundSampleDistance() public override string GetId() { - return String.Format("{0}-{1}-{2}-{3}", GetPixelValueLabel(), GetPolarization(), GetSwath(), GetStripe()).ToLower(); + return string.Format("{0}-{1}-{2}-{3}", GetPixelValueLabel(), GetPolarization(), GetSwath(), GetStripe()).ToLower(); } private object GetStripe() @@ -93,12 +92,12 @@ private string GetSwath() public override string GetAnnotationId() { - return String.Format("annotation-{0}-{1}-{2}", GetPolarization(), GetSwath(), GetStripe()).ToLower(); + return string.Format("annotation-{0}-{1}-{2}", GetPolarization(), GetSwath(), GetStripe()).ToLower(); } public string GetAnnotationTitle() { - return String.Format("Annotation {0} {1} {2}", GetPolarization(), GetSwath(), GetStripe()); + return string.Format("Annotation {0} {1} {2}", GetPolarization(), GetSwath(), GetStripe()); } public override StacAsset CreateMetadataAsset(IStacObject stacObject) @@ -110,4 +109,4 @@ public override StacAsset CreateMetadataAsset(IStacObject stacObject) return stacAsset; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L2AssetProduct.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L2AssetProduct.cs index a652080e..b4eebde4 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L2AssetProduct.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1L2AssetProduct.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System; using System.Threading.Tasks; using System.Xml.Serialization; using Stac; @@ -11,7 +10,7 @@ namespace Terradue.Stars.Data.Model.Metadata.Sentinels.Sentinel1 public class S1L2AssetProduct : SentinelAssetFactory { - public static XmlSerializer s1L2ProductSerializer = new XmlSerializer(typeof(Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S1.Level2.Product.level2ProductType)); + public static XmlSerializer s1L2ProductSerializer = new XmlSerializer(typeof(level2ProductType)); private readonly level2ProductType l2ProductType; private readonly string type; @@ -51,4 +50,4 @@ public override string GetId() throw new NotImplementedException(); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1SafeStacFactory.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1SafeStacFactory.cs index 43849b5f..a21181ef 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1SafeStacFactory.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/S1SafeStacFactory.cs @@ -1,12 +1,12 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using Stac; +using Stac.Extensions.Projection; using Stac.Extensions.Sar; using Terradue.OpenSearch.Sentinel.Data.Safe; using Terradue.Stars.Interface; -using Stac.Extensions.Projection; namespace Terradue.Stars.Data.Model.Metadata.Sentinels.Sentinel1 { @@ -31,7 +31,7 @@ internal override StacItem CreateStacItem() private void AddSarStacExtension(StacItem stacItem) { - stacItem.SarExtension().Required ( + stacItem.SarExtension().Required( GetInstrumentMode(), GetFrequencyBand(), GetPolarizations(), @@ -81,13 +81,7 @@ private char GetResolution() public string GetInstrumentMode() { - var platformMetadata = xfdu.metadataSection.FirstOrDefault(m => m.ID == "platform"); - - if (platformMetadata == null) - { - throw new ArgumentException("No platform metadata found in the manifest of " + xfdu.ID); - } - + var platformMetadata = xfdu.metadataSection.FirstOrDefault(m => m.ID == "platform") ?? throw new ArgumentException("No platform metadata found in the manifest of " + xfdu.ID); try { return platformMetadata.metadataWrap.xmlData.platform.instrument.extension.s1SarL0instrumentMode.mode.ToString(); @@ -141,12 +135,7 @@ private double GetGroundSampleDistance(string pt, string mode, char res) public override string GetProductType() { - var generalProductInformation = xfdu.metadataSection.FirstOrDefault(m => m.ID == "generalProductInformation"); - if (generalProductInformation == null) - { - throw new InvalidDataException("No generalProductInformation metadata found in the manifest of " + xfdu.ID); - } - + var generalProductInformation = xfdu.metadataSection.FirstOrDefault(m => m.ID == "generalProductInformation") ?? throw new InvalidDataException("No generalProductInformation metadata found in the manifest of " + xfdu.ID); try { return generalProductInformation.metadataWrap.xmlData.s1SarL1GeneralProductInformation.productType.ToString(); @@ -187,4 +176,4 @@ protected override void AddProjectionStacExtension(StacItem stacItem) stacItem.ProjectionExtension().Epsg = null; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/Sentinel1MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/Sentinel1MetadataExtractor.cs index eaea6289..9caafd40 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/Sentinel1MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel1/Sentinel1MetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Net.Mime; using System.Threading.Tasks; @@ -24,7 +24,7 @@ public override async Task ReadManifest(IAsset manifestAsset) XFDUType xfdu = await base.ReadManifest(manifestAsset); if (!xfdu.informationPackageMap.contentUnit[0].textInfo.StartsWith("Sentinel-1")) { - throw new FormatException(String.Format("Not a Sentinel-1 manifest SAFE file asset")); + throw new FormatException(string.Format("Not a Sentinel-1 manifest SAFE file asset")); } return xfdu; } @@ -34,9 +34,7 @@ protected async override Task AddAssets(StacItem stacItem, IItem item, SentinelS foreach (var bandAsset in FindAllAssetsFromFileNameRegex(item, "\\.tiff$")) { string filename = Path.GetFileNameWithoutExtension(bandAsset.Value.Uri.ToString()); - IAsset annotationAsset = FindFirstAssetFromFileNameRegex(item, @"^(.*\/+|)" + filename + @"\.xml$"); - if (annotationAsset == null) - throw new FileNotFoundException(string.Format("No XML annotation found for S1 tiff asset '{0}'", bandAsset.Key)); + IAsset annotationAsset = FindFirstAssetFromFileNameRegex(item, @"^(.*\/+|)" + filename + @"\.xml$") ?? throw new FileNotFoundException(string.Format("No XML annotation found for S1 tiff asset '{0}'", bandAsset.Key)); var bandStacAsset = await AddBandAsset(stacItem, bandAsset.Value, annotationAsset, stacFactory); var annotationStacAsset = await AddAnnotationAsset(stacItem, annotationAsset, stacFactory); } @@ -74,7 +72,7 @@ private string AddOverviewAsset(StacItem stacItem, string key, IItem item, Senti if (contentType == null) { - contentType = new System.Net.Mime.ContentType(MimeTypes.GetMimeType(asset.Uri.ToString())); + contentType = new ContentType(MimeTypes.GetMimeType(asset.Uri.ToString())); } StacAsset stacAsset = StacAsset.CreateOverviewAsset(stacItem, asset.Uri, contentType); @@ -164,7 +162,7 @@ protected override Task AddAdditionalProperties(StacItem stacItem, IItem item, S { AddSingleProvider( stacItem.Properties, - "ESA/EC (Copernicus)", + "ESA/EC (Copernicus)", "The Sentinel-1 mission comprises a constellation of two polar-orbiting satellites, operating day and night performing C-band synthetic aperture radar imaging, enabling them to acquire imagery regardless of the weather.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://sentinel.esa.int/web/sentinel/missions/sentinel-1") diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/S2L2SafeStacFactory.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/S2L2SafeStacFactory.cs index 90b5f36c..eb2415be 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/S2L2SafeStacFactory.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/S2L2SafeStacFactory.cs @@ -1,10 +1,6 @@ -using System.Collections.Generic; -using System.Linq; -using System.Xml.Serialization; -using Stac; +using Stac; using Stac.Extensions.Eo; using Stac.Extensions.Projection; -using Stac.Extensions.Sar; using Terradue.OpenSearch.Sentinel.Data.Safe; using Terradue.Stars.Interface; @@ -34,8 +30,8 @@ protected override void AddEoStacExtension(StacItem stacItem) protected override void AddProjectionStacExtension(StacItem stacItem) { - if ( mtdTile?.Geometric_Info == null ) return; + if (mtdTile?.Geometric_Info == null) return; stacItem.ProjectionExtension().Epsg = int.Parse(mtdTile.Geometric_Info.Tile_Geocoding.HORIZONTAL_CS_CODE.Replace("EPSG:", "")); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/S2SafeStacFactory.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/S2SafeStacFactory.cs index 3b197abe..1f45fd4b 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/S2SafeStacFactory.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/S2SafeStacFactory.cs @@ -1,6 +1,5 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Xml.Serialization; using Stac; using Stac.Extensions.Eo; using Stac.Extensions.Projection; @@ -78,7 +77,7 @@ protected override string GetProcessingLevel() protected override string GetTitle(IDictionary properties) { - return string .Format("{0} {1} {2} {3}", + return string.Format("{0} {1} {2} {3}", //StylePlatform(properties.GetProperty("platform")), properties.GetProperty("platform").ToUpper(), properties.GetProperty("instruments").First().ToUpper(), @@ -94,9 +93,9 @@ protected override string GetSensorType(metadataObjectType platformMetadata) protected override void AddProjectionStacExtension(StacItem stacItem) { - if ( mtdTile?.Geometric_Info?.Tile_Geocoding == null ) return; + if (mtdTile?.Geometric_Info?.Tile_Geocoding == null) return; stacItem.ProjectionExtension().Epsg = int.Parse(mtdTile.Geometric_Info.Tile_Geocoding.HORIZONTAL_CS_CODE.Replace("EPSG:", "")); // stacItem.ProjectionExtension().Epsg = null; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2Level1MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2Level1MetadataExtractor.cs index 0fd7c9e7..abe4979d 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2Level1MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2Level1MetadataExtractor.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System; using System.Globalization; using System.IO; using System.Linq; @@ -15,14 +14,13 @@ using Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S2.Level1; using Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S2.Level1.Granules; using Terradue.Stars.Interface; -using Terradue.Stars.Services.Model.Stac; namespace Terradue.Stars.Data.Model.Metadata.Sentinels.Sentinel2 { public class Sentinel2Level1MetadataExtractor : Sentinel2MetadataExtractor { - public static XmlSerializer s2L1CProductSerializer = new XmlSerializer(typeof(Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S2.Level1.Level1C_User_Product)); - public static XmlSerializer s2L1CProductTileSerializer = new XmlSerializer(typeof(Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S2.Level1.Granules.Level1C_Tile)); + public static XmlSerializer s2L1CProductSerializer = new XmlSerializer(typeof(Level1C_User_Product)); + public static XmlSerializer s2L1CProductTileSerializer = new XmlSerializer(typeof(Level1C_Tile)); private IAsset mtdAsset; private Level1C_User_Product level1C_User_Product; @@ -39,14 +37,12 @@ public override async Task ReadManifest(IAsset manifestAsset) { return xfdu; } - throw new FormatException(String.Format("Not a Sentinel-2 Level 1C manifest SAFE file asset")); + throw new FormatException(string.Format("Not a Sentinel-2 Level 1C manifest SAFE file asset")); } protected async override Task AddAssets(StacItem stacItem, IItem item, SentinelSafeStacFactory stacFactory) { - var mtdAsset = FindFirstAssetFromFileNameRegex(item, "MTD_MSIL1C.xml$"); - if (mtdAsset == null) - throw new FileNotFoundException("Product metadata file 'MTD_MSIL1C.xml' not found"); + var mtdAsset = FindFirstAssetFromFileNameRegex(item, "MTD_MSIL1C.xml$") ?? throw new FileNotFoundException("Product metadata file 'MTD_MSIL1C.xml' not found"); var mtdtlAsset = FindFirstAssetFromFileNameRegex(item, "MTD_TL.xml$"); Level1C_Tile mtdTile = null; if (mtdtlAsset != null) @@ -76,7 +72,7 @@ protected async override Task AddAdditionalProperties(StacItem stacItem, IItem i private string AddJp2BandAsset(StacItem stacItem, IAsset bandAsset, IItem item, Level1C_User_Product level1CUserProduct, Level1C_Tile? mtdTile) { StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, bandAsset.Uri, - new System.Net.Mime.ContentType("image/jp2") + new ContentType("image/jp2") ); stacAsset.Properties.AddRange(bandAsset.Properties); string bandId = Path.GetFileNameWithoutExtension(bandAsset.Uri.ToString()).Split('_').Last(); @@ -102,15 +98,16 @@ private string AddJp2BandAsset(StacItem stacItem, IAsset bandAsset, IItem item, rasterBand.Nodata = 0; rasterBand.Statistics = new Stac.Common.Statistics(0, 10000, null, null, null); rasterBand.SpatialResolution = (double)spectralInfo.RESOLUTION; - if ( mtdTile != null ){ - - var size = mtdTile.Geometric_Info.Tile_Geocoding.Size.First(s => s.resolution == spectralInfo.RESOLUTION); + if (mtdTile != null) + { + + var size = mtdTile.Geometric_Info.Tile_Geocoding.Size.First(s => s.resolution == spectralInfo.RESOLUTION); stacAsset.ProjectionExtension().Shape = new int[2] { size.NCOLS, size.NROWS }; } stacAsset.RasterExtension().Bands = new RasterBand[1] { rasterBand }; stacAsset.Title = eoBandObject.Description = string.Format("{0} {1}nm TOA {2}", GetBandCommonName(spectralInfo), Math.Round(spectralInfo.Wavelength.CENTRAL.Value), spectralInfo.RESOLUTION); } - + stacAsset.Roles.Add("reflectance"); stacItem.Assets.Add(bandId, stacAsset); diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2Level2MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2Level2MetadataExtractor.cs index 95c973d4..75bf41d2 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2Level2MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2Level2MetadataExtractor.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System; using System.Globalization; using System.IO; using System.Linq; @@ -12,7 +11,6 @@ using Stac.Extensions.Projection; using Stac.Extensions.Raster; using Terradue.OpenSearch.Sentinel.Data.Safe; -using Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S2.Level1.Granules; using Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S2.Level2; using Terradue.Stars.Interface; @@ -20,7 +18,7 @@ namespace Terradue.Stars.Data.Model.Metadata.Sentinels.Sentinel2 { public class Sentinel2Level2MetadataExtractor : Sentinel2MetadataExtractor { - public static XmlSerializer s2L2AProductSerializer = new XmlSerializer(typeof(Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S2.Level2.Level2A_User_Product)); + public static XmlSerializer s2L2AProductSerializer = new XmlSerializer(typeof(Level2A_User_Product)); public static XmlSerializer s2L2AProductTileSerializer = new XmlSerializer(typeof(Level2A_Tile)); private IAsset mtdAsset; @@ -38,7 +36,7 @@ public override async Task ReadManifest(IAsset manifestAsset) { return xfdu; } - throw new FormatException(String.Format("Not a Sentinel-2 Level 2A manifest SAFE file asset")); + throw new FormatException(string.Format("Not a Sentinel-2 Level 2A manifest SAFE file asset")); } @@ -86,11 +84,11 @@ private string AddJp2BandAsset(StacItem stacItem, IAsset bandAsset, IItem item, string msk = Path.GetFileNameWithoutExtension(bandAsset.Uri.ToString()).Split('_')[0]; if (msk == "MSK") { - return String.Empty; + return string.Empty; } StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, bandAsset.Uri, - new System.Net.Mime.ContentType("image/jp2") + new ContentType("image/jp2") ); stacAsset.Properties.AddRange(bandAsset.Properties); @@ -104,7 +102,7 @@ private string AddJp2BandAsset(StacItem stacItem, IAsset bandAsset, IItem item, } string res = Path.GetFileNameWithoutExtension(bandAsset.Uri.ToString()).Split('_')[3]; - double gsd = Double.Parse(res.TrimEnd('m')); + double gsd = double.Parse(res.TrimEnd('m')); string assetName = bandId; var spectralInfo = level2AUserProduct.General_Info.Product_Image_Characteristics.Spectral_Information_List.FirstOrDefault(si => si.physicalBand.ToString() == bandId.Replace("B0", "B")); if (spectralInfo != null) diff --git a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2MetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2MetadataExtractor.cs index 30ff432b..d6ec93b2 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2MetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/Sentinel2/Sentinel2MetadataExtractor.cs @@ -1,13 +1,10 @@ -using System; -using System.Collections.Generic; +using System; using System.Globalization; using System.Threading.Tasks; -using System.Xml.Serialization; using Microsoft.Extensions.Logging; using Stac; using Stac.Extensions.Eo; using Terradue.OpenSearch.Sentinel.Data.Safe; -using Terradue.OpenSearch.Sentinel.Data.Safe.Sentinel.S2.Level1.Granules; using Terradue.Stars.Interface; namespace Terradue.Stars.Data.Model.Metadata.Sentinels.Sentinel2 @@ -20,7 +17,7 @@ public class Sentinel2MetadataExtractor : SentinelMetadataExtractor public Sentinel2MetadataExtractor(ILogger logger, IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) { - this.loggerS2 = logger; + loggerS2 = logger; } public override async Task ReadManifest(IAsset manifestAsset) @@ -28,7 +25,7 @@ public override async Task ReadManifest(IAsset manifestAsset) XFDUType xfdu = await base.ReadManifest(manifestAsset); if (!xfdu.informationPackageMap.contentUnit[0].textInfo.StartsWith("Sentinel-2", true, CultureInfo.InvariantCulture)) { - throw new FormatException(String.Format("Not a Sentinel-2 manifest SAFE file asset")); + throw new FormatException(string.Format("Not a Sentinel-2 manifest SAFE file asset")); } return xfdu; } @@ -49,7 +46,7 @@ protected override async Task CreateSafeStacFactoryAsyn } else { - throw new FormatException(String.Format("Not a Sentinel-2 manifest SAFE file asset")); + throw new FormatException(string.Format("Not a Sentinel-2 manifest SAFE file asset")); } return stacFactory; @@ -71,8 +68,7 @@ protected SentinelMetadataExtractor GetMatchingExtractorInstance(SentinelSafeSta // This method is not normally used, subclass method is called directly with the proper instance protected override Task AddAssets(StacItem stacItem, IItem item, SentinelSafeStacFactory stacFactory) { - Sentinel2MetadataExtractor metadataExtractor = GetMatchingExtractorInstance(stacFactory) as Sentinel2MetadataExtractor; - if (metadataExtractor == null) return Task.CompletedTask; + if (!(GetMatchingExtractorInstance(stacFactory) is Sentinel2MetadataExtractor metadataExtractor)) return Task.CompletedTask; return metadataExtractor.AddAssets(stacItem, item, stacFactory); } @@ -80,8 +76,7 @@ protected override Task AddAssets(StacItem stacItem, IItem item, SentinelSafeSta // This method is not normally used, subclass method is called directly with the proper instance protected override Task AddAdditionalProperties(StacItem stacItem, IItem item, SentinelSafeStacFactory stacFactory) { - Sentinel2MetadataExtractor metadataExtractor = GetMatchingExtractorInstance(stacFactory) as Sentinel2MetadataExtractor; - if (metadataExtractor == null) return Task.CompletedTask; + if (!(GetMatchingExtractorInstance(stacFactory) is Sentinel2MetadataExtractor metadataExtractor)) return Task.CompletedTask; Task task = metadataExtractor.AddAdditionalProperties(stacItem, item, stacFactory); @@ -209,7 +204,7 @@ public static string GetBandNameConvention(OpenSearch.Sentinel.Data.Dimap.A_PROD break; } if (resolution == originalResolution) return commonName; - return String.Format("{0}-{1}{2}", useCommonName ? commonName : bandName, resolution, useCommonName ? "m" : String.Empty); + return string.Format("{0}-{1}{2}", useCommonName ? commonName : bandName, resolution, useCommonName ? "m" : string.Empty); } } } diff --git a/src/Stars.Data/Model/Metadata/Sentinels/SentinelAssetFactory.cs b/src/Stars.Data/Model/Metadata/Sentinels/SentinelAssetFactory.cs index d1aad7df..92852091 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/SentinelAssetFactory.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/SentinelAssetFactory.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using Stac; +using Stac; using Terradue.Stars.Interface; namespace Terradue.Stars.Data.Model.Metadata.Sentinels @@ -23,4 +21,4 @@ protected SentinelAssetFactory(IResourceServiceProvider resourceServiceProvider) public abstract StacAsset CreateMetadataAsset(IStacObject stacObject); } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Sentinels/SentinelMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Sentinels/SentinelMetadataExtractor.cs index d7809aa4..6398739d 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/SentinelMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/SentinelMetadataExtractor.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mime; @@ -27,8 +26,7 @@ protected SentinelMetadataExtractor(ILogger logger, IResourceServiceProvider res public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset manifestAsset = GetManifestAsset(item); @@ -63,7 +61,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi SentinelSafeStacFactory stacFactory = await CreateSafeStacFactoryAsync(manifest, item, identifier); StacItem stacItem = stacFactory.CreateStacItem(); - + // Get the proper instance for assets and additional properties // (can be this instance or a subclass instance, e.g. for Sentinel-2) SentinelMetadataExtractor metadataExtractor = GetMatchingExtractorInstance(stacFactory); @@ -89,7 +87,7 @@ protected virtual SentinelMetadataExtractor GetMatchingExtractorInstance(Sentine { return this; } - + protected abstract Task AddAssets(StacItem stacItem, IItem item, SentinelSafeStacFactory stacFactory); protected virtual Task AddAdditionalProperties(StacItem stacItem, IItem item, SentinelSafeStacFactory stacFactory) @@ -99,11 +97,7 @@ protected virtual Task AddAdditionalProperties(StacItem stacItem, IItem item, Se protected virtual IAsset GetManifestAsset(IItem item) { - IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, "manifest.safe$"); - if (manifestAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the manifest SAFE file asset")); - } + IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, "manifest.safe$") ?? throw new FileNotFoundException(string.Format("Unable to find the manifest SAFE file asset")); return manifestAsset; } protected abstract Task CreateSafeStacFactoryAsync(XFDUType manifest, IItem item, string identifier); diff --git a/src/Stars.Data/Model/Metadata/Sentinels/SentinelSafeStacFactory.cs b/src/Stars.Data/Model/Metadata/Sentinels/SentinelSafeStacFactory.cs index d57f5588..6c4d7d96 100644 --- a/src/Stars.Data/Model/Metadata/Sentinels/SentinelSafeStacFactory.cs +++ b/src/Stars.Data/Model/Metadata/Sentinels/SentinelSafeStacFactory.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -8,9 +8,9 @@ using Stac.Extensions.Processing; using Stac.Extensions.Sat; using Terradue.OpenSearch.Sentinel.Data.Safe; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Geometry.Gml321; using Terradue.Stars.Interface; -using Terradue.Stars.Geometry.GeoJson; namespace Terradue.Stars.Data.Model.Metadata.Sentinels { @@ -89,16 +89,10 @@ private void AddProcessingStacExtension(StacItem stacItem) proc.Lineage = processing.metadataWrap.xmlData.processing.name; if (processing.metadataWrap.xmlData.processing.Items != null) { - OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType facility = - processing.metadataWrap.xmlData.processing.Items.FirstOrDefault(i => i is OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType) as - OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType; - if (facility != null) + if (processing.metadataWrap.xmlData.processing.Items.FirstOrDefault(i => i is OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType) is OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType facility) { proc.Facility = facility.name; - OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType software = - facility.Items.FirstOrDefault(i => i is OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType) as - OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType; - if (software != null) + if (facility.Items.FirstOrDefault(i => i is OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType) is OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType software) proc.Software.Add(software.name, software.version); } } @@ -109,16 +103,10 @@ private void AddProcessingStacExtension(StacItem stacItem) proc.Lineage = processing.metadataWrap.xmlData.processing11.name; if (processing.metadataWrap.xmlData.processing11.Items != null) { - OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType facility = - processing.metadataWrap.xmlData.processing11.Items.FirstOrDefault(i => i is OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType) as - OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType; - if (facility != null) + if (processing.metadataWrap.xmlData.processing11.Items.FirstOrDefault(i => i is OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType) is OpenSearch.Sentinel.Data.Safe.Sentinel10.facilityType facility) { proc.Facility = facility.name; - OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType software = - facility.Items.FirstOrDefault(i => i is OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType) as - OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType; - if (software != null) + if (facility.Items.FirstOrDefault(i => i is OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType) is OpenSearch.Sentinel.Data.Safe.Sentinel10.softwareType software) proc.Software.Add(software.name, software.version); } } @@ -360,44 +348,44 @@ public virtual IGeometryObject GetGeometry() var measurementFrameSet = xfdu.metadataSection.First(m => m.ID == "measurementFrameSet"); if (measurementFrameSet.metadataWrap.xmlData.frameSet != null && measurementFrameSet.metadataWrap.xmlData.frameSet.frame[0].footPrint != null && - measurementFrameSet.metadataWrap.xmlData.frameSet.frame[0].footPrint.Items1[0] is Terradue.ServiceModel.Ogc.Gml311.CoordinatesType) + measurementFrameSet.metadataWrap.xmlData.frameSet.frame[0].footPrint.Items1[0] is ServiceModel.Ogc.Gml311.CoordinatesType) { - Terradue.ServiceModel.Ogc.Gml311.CoordinatesType coordinates = (Terradue.ServiceModel.Ogc.Gml311.CoordinatesType)measurementFrameSet.metadataWrap.xmlData.frameSet.frame[0].footPrint.Items1[0]; + ServiceModel.Ogc.Gml311.CoordinatesType coordinates = (ServiceModel.Ogc.Gml311.CoordinatesType)measurementFrameSet.metadataWrap.xmlData.frameSet.frame[0].footPrint.Items1[0]; - var polygon = new Terradue.ServiceModel.Ogc.Gml321.PolygonType(); - polygon.exterior = new Terradue.ServiceModel.Ogc.Gml321.AbstractRingPropertyType(); - var linearRing = new Terradue.ServiceModel.Ogc.Gml321.LinearRingType(); - var posList = new List(); + var polygon = new ServiceModel.Ogc.Gml321.PolygonType(); + polygon.exterior = new ServiceModel.Ogc.Gml321.AbstractRingPropertyType(); + var linearRing = new ServiceModel.Ogc.Gml321.LinearRingType(); + var posList = new List(); - posList.Add(new Terradue.ServiceModel.Ogc.Gml321.DirectPositionListType() { Text = coordinates.Value.Replace(",", " ") }); + posList.Add(new ServiceModel.Ogc.Gml321.DirectPositionListType() { Text = coordinates.Value.Replace(",", " ") }); if (posList[0].Text.Split(' ')[1] != posList[0].Text.Split(' ').Last()) { posList[0].Text += " " + posList[0].Text.Split(' ')[0] + " " + posList[0].Text.Split(' ')[1]; } linearRing.Items = posList.ToArray(); - linearRing.ItemsElementName = new Terradue.ServiceModel.Ogc.Gml321.ItemsChoiceType6[1] { Terradue.ServiceModel.Ogc.Gml321.ItemsChoiceType6.posList }; + linearRing.ItemsElementName = new ServiceModel.Ogc.Gml321.ItemsChoiceType6[1] { Terradue.ServiceModel.Ogc.Gml321.ItemsChoiceType6.posList }; polygon.exterior.Item = linearRing; return polygon.ToGeometry().NormalizePolygon(); } if (measurementFrameSet.metadataWrap.xmlData.frameSet11 != null && measurementFrameSet.metadataWrap.xmlData.frameSet11.footPrint != null && - measurementFrameSet.metadataWrap.xmlData.frameSet11.footPrint.Items1[0] is Terradue.ServiceModel.Ogc.Gml311.CoordinatesType) + measurementFrameSet.metadataWrap.xmlData.frameSet11.footPrint.Items1[0] is ServiceModel.Ogc.Gml311.CoordinatesType) { - Terradue.ServiceModel.Ogc.Gml311.CoordinatesType coordinates = (Terradue.ServiceModel.Ogc.Gml311.CoordinatesType)measurementFrameSet.metadataWrap.xmlData.frameSet11.footPrint.Items1[0]; + ServiceModel.Ogc.Gml311.CoordinatesType coordinates = (ServiceModel.Ogc.Gml311.CoordinatesType)measurementFrameSet.metadataWrap.xmlData.frameSet11.footPrint.Items1[0]; - var polygon = new Terradue.ServiceModel.Ogc.Gml321.PolygonType(); - polygon.exterior = new Terradue.ServiceModel.Ogc.Gml321.AbstractRingPropertyType(); - var linearRing = new Terradue.ServiceModel.Ogc.Gml321.LinearRingType(); - var posList = new List(); + var polygon = new ServiceModel.Ogc.Gml321.PolygonType(); + polygon.exterior = new ServiceModel.Ogc.Gml321.AbstractRingPropertyType(); + var linearRing = new ServiceModel.Ogc.Gml321.LinearRingType(); + var posList = new List(); - posList.Add(new Terradue.ServiceModel.Ogc.Gml321.DirectPositionListType() { Text = coordinates.Value.Replace(",", " ") }); + posList.Add(new ServiceModel.Ogc.Gml321.DirectPositionListType() { Text = coordinates.Value.Replace(",", " ") }); if (posList[0].Text.Split(' ')[1] != posList[0].Text.Split(' ').Last()) { posList[0].Text += " " + posList[0].Text.Split(' ')[0] + " " + posList[0].Text.Split(' ')[1]; } linearRing.Items = posList.ToArray(); - linearRing.ItemsElementName = new Terradue.ServiceModel.Ogc.Gml321.ItemsChoiceType6[1] { Terradue.ServiceModel.Ogc.Gml321.ItemsChoiceType6.posList }; + linearRing.ItemsElementName = new ServiceModel.Ogc.Gml321.ItemsChoiceType6[1] { Terradue.ServiceModel.Ogc.Gml321.ItemsChoiceType6.posList }; polygon.exterior.Item = linearRing; return polygon.ToGeometry().NormalizePolygon(); @@ -409,4 +397,4 @@ public virtual IGeometryObject GetGeometry() public abstract string GetProductType(); } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/TerrasarX/TerrasarXMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/TerrasarX/TerrasarXMetadataExtractor.cs index c57e40d7..9b0c8716 100644 --- a/src/Stars.Data/Model/Metadata/TerrasarX/TerrasarXMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/TerrasarX/TerrasarXMetadataExtractor.cs @@ -1,7 +1,8 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Linq; using System.Net.Mime; using System.Threading.Tasks; using System.Xml; @@ -10,14 +11,13 @@ using Stac; using Stac.Extensions.Processing; using Stac.Extensions.Projection; -using Stac.Extensions.Sat; using Stac.Extensions.Sar; +using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; -using System.Linq; namespace Terradue.Stars.Data.Model.Metadata.TerrasarX { @@ -33,8 +33,7 @@ public TerrasarXMetadataExtractor(ILogger logger, IR public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset metadataAsset = GetMetadataAsset(item); @@ -234,7 +233,7 @@ private void FillDateTimeProperties(level1Product metadata, Dictionary properties) + private void FillBasicsProperties(level1Product metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); properties.Remove("title"); @@ -256,7 +255,7 @@ private void AddOtherProperties(level1Product metadata, StacItem stacItem) { AddSingleProvider( stacItem.Properties, - "DLR", + "DLR", "TerraSAR-X is a German Earth-observation satellite. Its primary payload is an X-band radar sensor with a range of different modes of operation, allowing it to record images with different swath widths, resolutions and polarisations.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.dlr.de/content/en/articles/missions-projects/terrasar-x/terrasar-x-earth-observation-satellite.html") @@ -270,10 +269,7 @@ private void AddOtherProperties(level1Product metadata, StacItem stacItem) private XmlDocument ReadGeometryFile(IItem item) { var coordinatesDocument = new XmlDocument(); - var fileAsset = FindFirstAssetFromFileNameRegex(item, @".*_iif.*\.xml"); - if (fileAsset == null) - throw new FileNotFoundException(string.Format("Coordinates file not found ")); - + var fileAsset = FindFirstAssetFromFileNameRegex(item, @".*_iif.*\.xml") ?? throw new FileNotFoundException(string.Format("Coordinates file not found ")); coordinatesDocument.Load(resourceServiceProvider.GetAssetStreamAsync(fileAsset, System.Threading.CancellationToken.None).GetAwaiter().GetResult()); @@ -324,10 +320,7 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometry(level1Product metadata, protected void AddAssets(StacItem stacItem, IItem item, level1Product metadata) { string tifFileName = metadata.productComponents.imageData[0].file.location.filename; - IAsset amplitudeAsset = FindFirstAssetFromFileNameRegex(item, tifFileName + "$"); - - if (amplitudeAsset == null) - throw new FileNotFoundException(string.Format("No product found '{0}'", tifFileName)); + IAsset amplitudeAsset = FindFirstAssetFromFileNameRegex(item, tifFileName + "$") ?? throw new FileNotFoundException(string.Format("No product found '{0}'", tifFileName)); var bandStacAsset = AddBandAsset(stacItem, amplitudeAsset, metadata, item); //amplitude-hh var metadataAsset = FindFirstAssetFromFileNameRegex(item, @".*L1B.*\.xml"); //metadata @@ -352,9 +345,7 @@ protected void AddAssets(StacItem stacItem, IItem item, level1Product metadata) throw new FileNotFoundException(string.Format("TSX-1 product-metadata file not found ")); - IAsset overviewAsset = FindFirstAssetFromFileNameRegex(item, @".*COMPOSITE.*\.tif"); //overwiew - if (overviewAsset == null) - throw new FileNotFoundException(string.Format("No product found '{0}'", "")); + IAsset overviewAsset = FindFirstAssetFromFileNameRegex(item, @".*COMPOSITE.*\.tif") ?? throw new FileNotFoundException(string.Format("No product found '{0}'", "")); //overwiew stacItem.Assets.Add("overview", StacAsset.CreateOverviewAsset(stacItem, overviewAsset.Uri, new ContentType(MimeTypes.GetMimeType(overviewAsset.Uri.ToString())))); stacItem.Assets["overview"].Properties.AddRange(overviewAsset.Properties); @@ -364,7 +355,7 @@ protected void AddAssets(StacItem stacItem, IItem item, level1Product metadata) private string AddBandAsset(StacItem stacItem, IAsset bandAsset, level1Product metadata, IItem item) { - StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, bandAsset.Uri, new System.Net.Mime.ContentType("image/x.geotiff")); + StacAsset stacAsset = StacAsset.CreateDataAsset(stacItem, bandAsset.Uri, new ContentType("image/x.geotiff")); stacAsset.Properties.AddRange(bandAsset.Properties); stacAsset.SetProperty("gsd", GetGroundSampleDistance(metadata, item)); stacAsset.Properties.Add("sar:polarizations", GetPolarizations(metadata)); @@ -416,11 +407,7 @@ private double GetGroundSampleDistance(level1Product metadata, IItem item) protected virtual IAsset GetMetadataAsset(IItem item) { - IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"T(S|D)X1_SAR.*\.xml$"); - if (manifestAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } + IAsset manifestAsset = FindFirstAssetFromFileNameRegex(item, @"T(S|D)X1_SAR.*\.xml$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); return manifestAsset; } @@ -444,4 +431,4 @@ protected KeyValuePair CreateManifestAsset(IStacObject stacOb return new KeyValuePair("manifest", stacAsset); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Vrss/Schemas/Metadata.cs b/src/Stars.Data/Model/Metadata/Vrss/Schemas/Metadata.cs index a516743b..eb03fb99 100644 --- a/src/Stars.Data/Model/Metadata/Vrss/Schemas/Metadata.cs +++ b/src/Stars.Data/Model/Metadata/Vrss/Schemas/Metadata.cs @@ -1,4 +1,4 @@ -namespace Terradue.Stars.Data.Model.Metadata.Vrss.Schemas +namespace Terradue.Stars.Data.Model.Metadata.Vrss.Schemas { /// diff --git a/src/Stars.Data/Model/Metadata/Vrss/VrssMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Vrss/VrssMetadataExtractor.cs index 49e5310d..d5ae1073 100644 --- a/src/Stars.Data/Model/Metadata/Vrss/VrssMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Vrss/VrssMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -13,13 +13,13 @@ using Stac.Extensions.Eo; using Stac.Extensions.Processing; using Stac.Extensions.Projection; +using Stac.Extensions.Raster; using Stac.Extensions.Sat; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; using Terradue.Stars.Services.Model.Stac; -using Terradue.Stars.Geometry.GeoJson; -using Stac.Extensions.Raster; namespace Terradue.Stars.Data.Model.Metadata.Vrss { @@ -35,7 +35,7 @@ public class VrssMetadataExtractor : MetadataExtraction private Regex utmZoneRegex = new Regex(@"(?'num'\d+)(?'hem'[NS])"); public static XmlSerializer metadataSerializer = new XmlSerializer(typeof(Schemas.Metadata)); - + public override string Label => "Venezuelan Remote Sensing Satellite (ABAE) mission product metadata extractor"; public VrssMetadataExtractor(ILogger logger, IResourceServiceProvider resourceServiceProvider) : base(logger, resourceServiceProvider) @@ -44,8 +44,7 @@ public VrssMetadataExtractor(ILogger logger, IResourceSer public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; try { IAsset metadataAsset = GetMetadataAsset(item); @@ -76,7 +75,7 @@ protected override async Task ExtractMetadata(IItem item, string suffi FillBasicsProperties(metadata, stacItem.Properties); AddOtherProperties(metadata, stacItem.Properties); - return StacItemNode.Create(stacItem, item.Uri);; + return StacItemNode.Create(stacItem, item.Uri); ; } internal virtual StacItem CreateStacItem(Schemas.Metadata metadata) @@ -85,12 +84,12 @@ internal virtual StacItem CreateStacItem(Schemas.Metadata metadata) Match identifierMatch = identifierRegex.Match(metadata.imageName); if (!identifierMatch.Success) { - throw new InvalidOperationException(String.Format("Identifier not recognised from image name: {0}", metadata.imageName)); + throw new InvalidOperationException(string.Format("Identifier not recognised from image name: {0}", metadata.imageName)); } string identifier = identifierMatch.Groups["id"].Value; StacItem stacItem = new StacItem(identifier, GetGeometry(metadata), GetCommonMetadata(metadata)); - + return stacItem; } @@ -116,11 +115,7 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometry(Schemas.Metadata metada protected virtual IAsset GetMetadataAsset(IItem item) { - IAsset metadataAsset = FindFirstAssetFromFileNameRegex(item, @"VRSS-[12]_.*\d\.xml$"); - if (metadataAsset == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } + IAsset metadataAsset = FindFirstAssetFromFileNameRegex(item, @"VRSS-[12]_.*\d\.xml$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); return metadataAsset; } @@ -197,16 +192,16 @@ private void FillInstrument(Schemas.Metadata metadata, Dictionary properties) + private void FillBasicsProperties(Schemas.Metadata metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); - properties["title"] = String.Format("{0} {1} {2} {3}", + properties["title"] = string.Format("{0} {1} {2} {3}", metadata.satelliteId, metadata.sensorId, GetProcessingLevel(metadata), @@ -214,13 +209,13 @@ private void FillBasicsProperties(Schemas.Metadata metadata, IDictionary properties) + private void AddOtherProperties(Schemas.Metadata metadata, IDictionary properties) { if (IncludeProviderProperty) { AddSingleProvider( properties, - "ABAE", + "ABAE", "The Venezuelan VRSS missions provide high-resolution land and vegetation observations to assess Venezuela's soil and water resources, collect images to help urban planners, monitor illegal mining and drug activities, and strengthen national defense, and support of disaster monitoring.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://www.eoportal.org/satellite-missions/vrss-1") @@ -257,7 +252,7 @@ private void AddProjStacExtension(Schemas.Metadata metadata, StacItem stacItem) ProjectionStacExtension proj = stacItem.ProjectionExtension(); //proj.Wkt2 = ProjNet.CoordinateSystems.GeocentricCoordinateSystem.WGS84.WKT; - int zone = Int32.Parse(utmZoneMatch.Groups["num"].Value); + int zone = int.Parse(utmZoneMatch.Groups["num"].Value); bool north = utmZoneMatch.Groups["hem"].Value == "N"; ProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(zone, north); proj.SetCoordinateSystem(utm); @@ -267,15 +262,15 @@ private void AddProjStacExtension(Schemas.Metadata metadata, StacItem stacItem) private void AddViewStacExtension(Schemas.Metadata metadata, StacItem stacItem) { var view = new ViewStacExtension(stacItem); - if (Double.TryParse(metadata.satOffNadir, out double offNadir)) + if (double.TryParse(metadata.satOffNadir, out double offNadir)) { view.OffNadir = Math.Abs(offNadir); - } - if (metadata.sunAzimuth != null && metadata.sunAzimuth.Length != 0 && Double.TryParse(metadata.sunAzimuth[0].Value, out double sunAzimuth)) + } + if (metadata.sunAzimuth != null && metadata.sunAzimuth.Length != 0 && double.TryParse(metadata.sunAzimuth[0].Value, out double sunAzimuth)) { view.SunAzimuth = sunAzimuth; } - if (metadata.sunElevation != null && metadata.sunElevation.Length != 0 && Double.TryParse(metadata.sunElevation[0].Value, out double sunElevation)) + if (metadata.sunElevation != null && metadata.sunElevation.Length != 0 && double.TryParse(metadata.sunElevation[0].Value, out double sunElevation)) { view.SunElevation = sunElevation; } @@ -294,35 +289,29 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat string[] imageFiles = metadata.imageName.Split(','); foreach (string imageFile in imageFiles) { - IAsset imageAsset = FindFirstAssetFromFileNameRegex(item, String.Format("{0}$", imageFile)); - if (imageAsset == null) - throw new FileNotFoundException(string.Format("Image file declared in metadata, but not present '{0}'", metadata.browseName)); + IAsset imageAsset = FindFirstAssetFromFileNameRegex(item, string.Format("{0}$", imageFile)) ?? throw new FileNotFoundException(string.Format("Image file declared in metadata, but not present '{0}'", metadata.browseName)); Match match = identifierRegex.Match(imageFile); - + string type = match.Groups["type"].Value; - string key; - if ((type == "MSS" || type == "WMC") && match.Groups["n"].Success) key = String.Format("band-{0}", match.Groups["n"].Value); + string key; + if ((type == "MSS" || type == "WMC") && match.Groups["n"].Success) key = string.Format("band-{0}", match.Groups["n"].Value); else if (type == "PAN") key = "pan"; else key = "image"; - int index = (match.Groups["n"].Success ? Int32.Parse(match.Groups["n"].Value) - 1 : 0); - + int index = (match.Groups["n"].Success ? int.Parse(match.Groups["n"].Value) - 1 : 0); + AddBandStacAsset(stacItem, type, key, index, imageAsset, metadata); } - + if (metadata.browseName != null) { - IAsset browseAsset = FindFirstAssetFromFileNameRegex(item, String.Format("{0}$", metadata.browseName)); - if (browseAsset == null) - throw new FileNotFoundException(string.Format("Browse image declared in metadata, but not present '{0}'", metadata.browseName)); + IAsset browseAsset = FindFirstAssetFromFileNameRegex(item, string.Format("{0}$", metadata.browseName)) ?? throw new FileNotFoundException(string.Format("Browse image declared in metadata, but not present '{0}'", metadata.browseName)); stacItem.Assets.Add("overview", StacAsset.CreateOverviewAsset(stacItem, browseAsset.Uri, new ContentType(MimeTypes.GetMimeType(browseAsset.Uri.OriginalString)), "Browse image")); stacItem.Assets["overview"].Properties.AddRange(browseAsset.Properties); } if (metadata.thumbName != null) { - IAsset thumbAsset = FindFirstAssetFromFileNameRegex(item, String.Format("{0}$", metadata.thumbName)); - if (thumbAsset == null) - throw new FileNotFoundException(string.Format("Thumbnail image declared in metadata, but not present '{0}'", metadata.thumbName)); + IAsset thumbAsset = FindFirstAssetFromFileNameRegex(item, string.Format("{0}$", metadata.thumbName)) ?? throw new FileNotFoundException(string.Format("Thumbnail image declared in metadata, but not present '{0}'", metadata.thumbName)); stacItem.Assets.Add("thumbnail", StacAsset.CreateThumbnailAsset(stacItem, thumbAsset.Uri, new ContentType(MimeTypes.GetMimeType(thumbAsset.Uri.OriginalString)), "Thumbnail image")); stacItem.Assets["thumbnail"].Properties.AddRange(thumbAsset.Properties); } @@ -332,7 +321,8 @@ protected void AddAssets(StacItem stacItem, IItem item, Schemas.Metadata metadat stacItem.Assets["metadata"].Properties.AddRange(metadataAsset.Properties); IAsset additionalMetadataAsset = FindFirstAssetFromFileNameRegex(item, @"VRSS-[12]_.*ADDITION\.xml$"); - if (additionalMetadataAsset != null){ + if (additionalMetadataAsset != null) + { stacItem.Assets.Add("metadata-addition", StacAsset.CreateMetadataAsset(stacItem, additionalMetadataAsset.Uri, new ContentType(MimeTypes.GetMimeType(additionalMetadataAsset.Uri.OriginalString)), "Additional metadata")); stacItem.Assets["metadata-addition"].Properties.AddRange(additionalMetadataAsset.Properties); } @@ -348,7 +338,7 @@ private void AddBandStacAsset(StacItem stacItem, string type, string assetkey, i EoBandCommonName commonName = new EoBandCommonName(); bool notFound = false; - var dataSize = Array.ConvertAll(metadata.dataSize.Split(','), a => Int32.Parse(a)); + var dataSize = Array.ConvertAll(metadata.dataSize.Split(','), a => int.Parse(a)); stacAsset.ProjectionExtension().Shape = dataSize; if (type == "PAN") @@ -362,7 +352,8 @@ private void AddBandStacAsset(StacItem stacItem, string type, string assetkey, i } else if (type == "MSS" || type == "WMC") { - switch (index + 1) { + switch (index + 1) + { case 1: wavelength = 0.485; commonName = EoBandCommonName.blue; @@ -391,7 +382,7 @@ private void AddBandStacAsset(StacItem stacItem, string type, string assetkey, i if (notFound) { - throw new InvalidOperationException(String.Format("Band information not found for {0}", assetkey)); + throw new InvalidOperationException(string.Format("Band information not found for {0}", assetkey)); } EoBandObject eoBandObject = new EoBandObject(assetkey, commonName); @@ -400,15 +391,15 @@ private void AddBandStacAsset(StacItem stacItem, string type, string assetkey, i { // Note: for VRSS-2 IRC-2 has to be used instead of for the offset calculation // No such sample data exists at the moment and no corresponding property in the metadata class - bool existK = Double.TryParse(metadata.ab_calibra_param[index].K, out double k) && k != 0; - bool existB = Double.TryParse(metadata.ab_calibra_param[index].B, out double b); - if (Double.TryParse(metadata.SolarIrradiance[index].Value, out double eai)) + bool existK = double.TryParse(metadata.ab_calibra_param[index].K, out double k) && k != 0; + bool existB = double.TryParse(metadata.ab_calibra_param[index].B, out double b); + if (double.TryParse(metadata.SolarIrradiance[index].Value, out double eai)) eoBandObject.SolarIllumination = eai; if (existK && existB) { RasterBand rasterBand = new RasterBand(); rasterBand.Scale = 1 / k; - rasterBand.Offset = - (b / k); + rasterBand.Offset = -(b / k); stacAsset.RasterExtension().Bands = new RasterBand[] { rasterBand }; } } diff --git a/src/Stars.Data/Model/Metadata/Worldview/IsdMetadata.cs b/src/Stars.Data/Model/Metadata/Worldview/IsdMetadata.cs index ca7c6014..d50030d2 100644 --- a/src/Stars.Data/Model/Metadata/Worldview/IsdMetadata.cs +++ b/src/Stars.Data/Model/Metadata/Worldview/IsdMetadata.cs @@ -1,11 +1,12 @@ -using System; +using System.Collections.Generic; using System.Xml.Serialization; -using System.Collections.Generic; -namespace Terradue.Stars.Data.Model.Metadata.Worldview { +namespace Terradue.Stars.Data.Model.Metadata.Worldview +{ [XmlRoot(ElementName = "BAND")] - public class BAND { + public class BAND + { [XmlElement(ElementName = "ULLON")] public string ULLON { get; set; } [XmlElement(ElementName = "ULLAT")] public string ULLAT { get; set; } [XmlElement(ElementName = "ULHAE")] public string ULHAE { get; set; } @@ -33,12 +34,14 @@ public class BAND { } [XmlRoot(ElementName = "TLCLISTList")] - public class TLCLISTList { + public class TLCLISTList + { [XmlElement(ElementName = "TLCLIST")] public List TLCLIST { get; set; } } [XmlRoot(ElementName = "IMAGE")] - public class IMAGE { + public class IMAGE + { [XmlElement(ElementName = "SATID")] public string SATID { get; set; } [XmlElement(ElementName = "MODE")] public string MODE { get; set; } @@ -211,7 +214,8 @@ public class IMAGE { } [XmlRoot(ElementName = "IMD")] - public class IMD { + public class IMD + { [XmlElement(ElementName = "VERSION")] public string VERSION { get; set; } [XmlElement(ElementName = "GENERATIONTIME")] @@ -282,13 +286,15 @@ public class IMD { } [XmlRoot(ElementName = "EPHEMLISTList")] - public class EPHEMLISTList { + public class EPHEMLISTList + { [XmlElement(ElementName = "EPHEMLIST")] public List EPHEMLIST { get; set; } } [XmlRoot(ElementName = "EPH")] - public class EPH { + public class EPH + { [XmlElement(ElementName = "SATID")] public string SATID { get; set; } [XmlElement(ElementName = "REVNUMBER")] @@ -315,12 +321,14 @@ public class EPH { } [XmlRoot(ElementName = "ATTLISTList")] - public class ATTLISTList { + public class ATTLISTList + { [XmlElement(ElementName = "ATTLIST")] public List ATTLIST { get; set; } } [XmlRoot(ElementName = "ATT")] - public class ATT { + public class ATT + { [XmlElement(ElementName = "SATID")] public string SATID { get; set; } [XmlElement(ElementName = "REVNUMBER")] @@ -347,7 +355,8 @@ public class ATT { } [XmlRoot(ElementName = "TILE")] - public class TILE { + public class TILE + { [XmlElement(ElementName = "FILENAME")] public string FILENAME { get; set; } [XmlElement(ElementName = "ULCOLOFFSET")] @@ -385,7 +394,8 @@ public class TILE { } [XmlRoot(ElementName = "TIL")] - public class TIL { + public class TIL + { [XmlElement(ElementName = "BANDID")] public string BANDID { get; set; } [XmlElement(ElementName = "NUMTILES")] public string NUMTILES { get; set; } @@ -405,7 +415,8 @@ public class TIL { } [XmlRoot(ElementName = "PRINCIPAL_DISTANCE")] - public class PRINCIPAL_DISTANCE { + public class PRINCIPAL_DISTANCE + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -413,7 +424,8 @@ public class PRINCIPAL_DISTANCE { } [XmlRoot(ElementName = "OPTICAL_DISTORTION")] - public class OPTICAL_DISTORTION { + public class OPTICAL_DISTORTION + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -428,7 +440,8 @@ public class OPTICAL_DISTORTION { } [XmlRoot(ElementName = "PERSPECTIVE_CENTER")] - public class PERSPECTIVE_CENTER { + public class PERSPECTIVE_CENTER + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -438,7 +451,8 @@ public class PERSPECTIVE_CENTER { } [XmlRoot(ElementName = "CAMERA_ATTITUDE")] - public class CAMERA_ATTITUDE { + public class CAMERA_ATTITUDE + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -449,7 +463,8 @@ public class CAMERA_ATTITUDE { } [XmlRoot(ElementName = "DETECTOR_ARRAY")] - public class DETECTOR_ARRAY { + public class DETECTOR_ARRAY + { [XmlElement(ElementName = "DETARRID")] public string DETARRID { get; set; } [XmlElement(ElementName = "DETORIGINX")] @@ -465,7 +480,8 @@ public class DETECTOR_ARRAY { } [XmlRoot(ElementName = "DETECTOR_MOUNTING")] - public class DETECTOR_MOUNTING { + public class DETECTOR_MOUNTING + { [XmlElement(ElementName = "GENERATIONTIME")] public string GENERATIONTIME { get; set; } @@ -473,7 +489,8 @@ public class DETECTOR_MOUNTING { } [XmlRoot(ElementName = "GEO")] - public class GEO { + public class GEO + { [XmlElement(ElementName = "EFFECTIVETIME")] public string EFFECTIVETIME { get; set; } @@ -502,31 +519,36 @@ public class GEO { } [XmlRoot(ElementName = "LINENUMCOEFList")] - public class LINENUMCOEFList { + public class LINENUMCOEFList + { [XmlElement(ElementName = "LINENUMCOEF")] public string LINENUMCOEF { get; set; } } [XmlRoot(ElementName = "LINEDENCOEFList")] - public class LINEDENCOEFList { + public class LINEDENCOEFList + { [XmlElement(ElementName = "LINEDENCOEF")] public string LINEDENCOEF { get; set; } } [XmlRoot(ElementName = "SAMPNUMCOEFList")] - public class SAMPNUMCOEFList { + public class SAMPNUMCOEFList + { [XmlElement(ElementName = "SAMPNUMCOEF")] public string SAMPNUMCOEF { get; set; } } [XmlRoot(ElementName = "SAMPDENCOEFList")] - public class SAMPDENCOEFList { + public class SAMPDENCOEFList + { [XmlElement(ElementName = "SAMPDENCOEF")] public string SAMPDENCOEF { get; set; } } [XmlRoot(ElementName = "RPB")] - public class RPB { + public class RPB + { [XmlElement(ElementName = "SATID")] public string SATID { get; set; } [XmlElement(ElementName = "BANDID")] public string BANDID { get; set; } [XmlElement(ElementName = "SPECID")] public string SPECID { get; set; } @@ -534,7 +556,8 @@ public class RPB { } [XmlRoot(ElementName = "isd")] - public class Isd { + public class Isd + { [XmlElement(ElementName = "IMD")] public IMD IMD { get; set; } [XmlElement(ElementName = "EPH")] public EPH EPH { get; set; } [XmlElement(ElementName = "ATT")] public ATT ATT { get; set; } @@ -542,4 +565,4 @@ public class Isd { [XmlElement(ElementName = "GEO")] public GEO GEO { get; set; } [XmlElement(ElementName = "RPB")] public RPB RPB { get; set; } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/Metadata/Worldview/WorldviewMetadataExtractor.cs b/src/Stars.Data/Model/Metadata/Worldview/WorldviewMetadataExtractor.cs index 3d7d90d8..b2c10bc2 100644 --- a/src/Stars.Data/Model/Metadata/Worldview/WorldviewMetadataExtractor.cs +++ b/src/Stars.Data/Model/Metadata/Worldview/WorldviewMetadataExtractor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -12,14 +12,14 @@ using Stac; using Stac.Extensions.Eo; using Stac.Extensions.Processing; +using Stac.Extensions.Projection; +using Stac.Extensions.Raster; using Stac.Extensions.View; +using Terradue.Stars.Geometry.GeoJson; using Terradue.Stars.Interface; using Terradue.Stars.Interface.Supplier.Destination; -using Terradue.Stars.Services.Model.Stac; -using Stac.Extensions.Raster; using Terradue.Stars.Services; -using Terradue.Stars.Geometry.GeoJson; -using Stac.Extensions.Projection; +using Terradue.Stars.Services.Model.Stac; namespace Terradue.Stars.Data.Model.Metadata.Worldview { @@ -31,8 +31,7 @@ public WorldviewMetadataExtractor(ILogger logger, IR public override bool CanProcess(IResource route, IDestination destination) { - IItem item = route as IItem; - if (item == null) return false; + if (!(route is IItem item)) return false; IAsset metadata = FindFirstAssetFromFileNameRegex(item, "^(WV)[0-9a-zA-Z_-]*(\\.txt)$"); @@ -49,13 +48,8 @@ public override bool CanProcess(IResource route, IDestination destination) protected override async Task ExtractMetadata(IItem item, string suffix) { logger.LogDebug("Retrieving the metadata file in the product package"); - IAsset metadataFile = FindFirstAssetFromFileNameRegex(item, "^(WV)[0-9a-zA-Z_-]*(\\.txt)$"); - if (metadataFile == null) - { - throw new FileNotFoundException(String.Format("Unable to find the metadata file asset")); - } - - logger.LogDebug(String.Format("Metadata file is {0}", metadataFile.Uri)); + IAsset metadataFile = FindFirstAssetFromFileNameRegex(item, "^(WV)[0-9a-zA-Z_-]*(\\.txt)$") ?? throw new FileNotFoundException(string.Format("Unable to find the metadata file asset")); + logger.LogDebug(string.Format("Metadata file is {0}", metadataFile.Uri)); // loading properties in dictionary @@ -141,7 +135,8 @@ private void AddAsset(StacItem stacItem, string filename = Path.GetFileName(asset.Uri.ToString()); // thumbnail - if (filename.EndsWith(".XML", true, CultureInfo.InvariantCulture)){ + if (filename.EndsWith(".XML", true, CultureInfo.InvariantCulture)) + { stacItem.Assets.Add("manifest", GetGenericAsset(stacItem, asset, new[] { "metadata" })); } @@ -555,7 +550,7 @@ private void FillDateTimeProperties(JavaProperties metadata, } } - private void FillBasicsProperties(JavaProperties metadata, IDictionary properties) + private void FillBasicsProperties(JavaProperties metadata, IDictionary properties) { CultureInfo culture = new CultureInfo("fr-FR"); // title @@ -569,13 +564,13 @@ private void FillBasicsProperties(JavaProperties metadata, IDictionary properties) + private void AddOtherProperties(JavaProperties metadata, IDictionary properties) { if (IncludeProviderProperty) { AddSingleProvider( properties, - "DigitalGlobe/Maxar", + "DigitalGlobe/Maxar", "WorldView are commercial imaging satellites of DigitalGlobe Inc. of Longmont, CO, USA. The overall objective is to meet the growing commercial demand for high-resolution satellite imagery.", new StacProviderRole[] { StacProviderRole.producer, StacProviderRole.processor, StacProviderRole.licensor }, new Uri("https://gisgeography.com/digitalglobe-satellite-imagery/") @@ -619,7 +614,7 @@ private RasterBand CreateRasterBandObject(double offset, double gain) private void AddProjStacExtension(Isd auxiliary, StacItem stacItem) { - stacItem.ProjectionExtension().Epsg = null; + stacItem.ProjectionExtension().Epsg = null; } @@ -643,4 +638,4 @@ private GeoJSON.Net.Geometry.IGeometryObject GetGeometryObjectFromProductMetadat return new GeoJSON.Net.Geometry.Polygon(new[] { lineString }).NormalizePolygon(); } } -} \ No newline at end of file +} diff --git a/src/Stars.Data/Model/OpenSearchMetadata.cs b/src/Stars.Data/Model/OpenSearchMetadata.cs index f946f10a..3a32a217 100644 --- a/src/Stars.Data/Model/OpenSearchMetadata.cs +++ b/src/Stars.Data/Model/OpenSearchMetadata.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using Terradue.Metadata.EarthObservation.OpenSearch.Extensions; -using Terradue.OpenSearch.Result; - -namespace Terradue.Stars.Data.Model +namespace Terradue.Stars.Data.Model { public static class OpenSearchMetadata { diff --git a/src/Stars.Data/Model/Shared/Kml.cs b/src/Stars.Data/Model/Shared/Kml.cs index b501401a..b415ba7f 100644 --- a/src/Stars.Data/Model/Shared/Kml.cs +++ b/src/Stars.Data/Model/Shared/Kml.cs @@ -1,233 +1,252 @@ +using System.Collections.Generic; using System.Xml.Serialization; -using System.Collections.Generic; -using System; namespace Terradue.Stars.Data.Model.Shared { - [XmlRoot(ElementName="LineStyle", Namespace="")] - public class LineStyle { + [XmlRoot(ElementName = "LineStyle", Namespace = "")] + public class LineStyle + { - [XmlElement(ElementName="color", Namespace="")] - public string Color { get; set; } + [XmlElement(ElementName = "color", Namespace = "")] + public string Color { get; set; } } - [XmlRoot(ElementName="PolyStyle", Namespace="")] - public class PolyStyle { + [XmlRoot(ElementName = "PolyStyle", Namespace = "")] + public class PolyStyle + { - [XmlElement(ElementName="fill", Namespace="")] - public int Fill { get; set; } + [XmlElement(ElementName = "fill", Namespace = "")] + public int Fill { get; set; } } - [XmlRoot(ElementName="Style", Namespace="")] - public class Style { + [XmlRoot(ElementName = "Style", Namespace = "")] + public class Style + { - [XmlElement(ElementName="LineStyle", Namespace="")] - public LineStyle LineStyle { get; set; } + [XmlElement(ElementName = "LineStyle", Namespace = "")] + public LineStyle LineStyle { get; set; } - [XmlElement(ElementName="PolyStyle", Namespace="")] - public PolyStyle PolyStyle { get; set; } + [XmlElement(ElementName = "PolyStyle", Namespace = "")] + public PolyStyle PolyStyle { get; set; } - [XmlAttribute(AttributeName="id", Namespace="")] - public string Id { get; set; } + [XmlAttribute(AttributeName = "id", Namespace = "")] + public string Id { get; set; } - [XmlText] - public string Text { get; set; } + [XmlText] + public string Text { get; set; } - [XmlElement(ElementName="IconStyle", Namespace="")] - public IconStyle IconStyle { get; set; } + [XmlElement(ElementName = "IconStyle", Namespace = "")] + public IconStyle IconStyle { get; set; } - [XmlElement(ElementName="BalloonStyle", Namespace="")] - public BalloonStyle BalloonStyle { get; set; } + [XmlElement(ElementName = "BalloonStyle", Namespace = "")] + public BalloonStyle BalloonStyle { get; set; } } - [XmlRoot(ElementName="Icon", Namespace="")] - public class Icon { + [XmlRoot(ElementName = "Icon", Namespace = "")] + public class Icon + { - [XmlElement(ElementName="href", Namespace="")] - public string Href { get; set; } + [XmlElement(ElementName = "href", Namespace = "")] + public string Href { get; set; } } - [XmlRoot(ElementName="IconStyle", Namespace="")] - public class IconStyle { + [XmlRoot(ElementName = "IconStyle", Namespace = "")] + public class IconStyle + { - [XmlElement(ElementName="scale", Namespace="")] - public double Scale { get; set; } + [XmlElement(ElementName = "scale", Namespace = "")] + public double Scale { get; set; } - [XmlElement(ElementName="Icon", Namespace="")] - public Icon Icon { get; set; } + [XmlElement(ElementName = "Icon", Namespace = "")] + public Icon Icon { get; set; } } - [XmlRoot(ElementName="BalloonStyle", Namespace="")] - public class BalloonStyle { + [XmlRoot(ElementName = "BalloonStyle", Namespace = "")] + public class BalloonStyle + { - [XmlElement(ElementName="text", Namespace="")] - public string Text { get; set; } + [XmlElement(ElementName = "text", Namespace = "")] + public string Text { get; set; } } - [XmlRoot(ElementName="Pair", Namespace="")] - public class Pair { + [XmlRoot(ElementName = "Pair", Namespace = "")] + public class Pair + { - [XmlElement(ElementName="key", Namespace="")] - public string Key { get; set; } + [XmlElement(ElementName = "key", Namespace = "")] + public string Key { get; set; } - [XmlElement(ElementName="styleUrl", Namespace="")] - public string StyleUrl { get; set; } + [XmlElement(ElementName = "styleUrl", Namespace = "")] + public string StyleUrl { get; set; } } - [XmlRoot(ElementName="StyleMap", Namespace="")] - public class StyleMap { + [XmlRoot(ElementName = "StyleMap", Namespace = "")] + public class StyleMap + { - [XmlElement(ElementName="Pair", Namespace="")] - public List Pair { get; set; } + [XmlElement(ElementName = "Pair", Namespace = "")] + public List Pair { get; set; } - [XmlAttribute(AttributeName="id", Namespace="")] - public string Id { get; set; } + [XmlAttribute(AttributeName = "id", Namespace = "")] + public string Id { get; set; } - [XmlText] - public string Text { get; set; } + [XmlText] + public string Text { get; set; } } - [XmlRoot(ElementName="LookAt", Namespace="")] - public class LookAt { + [XmlRoot(ElementName = "LookAt", Namespace = "")] + public class LookAt + { - [XmlElement(ElementName="longitude", Namespace="")] - public double Longitude { get; set; } + [XmlElement(ElementName = "longitude", Namespace = "")] + public double Longitude { get; set; } - [XmlElement(ElementName="latitude", Namespace="")] - public double Latitude { get; set; } + [XmlElement(ElementName = "latitude", Namespace = "")] + public double Latitude { get; set; } - [XmlElement(ElementName="range", Namespace="")] - public int Range { get; set; } + [XmlElement(ElementName = "range", Namespace = "")] + public int Range { get; set; } } - [XmlRoot(ElementName="Point", Namespace="")] - public class Point { + [XmlRoot(ElementName = "Point", Namespace = "")] + public class Point + { - [XmlElement(ElementName="coordinates", Namespace="")] - public string Coordinates { get; set; } + [XmlElement(ElementName = "coordinates", Namespace = "")] + public string Coordinates { get; set; } } - [XmlRoot(ElementName="Placemark", Namespace="")] - public class Placemark { + [XmlRoot(ElementName = "Placemark", Namespace = "")] + public class Placemark + { - [XmlElement(ElementName="name", Namespace="")] - public string Name { get; set; } + [XmlElement(ElementName = "name", Namespace = "")] + public string Name { get; set; } - [XmlElement(ElementName="description", Namespace="")] - public string Description { get; set; } + [XmlElement(ElementName = "description", Namespace = "")] + public string Description { get; set; } - [XmlElement(ElementName="LookAt", Namespace="")] - public LookAt LookAt { get; set; } + [XmlElement(ElementName = "LookAt", Namespace = "")] + public LookAt LookAt { get; set; } - [XmlElement(ElementName="Point", Namespace="")] - public Point Point { get; set; } + [XmlElement(ElementName = "Point", Namespace = "")] + public Point Point { get; set; } - [XmlElement(ElementName="styleUrl", Namespace="")] - public string StyleUrl { get; set; } + [XmlElement(ElementName = "styleUrl", Namespace = "")] + public string StyleUrl { get; set; } - [XmlElement(ElementName="MultiGeometry", Namespace="")] - public MultiGeometry MultiGeometry { get; set; } + [XmlElement(ElementName = "MultiGeometry", Namespace = "")] + public MultiGeometry MultiGeometry { get; set; } } - [XmlRoot(ElementName="LinearRing", Namespace="")] - public class LinearRing { + [XmlRoot(ElementName = "LinearRing", Namespace = "")] + public class LinearRing + { - [XmlElement(ElementName="coordinates", Namespace="")] - public string Coordinates { get; set; } + [XmlElement(ElementName = "coordinates", Namespace = "")] + public string Coordinates { get; set; } } - [XmlRoot(ElementName="outerBoundaryIs", Namespace="")] - public class OuterBoundaryIs { + [XmlRoot(ElementName = "outerBoundaryIs", Namespace = "")] + public class OuterBoundaryIs + { - [XmlElement(ElementName="LinearRing", Namespace="")] - public LinearRing LinearRing { get; set; } + [XmlElement(ElementName = "LinearRing", Namespace = "")] + public LinearRing LinearRing { get; set; } } - [XmlRoot(ElementName="Polygon", Namespace="")] - public class Polygon { + [XmlRoot(ElementName = "Polygon", Namespace = "")] + public class Polygon + { - [XmlElement(ElementName="outerBoundaryIs", Namespace="")] - public OuterBoundaryIs OuterBoundaryIs { get; set; } + [XmlElement(ElementName = "outerBoundaryIs", Namespace = "")] + public OuterBoundaryIs OuterBoundaryIs { get; set; } } - [XmlRoot(ElementName="MultiGeometry", Namespace="")] - public class MultiGeometry { + [XmlRoot(ElementName = "MultiGeometry", Namespace = "")] + public class MultiGeometry + { - [XmlElement(ElementName="Polygon", Namespace="")] - public Polygon Polygon { get; set; } + [XmlElement(ElementName = "Polygon", Namespace = "")] + public Polygon Polygon { get; set; } } - [XmlRoot(ElementName="LatLonQuad", Namespace="http://www.google.com/kml/ext/2.2")] - public class LatLonQuad { + [XmlRoot(ElementName = "LatLonQuad", Namespace = "http://www.google.com/kml/ext/2.2")] + public class LatLonQuad + { - [XmlElement(ElementName="coordinates", Namespace="")] - public string Coordinates { get; set; } + [XmlElement(ElementName = "coordinates", Namespace = "")] + public string Coordinates { get; set; } } - [XmlRoot(ElementName="GroundOverlay", Namespace="")] - public class GroundOverlay { + [XmlRoot(ElementName = "GroundOverlay", Namespace = "")] + public class GroundOverlay + { - [XmlElement(ElementName="name", Namespace="")] - public string Name { get; set; } + [XmlElement(ElementName = "name", Namespace = "")] + public string Name { get; set; } - [XmlElement(ElementName="Icon", Namespace="")] - public Icon Icon { get; set; } + [XmlElement(ElementName = "Icon", Namespace = "")] + public Icon Icon { get; set; } - [XmlElement(ElementName="altitudeMode", Namespace="")] - public string AltitudeMode { get; set; } + [XmlElement(ElementName = "altitudeMode", Namespace = "")] + public string AltitudeMode { get; set; } - [XmlElement(ElementName="LatLonQuad", Namespace="http://www.google.com/kml/ext/2.2")] - public LatLonQuad LatLonQuad { get; set; } + [XmlElement(ElementName = "LatLonQuad", Namespace = "http://www.google.com/kml/ext/2.2")] + public LatLonQuad LatLonQuad { get; set; } } - [XmlRoot(ElementName="Folder", Namespace="")] - public class Folder { + [XmlRoot(ElementName = "Folder", Namespace = "")] + public class Folder + { - [XmlElement(ElementName="name", Namespace="")] - public string Name { get; set; } + [XmlElement(ElementName = "name", Namespace = "")] + public string Name { get; set; } - [XmlElement(ElementName="Placemark", Namespace="")] - public List Placemark { get; set; } + [XmlElement(ElementName = "Placemark", Namespace = "")] + public List Placemark { get; set; } - [XmlElement(ElementName="GroundOverlay", Namespace="")] - public GroundOverlay GroundOverlay { get; set; } + [XmlElement(ElementName = "GroundOverlay", Namespace = "")] + public GroundOverlay GroundOverlay { get; set; } } - [XmlRoot(ElementName="Document", Namespace="")] - public class Document { + [XmlRoot(ElementName = "Document", Namespace = "")] + public class Document + { - [XmlElement(ElementName="Style", Namespace="")] - public List