From 00a9b9599e3cc1182688d73e00006e049f2317ab Mon Sep 17 00:00:00 2001 From: Emmanuel Mathot Date: Wed, 10 Jun 2020 22:49:35 +0200 Subject: [PATCH 01/21] Initial commit --- README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..364adc05 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +DotNetStac From 09eed1b6b1982ac0d8e4ee682bc5340e15fb36ab Mon Sep 17 00:00:00 2001 From: Emmanuel Mathot Date: Wed, 10 Jun 2020 22:52:54 +0200 Subject: [PATCH 02/21] Stac Item Serialization + Tests --- .gitignore | 370 ++++++++++++++++++ .vscode/settings.json | 3 + .vscode/tasks.json | 25 ++ src/DotNetStac.Test/DotNetStac.Test.csproj | 20 + src/DotNetStac.Test/Item/ItemTests.cs | 95 +++++ src/DotNetStac.Test/JsonAssert.cs | 65 +++ ...ItemTests_CanDeserializeMinimalSample.json | 66 ++++ .../ItemTests_CanSerializeMinimalSample.json | 66 ++++ src/DotNetStac.Test/TestBase.cs | 41 ++ src/DotNetStac.Test/runsettings.xml | 12 + src/DotNetStac.sln | 48 +++ .../Converters/CollectionConverter.cs | 41 ++ .../Converters/StacExtensionConverter.cs | 57 +++ src/DotNetStac/DotNetStac.csproj | 10 + src/DotNetStac/Extensions/IStacExtension.cs | 8 + .../Extensions/IStacExtensionsFactory.cs | 9 + .../Extensions/Sat/SatStacExtension.cs | 14 + .../Extensions/StacExtensionsFactory.cs | 42 ++ src/DotNetStac/IStacObject.cs | 17 + src/DotNetStac/Item/StacItem.cs | 88 +++++ src/DotNetStac/StacAsset.cs | 147 +++++++ src/DotNetStac/StacLink.cs | 121 ++++++ src/DotNetStac/StacObject.cs | 63 +++ src/DotNetStac/StacVersionList.cs | 11 + src/json-schemas/item.json | 179 +++++++++ 25 files changed, 1618 insertions(+) create mode 100644 .gitignore create mode 100644 .vscode/settings.json create mode 100644 .vscode/tasks.json create mode 100644 src/DotNetStac.Test/DotNetStac.Test.csproj create mode 100644 src/DotNetStac.Test/Item/ItemTests.cs create mode 100644 src/DotNetStac.Test/JsonAssert.cs create mode 100644 src/DotNetStac.Test/Resources/Item/ItemTests_CanDeserializeMinimalSample.json create mode 100644 src/DotNetStac.Test/Resources/Item/ItemTests_CanSerializeMinimalSample.json create mode 100644 src/DotNetStac.Test/TestBase.cs create mode 100644 src/DotNetStac.Test/runsettings.xml create mode 100644 src/DotNetStac.sln create mode 100644 src/DotNetStac/Converters/CollectionConverter.cs create mode 100644 src/DotNetStac/Converters/StacExtensionConverter.cs create mode 100644 src/DotNetStac/DotNetStac.csproj create mode 100644 src/DotNetStac/Extensions/IStacExtension.cs create mode 100644 src/DotNetStac/Extensions/IStacExtensionsFactory.cs create mode 100644 src/DotNetStac/Extensions/Sat/SatStacExtension.cs create mode 100644 src/DotNetStac/Extensions/StacExtensionsFactory.cs create mode 100644 src/DotNetStac/IStacObject.cs create mode 100644 src/DotNetStac/Item/StacItem.cs create mode 100644 src/DotNetStac/StacAsset.cs create mode 100644 src/DotNetStac/StacLink.cs create mode 100644 src/DotNetStac/StacObject.cs create mode 100644 src/DotNetStac/StacVersionList.cs create mode 100644 src/json-schemas/item.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..91958d18 --- /dev/null +++ b/.gitignore @@ -0,0 +1,370 @@ +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..e0e1ac93 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "dotnet-test-explorer.testProjectPath": "**/*Test.@(csproj|vbproj|fsproj)" +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 00000000..6a6c3dc6 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,25 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "shell", + "args": [ + "build", + // Ask dotnet build to generate full paths for file names. + "/property:GenerateFullPaths=true", + // Do not generate summary otherwise it leads to duplicate errors in Problems panel + "/consoleloggerparameters:NoSummary", + "src/DotNetStac.sln" + ], + "group": "build", + "presentation": { + "reveal": "silent" + }, + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/src/DotNetStac.Test/DotNetStac.Test.csproj b/src/DotNetStac.Test/DotNetStac.Test.csproj new file mode 100644 index 00000000..95801da8 --- /dev/null +++ b/src/DotNetStac.Test/DotNetStac.Test.csproj @@ -0,0 +1,20 @@ + + + netcoreapp3.0 + false + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + \ No newline at end of file diff --git a/src/DotNetStac.Test/Item/ItemTests.cs b/src/DotNetStac.Test/Item/ItemTests.cs new file mode 100644 index 00000000..4016c6e0 --- /dev/null +++ b/src/DotNetStac.Test/Item/ItemTests.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GeoJSON.Net; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Stac.Item; +using Xunit; + +namespace Stac.Test.Item +{ + public class ItemTests : TestBase + { + [Fact] + public void CanDeserializeMinimalSample() + { + var json = GetExpectedJson("Item"); + + var item = JsonConvert.DeserializeObject(json); + + Assert.NotNull(item); + + Assert.NotNull(item.Properties); + + Assert.Equal("1.0.0-beta.1", item.StacVersion); + + Assert.Empty(item.StacExtensions); + + Assert.Equal(GeoJSONObjectType.Feature, item.Type); + + Assert.Equal("CS3-20160503_132130_04", item.Id); + + Assert.IsType(item.Geometry); + + Assert.Equal(new double[4] { -122.59750209, 37.48803556, -122.2880486, 37.613537207 }, item.BoundingBoxes); + + Assert.True(item.Properties.ContainsKey("collection")); + Assert.Equal("CS3", item.Properties["collection"]); + + Assert.Equal(DateTime.Parse("2016-05-03T13:21:30.040Z").ToUniversalTime(), item.Properties["datetime"]); + + Assert.Contains(item.Links, l => l.RelationshipType == "self" && l.Uri.ToString() == "http://cool-sat.com/catalog/CS3-20160503_132130_04/CS3-20160503_132130_04.json"); + + Assert.Contains(item.Links, l => l.RelationshipType == "collection" && l.Uri.ToString() == "http://cool-sat.com/catalog.json"); + + Assert.Equal("relative-path/to/analytic.tif", item.Assets["analytic"].Uri.ToString()); + Assert.Equal("4-Band Analytic", item.Assets["analytic"].Title); + + Assert.Equal("http://cool-sat.com/catalog/CS3-20160503_132130_04/thumbnail.png", item.Assets["thumbnail"].Uri.ToString()); + Assert.Equal("Thumbnail", item.Assets["thumbnail"].Title); + Assert.Contains("thumbnail", item.Assets["thumbnail"].SemanticRoles); + } + + [Fact] + public void CanSerializeMinimalSample() + { + var coordinates = new[] + { + new List + { + new Position(37.488035566,-122.308150179), + new Position(37.538869539,-122.597502109), + new Position(37.613537207,-122.576687533), + new Position(37.562818007,-122.288048600), + new Position(37.488035566,-122.308150179) + } + }; + + var geometry = new Polygon(new LineString[] { new LineString(coordinates[0]) }); + + var properties = new Dictionary(); + + properties.Add("datetime", DateTime.Parse("2016-05-03T13:21:30.040Z").ToUniversalTime()); + properties.Add("collection", "CS3"); + + StacItem item = new StacItem(geometry, properties, "CS3-20160503_132130_04"); + + item.Links.Add(StacLink.CreateSelfLink(new Uri("http://cool-sat.com/catalog/CS3-20160503_132130_04/CS3-20160503_132130_04.json"))); + item.Links.Add(StacLink.CreateCollectionLink(new Uri("http://cool-sat.com/catalog.json"))); + + item.Assets.Add("analytic", new StacAsset(new Uri("relative-path/to/analytic.tif", UriKind.Relative), null, "4-Band Analytic", null)); + item.Assets.Add("thumbnail", StacAsset.CreateThumbnailAsset(new Uri("http://cool-sat.com/catalog/CS3-20160503_132130_04/thumbnail.png"), null, "Thumbnail")); + + item.BoundingBoxes = new double[4] { -122.59750209, 37.48803556, -122.2880486, 37.613537207 }; + + var actualJson = JsonConvert.SerializeObject(item); + + Console.WriteLine(actualJson); + + var expectedJson = GetExpectedJson("Item"); + + JsonAssert.AreEqual(expectedJson, actualJson); + } + } +} diff --git a/src/DotNetStac.Test/JsonAssert.cs b/src/DotNetStac.Test/JsonAssert.cs new file mode 100644 index 00000000..5cd03ab9 --- /dev/null +++ b/src/DotNetStac.Test/JsonAssert.cs @@ -0,0 +1,65 @@ +using System.Linq; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Stac.Test +{ + /// + /// Assertions for json strings + /// + public static class JsonAssert + { + /// + /// Asserts that the json strings are equal. + /// + /// + /// Parses each json string into a , sorts the properties of each + /// and then serializes each back to a json string for comparison. + /// + /// The expect json. + /// The actual json. + public static void AreEqual(string expectJson, string actualJson) + { + Assert.Equal( + JObject.Parse(expectJson).SortProperties().ToString(), + JObject.Parse(actualJson).SortProperties().ToString()); + } + + /// + /// Asserts that contains + /// + /// The expected json. + /// The actual json. + public static void Contains(string expectedJson, string actualJson) + { + Assert.True(actualJson.Contains(expectedJson), string.Format("expected {0} to contain {1}", actualJson, expectedJson)); + } + + /// + /// Sorts the properties of a JObject + /// + /// The json object whhose properties to sort + /// A new instance of a with sorted properties + private static JObject SortProperties(this JObject jObject) + { + var result = new JObject(); + + foreach (var property in jObject.Properties().OrderBy(p => p.Name)) + { + var value = property.Value as JObject; + + if (value != null) + { + value = value.SortProperties(); + result.Add(property.Name, value); + } + else + { + result.Add(property.Name, property.Value); + } + } + + return result; + } + } +} \ No newline at end of file diff --git a/src/DotNetStac.Test/Resources/Item/ItemTests_CanDeserializeMinimalSample.json b/src/DotNetStac.Test/Resources/Item/ItemTests_CanDeserializeMinimalSample.json new file mode 100644 index 00000000..85308997 --- /dev/null +++ b/src/DotNetStac.Test/Resources/Item/ItemTests_CanDeserializeMinimalSample.json @@ -0,0 +1,66 @@ +{ + "stac_version": "1.0.0-beta.1", + "stac_extensions": [], + "type": "Feature", + "id": "CS3-20160503_132130_04", + "bbox": [ + -122.59750209, + 37.48803556, + -122.2880486, + 37.613537207 + ], + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [ + -122.308150179, + 37.488035566 + ], + [ + -122.597502109, + 37.538869539 + ], + [ + -122.576687533, + 37.613537207 + ], + [ + -122.288048600, + 37.562818007 + ], + [ + -122.308150179, + 37.488035566 + ] + ] + ] + }, + "properties": { + "datetime": "2016-05-03T13:21:30.040Z", + "collection": "CS3" + }, + "links": [ + { + "rel": "self", + "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/CS3-20160503_132130_04.json" + }, + { + "rel": "collection", + "href": "http://cool-sat.com/catalog.json" + } + ], + "assets": { + "analytic": { + "href": "relative-path/to/analytic.tif", + "title": "4-Band Analytic" + }, + "thumbnail": { + "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/thumbnail.png", + "title": "Thumbnail", + "roles": [ + "thumbnail" + ] + } + } +} \ No newline at end of file diff --git a/src/DotNetStac.Test/Resources/Item/ItemTests_CanSerializeMinimalSample.json b/src/DotNetStac.Test/Resources/Item/ItemTests_CanSerializeMinimalSample.json new file mode 100644 index 00000000..85308997 --- /dev/null +++ b/src/DotNetStac.Test/Resources/Item/ItemTests_CanSerializeMinimalSample.json @@ -0,0 +1,66 @@ +{ + "stac_version": "1.0.0-beta.1", + "stac_extensions": [], + "type": "Feature", + "id": "CS3-20160503_132130_04", + "bbox": [ + -122.59750209, + 37.48803556, + -122.2880486, + 37.613537207 + ], + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [ + -122.308150179, + 37.488035566 + ], + [ + -122.597502109, + 37.538869539 + ], + [ + -122.576687533, + 37.613537207 + ], + [ + -122.288048600, + 37.562818007 + ], + [ + -122.308150179, + 37.488035566 + ] + ] + ] + }, + "properties": { + "datetime": "2016-05-03T13:21:30.040Z", + "collection": "CS3" + }, + "links": [ + { + "rel": "self", + "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/CS3-20160503_132130_04.json" + }, + { + "rel": "collection", + "href": "http://cool-sat.com/catalog.json" + } + ], + "assets": { + "analytic": { + "href": "relative-path/to/analytic.tif", + "title": "4-Band Analytic" + }, + "thumbnail": { + "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/thumbnail.png", + "title": "Thumbnail", + "roles": [ + "thumbnail" + ] + } + } +} \ No newline at end of file diff --git a/src/DotNetStac.Test/TestBase.cs b/src/DotNetStac.Test/TestBase.cs new file mode 100644 index 00000000..c4f80647 --- /dev/null +++ b/src/DotNetStac.Test/TestBase.cs @@ -0,0 +1,41 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Stac.Test +{ + public abstract class TestBase + { + private static readonly Assembly ThisAssembly = typeof(TestBase) +#if NETCOREAPP1_1 + .GetTypeInfo() +#endif + .Assembly; + private static readonly string AssemblyName = ThisAssembly.GetName().Name; + + public static string AssemblyDirectory + { + get + { + string codeBase = ThisAssembly.CodeBase; + UriBuilder uri = new UriBuilder(codeBase); + string path = Uri.UnescapeDataString(uri.Path); + return Path.GetDirectoryName(path); + } + } + + protected string GetExpectedJson(string folder, [CallerMemberName] string name = null) + { + var type = GetType().Name; + var path = Path.Combine(AssemblyDirectory, @"../../..", "Resources", folder, type + "_" + name + ".json"); + + if (!File.Exists(path)) + { + throw new FileNotFoundException("file not found at " + path); + } + + return File.ReadAllText(path); + } + } +} \ No newline at end of file diff --git a/src/DotNetStac.Test/runsettings.xml b/src/DotNetStac.Test/runsettings.xml new file mode 100644 index 00000000..37478809 --- /dev/null +++ b/src/DotNetStac.Test/runsettings.xml @@ -0,0 +1,12 @@ + + + + + + + lcov,cobertura + + + + + \ No newline at end of file diff --git a/src/DotNetStac.sln b/src/DotNetStac.sln new file mode 100644 index 00000000..8977a984 --- /dev/null +++ b/src/DotNetStac.sln @@ -0,0 +1,48 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetStac", "DotNetStac\DotNetStac.csproj", "{19E9F528-4825-45F6-B515-FDD88DAB95F5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetStac.Test", "DotNetStac.Test\DotNetStac.Test.csproj", "{19D1373B-24F2-4776-85BA-2EF7B7D81FFD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Debug|x64.ActiveCfg = Debug|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Debug|x64.Build.0 = Debug|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Debug|x86.ActiveCfg = Debug|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Debug|x86.Build.0 = Debug|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Release|Any CPU.Build.0 = Release|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Release|x64.ActiveCfg = Release|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Release|x64.Build.0 = Release|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Release|x86.ActiveCfg = Release|Any CPU + {19E9F528-4825-45F6-B515-FDD88DAB95F5}.Release|x86.Build.0 = Release|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Debug|x64.ActiveCfg = Debug|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Debug|x64.Build.0 = Debug|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Debug|x86.ActiveCfg = Debug|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Debug|x86.Build.0 = Debug|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Release|Any CPU.Build.0 = Release|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Release|x64.ActiveCfg = Release|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Release|x64.Build.0 = Release|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Release|x86.ActiveCfg = Release|Any CPU + {19D1373B-24F2-4776-85BA-2EF7B7D81FFD}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/src/DotNetStac/Converters/CollectionConverter.cs b/src/DotNetStac/Converters/CollectionConverter.cs new file mode 100644 index 00000000..9e8862f4 --- /dev/null +++ b/src/DotNetStac/Converters/CollectionConverter.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace DotNetStac.Converters +{ + public class CollectionConverter : JsonConverter + { + public override bool CanConvert(Type objectType) + { + return (objectType == typeof(Collection)); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + JToken token = JToken.Load(reader); + if (token.Type == JTokenType.Array) + { + return new Collection(token.ToObject>()); + } + return new Collection(); + } + + public override bool CanRead => true; + + public override bool CanWrite => true; + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + Collection collection = (Collection)value; + writer.WriteStartArray(); + foreach (var item in collection) + { + serializer.Serialize(writer, item); + } + writer.WriteEndArray(); + } + } +} diff --git a/src/DotNetStac/Converters/StacExtensionConverter.cs b/src/DotNetStac/Converters/StacExtensionConverter.cs new file mode 100644 index 00000000..2af00103 --- /dev/null +++ b/src/DotNetStac/Converters/StacExtensionConverter.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac.Extensions; + +namespace Stac.Converters +{ + internal class StacExtensionConverter : JsonConverter + { + private readonly IStacExtensionsFactory stacExtensionFactory; + + public StacExtensionConverter() : this(StacExtensionsFactory.Default) { } + + public StacExtensionConverter(IStacExtensionsFactory stacExtensionFactory) + { + this.stacExtensionFactory = stacExtensionFactory; + } + + public override bool CanConvert(Type objectType) + { + return objectType.IsAssignableFrom(typeof(IStacExtension)); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + Collection stacExtensions = new Collection(); + if (reader.TokenType != JsonToken.Null) + { + if (reader.TokenType == JsonToken.StartArray) + { + JToken token = JToken.Load(reader); + List extensionPrefixes = token.ToObject>(); + foreach (var extensionPrefix in extensionPrefixes) + { + var stacExtension = stacExtensionFactory.CreateStacExtension(extensionPrefix); + if (stacExtension != null) + stacExtensions.Add(stacExtension); + } + } + } + return stacExtensions; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + Collection stacExtensions = (Collection)value; + writer.WriteStartArray(); + foreach (var stacExtension in stacExtensions) + { + writer.WriteValue(stacExtension.Id); + } + writer.WriteEndArray(); + } + } +} \ No newline at end of file diff --git a/src/DotNetStac/DotNetStac.csproj b/src/DotNetStac/DotNetStac.csproj new file mode 100644 index 00000000..c877c17b --- /dev/null +++ b/src/DotNetStac/DotNetStac.csproj @@ -0,0 +1,10 @@ + + + netstandard2.0 + + + + + + + \ No newline at end of file diff --git a/src/DotNetStac/Extensions/IStacExtension.cs b/src/DotNetStac/Extensions/IStacExtension.cs new file mode 100644 index 00000000..00178fbd --- /dev/null +++ b/src/DotNetStac/Extensions/IStacExtension.cs @@ -0,0 +1,8 @@ +namespace Stac.Extensions +{ + public interface IStacExtension + { + string Id { get; } + + } +} \ No newline at end of file diff --git a/src/DotNetStac/Extensions/IStacExtensionsFactory.cs b/src/DotNetStac/Extensions/IStacExtensionsFactory.cs new file mode 100644 index 00000000..658b4b0a --- /dev/null +++ b/src/DotNetStac/Extensions/IStacExtensionsFactory.cs @@ -0,0 +1,9 @@ +namespace Stac.Extensions +{ + public interface IStacExtensionsFactory + { + + IStacExtension CreateStacExtension(string prefix); + + } +} \ No newline at end of file diff --git a/src/DotNetStac/Extensions/Sat/SatStacExtension.cs b/src/DotNetStac/Extensions/Sat/SatStacExtension.cs new file mode 100644 index 00000000..c2ed5ceb --- /dev/null +++ b/src/DotNetStac/Extensions/Sat/SatStacExtension.cs @@ -0,0 +1,14 @@ +using System; +using Stac.Extensions; + +namespace DotNetStac.Extensions.Sat +{ + public class SatStacExtension : IStacExtension + { + public SatStacExtension() + { + } + + public string Id => "sat"; + } +} diff --git a/src/DotNetStac/Extensions/StacExtensionsFactory.cs b/src/DotNetStac/Extensions/StacExtensionsFactory.cs new file mode 100644 index 00000000..665a7437 --- /dev/null +++ b/src/DotNetStac/Extensions/StacExtensionsFactory.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Stac.Extensions +{ + public class StacExtensionsFactory : IStacExtensionsFactory + { + + Dictionary stacExtensionsDictionary = new Dictionary(); + + public StacExtensionsFactory(IStacExtension[] stacExtensions) + { + this.stacExtensionsDictionary = stacExtensions.ToDictionary(se => se.Id, se => se); + } + + internal StacExtensionsFactory() + { + this.stacExtensionsDictionary = new IStacExtension[] { + new DotNetStac.Extensions.Sat.SatStacExtension() + }.ToDictionary(se => se.Id, se => se); + } + + public static StacExtensionsFactory Default + { + get + { + return StacExtensionsFactory.CreateDefaultFactory(); + } + } + + public static StacExtensionsFactory CreateDefaultFactory() + { + return new StacExtensionsFactory(); + } + + public IStacExtension CreateStacExtension(string prefix) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/DotNetStac/IStacObject.cs b/src/DotNetStac/IStacObject.cs new file mode 100644 index 00000000..8bcc9172 --- /dev/null +++ b/src/DotNetStac/IStacObject.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.ObjectModel; +using Stac.Extensions; + +namespace Stac +{ + public interface IStacObject + { + string Id { get; } + + string StacVersion { get; } + + Collection StacExtensions { get; } + + Collection Links { get; } + } +} \ No newline at end of file diff --git a/src/DotNetStac/Item/StacItem.cs b/src/DotNetStac/Item/StacItem.cs new file mode 100644 index 00000000..5596b098 --- /dev/null +++ b/src/DotNetStac/Item/StacItem.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using DotNetStac; +using DotNetStac.Converters; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Stac.Converters; +using Stac.Extensions; + +namespace Stac.Item +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + public class StacItem : GeoJSON.Net.Feature.Feature, IStacObject + { + private Collection links; + + private Dictionary assets; + + private string stacVersion = StacVersionList.Current; + + private Collection extensions; + + [JsonConstructor] + public StacItem(IGeometryObject geometry, IDictionary properties = null, string id = null) : base(geometry, properties, id) + { } + + public StacItem(IGeometryObject geometry, object properties, string id = null) : base(geometry, properties, id) + { } + + [JsonProperty("stac_extensions")] + [JsonConverter(typeof(StacExtensionConverter))] + public Collection StacExtensions + { + get + { + if (extensions == null) + extensions = new Collection(); + return extensions; + } + set + { + extensions = value; + } + } + + [JsonProperty("stac_version")] + public string StacVersion + { + get + { + return stacVersion; + } + + set + { + stacVersion = value; + } + } + + [JsonConverter(typeof(CollectionConverter))] + [JsonProperty("links")] + public Collection Links + { + get + { + if (links == null) + links = new Collection(); + return links; + } + set + { + links = value; + } + } + + [JsonProperty("assets")] + public Dictionary Assets + { + get + { + if (assets == null) + assets = new Dictionary(); + return assets; + } + } + } +} diff --git a/src/DotNetStac/StacAsset.cs b/src/DotNetStac/StacAsset.cs new file mode 100644 index 00000000..655c52f9 --- /dev/null +++ b/src/DotNetStac/StacAsset.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using DotNetStac.Converters; +using Newtonsoft.Json; + +namespace Stac +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + public class StacAsset + { + + #region Static members + + public static StacAsset CreateThumbnailAsset(Uri uri, string mediaType, string title = null) + { + return new StacAsset(uri, new string[] { "thumbnail" }, title, mediaType); + } + + public static StacAsset CreateOverviewAsset(Uri uri, string mediaType, string title = null) + { + return new StacAsset(uri, new string[] { "overview" }, title, mediaType); + } + + public static StacAsset CreateDataAsset(Uri uri, string mediaType, string title = null) + { + return new StacAsset(uri, new string[] { "data" }, title, mediaType); + } + + public static StacAsset CreateMetadataAsset(Uri uri, string mediaType, string title = null) + { + return new StacAsset(uri, new string[] { "metadata" }, title, mediaType); + } + + #endregion + + Uri base_uri, href; + string title, type, description; + + Collection semanticRoles; + + public StacAsset() + { + } + + public StacAsset(Uri uri) + { + Uri = uri; + } + + public StacAsset(Uri uri, IEnumerable semanticRoles, string title, string mediaType) + { + Uri = uri; + this.semanticRoles = semanticRoles == null ? new Collection() : new Collection(semanticRoles.ToList()); + Title = title; + MediaType = mediaType; + } + + public StacAsset(StacAsset source) + { + if (source == null) + throw new ArgumentNullException("source"); + base_uri = source.base_uri; + href = source.href; + semanticRoles = source.semanticRoles; + title = source.title; + type = source.type; + description = source.description; + } + + [JsonIgnore] + public Uri BaseUri + { + get { return base_uri; } + set + { + if (value != null && !value.IsAbsoluteUri) + throw new ArgumentException("Base URI must not be relative"); + base_uri = value; + } + } + + [JsonProperty("type")] + public string MediaType + { + get { return type; } + set { type = value; } + } + + [JsonProperty("roles")] + public List Roles + { + get + { + if (semanticRoles == null || semanticRoles.Count == 0) + return null; + return semanticRoles.ToList(); + } + set + { + if (value == null) + semanticRoles = null; + else + semanticRoles = new Collection(value); + } + } + + [JsonIgnore] + public Collection SemanticRoles + { + get + { + if (semanticRoles == null) + semanticRoles = new Collection(); + return semanticRoles; + } + } + + [JsonProperty("title")] + public string Title + { + get { return title; } + set { title = value; } + } + + [JsonProperty("href")] + public Uri Uri + { + get { return href; } + set { href = value; } + } + + [JsonProperty("description")] + public string Description + { + get { return description; } + set { description = value; } + } + + public virtual StacAsset Clone() + { + return new StacAsset(this); + } + } +} \ No newline at end of file diff --git a/src/DotNetStac/StacLink.cs b/src/DotNetStac/StacLink.cs new file mode 100644 index 00000000..5f72ec27 --- /dev/null +++ b/src/DotNetStac/StacLink.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace Stac +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + public class StacLink + { + #region Static members + + public static StacLink CreateSelfLink(Uri uri, string mediaType = null) + { + return new StacLink(uri, "self", null, mediaType); + } + + public static StacLink CreateRootLink(Uri uri, string mediaType = null) + { + return new StacLink(uri, "root", null, mediaType); + } + + public static StacLink CreateParentLink(Uri uri, string mediaType = null) + { + return new StacLink(uri, "parent", null, mediaType); + } + + public static StacLink CreateCollectionLink(Uri uri, string mediaType = null) + { + return new StacLink(uri, "collection", null, mediaType); + } + + public static StacLink CreateDerivedFromLink(Uri uri, string mediaType = null) + { + return new StacLink(uri, "derived_from", null, mediaType); + } + + public static StacLink CreateAlternateLink(Uri uri, string mediaType = null) + { + return new StacLink(uri, "alternate", null, mediaType); + } + + #endregion + + Uri base_uri, href; + string rel, title, type; + + public StacLink() + { + } + + public StacLink(Uri uri) + { + Uri = uri; + } + + public StacLink(Uri uri, string relationshipType, string title, string mediaType) + { + Uri = uri; + RelationshipType = relationshipType; + Title = title; + MediaType = mediaType; + } + + public StacLink(StacLink source) + { + if (source == null) + throw new ArgumentNullException("source"); + base_uri = source.base_uri; + href = source.href; + rel = source.rel; + title = source.title; + type = source.type; + } + + [JsonIgnore] + public Uri BaseUri + { + get { return base_uri; } + set + { + if (value != null && !value.IsAbsoluteUri) + throw new ArgumentException("Base URI must not be relative"); + base_uri = value; + } + } + + [JsonProperty("type")] + public string MediaType + { + get { return type; } + set { type = value; } + } + + [JsonProperty("rel")] + public string RelationshipType + { + get { return rel; } + set { rel = value; } + } + + [JsonProperty("title")] + public string Title + { + get { return title; } + set { title = value; } + } + + [JsonProperty("href")] + public Uri Uri + { + get { return href; } + set { href = value; } + } + + public virtual StacLink Clone() + { + return new StacLink(this); + } + + } +} diff --git a/src/DotNetStac/StacObject.cs b/src/DotNetStac/StacObject.cs new file mode 100644 index 00000000..5ea138f4 --- /dev/null +++ b/src/DotNetStac/StacObject.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using Newtonsoft.Json; +using Stac.Extensions; + +namespace Stac +{ + /// + /// A STACObject is the base class for any element of STAC that + /// has an Id, stac version and extensions, links e.g. (Catalogs, Collections, or Items). + /// + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + + public abstract class StacObject : IStacObject + { + private readonly string id; + private string stacVersion; + private Collection links; + + public StacObject(string id) + { + this.id = id; + } + + public StacObject(string id, IEnumerable links) : this(id) + { + Links = new Collection(links.ToList()); + } + + public string Id => id; + + public string StacVersion + { + get + { + return stacVersion; + } + + set + { + stacVersion = value; + } + } + + public abstract Collection StacExtensions { get; } + + public Collection Links + { + get + { + if (links == null) + links = new Collection(); + return links; + } + set + { + links = value; + } + } + } +} diff --git a/src/DotNetStac/StacVersionList.cs b/src/DotNetStac/StacVersionList.cs new file mode 100644 index 00000000..1c4cd70b --- /dev/null +++ b/src/DotNetStac/StacVersionList.cs @@ -0,0 +1,11 @@ +using System; + +namespace DotNetStac +{ + public static class StacVersionList + { + public static string Current => V100beta1; + + public static string V100beta1 => "1.0.0-beta.1"; + } +} diff --git a/src/json-schemas/item.json b/src/json-schemas/item.json new file mode 100644 index 00000000..c96ab234 --- /dev/null +++ b/src/json-schemas/item.json @@ -0,0 +1,179 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "item.json#", + "title": "STAC Item", + "type": "object", + "description": "This object represents the metadata for an item in a SpatioTemporal Asset Catalog.", + "additionalProperties": true, + "allOf": [ + { + "$ref": "#/definitions/core" + } + ], + "definitions": { + "common_metadata": { + "allOf": [ + { + "$ref": "basics.json" + }, + { + "$ref": "datetime.json" + }, + { + "$ref": "instrument.json" + }, + { + "$ref": "licensing.json" + }, + { + "$ref": "provider.json" + } + ] + }, + "core": { + "allOf": [ + { + "$ref": "https://geojson.org/schema/Feature.json" + }, + { + "type": "object", + "required": [ + "stac_version", + "id", + "links", + "assets", + "bbox", + "properties" + ], + "properties": { + "stac_version": { + "title": "STAC version", + "type": "string", + "const": "1.0.0-beta.1" + }, + "stac_extensions": { + "title": "STAC extensions", + "type": "array", + "uniqueItems": true, + "items": { + "anyOf": [ + { + "title": "Reference to a JSON Schema", + "type": "string", + "format": "uri" + }, + { + "title": "Reference to a core extension", + "type": "string" + } + ] + } + }, + "id": { + "title": "Provider ID", + "description": "Provider item ID", + "type": "string" + }, + "bbox": { + "type": "array", + "minItems": 4, + "items": { + "type": "number" + } + }, + "links": { + "title": "Item links", + "description": "Links to item relations", + "type": "array", + "items": { + "$ref": "#/definitions/link" + } + }, + "assets": { + "$ref": "#/definitions/assets" + }, + "properties": { + "$ref": "#/definitions/common_metadata" + }, + "collection": { + "title": "Collection ID", + "description": "The ID of the STAC Collection this Item references to.", + "type": "string" + } + } + } + ] + }, + "link": { + "type": "object", + "required": [ + "rel", + "href" + ], + "properties": { + "href": { + "title": "Link reference", + "type": "string" + }, + "rel": { + "title": "Link relation type", + "type": "string" + }, + "type": { + "title": "Link type", + "type": "string" + }, + "title": { + "title": "Link title", + "type": "string" + }, + "created": { + "$ref": "datetime.json#/definitions/created" + }, + "updated": { + "$ref": "datetime.json#/definitions/updated" + } + } + }, + "assets": { + "title": "Asset links", + "description": "Links to assets", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/asset" + } + }, + "asset": { + "type": "object", + "required": [ + "href" + ], + "properties": { + "href": { + "title": "Asset reference", + "type": "string" + }, + "title": { + "title": "Asset title", + "type": "string" + }, + "description": { + "title": "Asset description", + "type": "string" + }, + "type": { + "title": "Asset type", + "type": "string" + }, + "roles": { + "title": "Asset roles", + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + \ No newline at end of file From 860c3b9431be73d8656e0c4b720b8d5bbe4fef44 Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 16 Jun 2020 23:36:48 +0200 Subject: [PATCH 03/21] Collection Summaries --- .vscode/launch.json | 27 ++++ .../Collection/CollectionTests.cs | 45 ++++++ src/DotNetStac.Test/Item/ItemTests.cs | 10 ++ ...onTests_CanDeserializeSentinel2Sample.json | 148 ++++++++++++++++++ .../Item/ItemTests_CanManageDates.json | 101 ++++++++++++ src/DotNetStac/Collection/IStacSummaryItem.cs | 13 ++ src/DotNetStac/Collection/StacCollection.cs | 117 ++++++++++++++ src/DotNetStac/Collection/StacStatsObject.cs | 6 + src/DotNetStac/Collection/StacSummaryItem.cs | 13 ++ .../Collection/StacSummaryStatsObject.cs | 33 ++++ .../Collection/StacSummaryValueSet.cs | 29 ++++ src/DotNetStac/Collection/SummaryItemType.cs | 9 ++ .../Converters/StacExtensionConverter.cs | 2 +- .../Converters/StacSummariesConverter.cs | 93 +++++++++++ src/DotNetStac/DotNetStac.csproj | 2 + .../Extensions/GenericStacExtension.cs | 26 +++ src/DotNetStac/Extensions/IStacExtension.cs | 1 + .../Extensions/IStacExtensionsFactory.cs | 2 +- .../Extensions/Sat/SatStacExtension.cs | 6 + .../Extensions/StacExtensionsFactory.cs | 8 +- src/DotNetStac/Item/StacItem.cs | 58 +++++++ src/DotNetStac/StacExtent.cs | 6 + src/DotNetStac/StacObject.cs | 6 +- 23 files changed, 752 insertions(+), 9 deletions(-) create mode 100644 .vscode/launch.json create mode 100644 src/DotNetStac.Test/Collection/CollectionTests.cs create mode 100644 src/DotNetStac.Test/Resources/Collection/CollectionTests_CanDeserializeSentinel2Sample.json create mode 100644 src/DotNetStac.Test/Resources/Item/ItemTests_CanManageDates.json create mode 100644 src/DotNetStac/Collection/IStacSummaryItem.cs create mode 100644 src/DotNetStac/Collection/StacCollection.cs create mode 100644 src/DotNetStac/Collection/StacStatsObject.cs create mode 100644 src/DotNetStac/Collection/StacSummaryItem.cs create mode 100644 src/DotNetStac/Collection/StacSummaryStatsObject.cs create mode 100644 src/DotNetStac/Collection/StacSummaryValueSet.cs create mode 100644 src/DotNetStac/Collection/SummaryItemType.cs create mode 100644 src/DotNetStac/Converters/StacSummariesConverter.cs create mode 100644 src/DotNetStac/Extensions/GenericStacExtension.cs create mode 100644 src/DotNetStac/StacExtent.cs diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..a7eaeea2 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,27 @@ +{ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/src/DotNetStac.Test/bin/Debug/netcoreapp3.0/DotNetStac.Test.dll", + "args": [], + "cwd": "${workspaceFolder}/src/DotNetStac.Test", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} \ No newline at end of file diff --git a/src/DotNetStac.Test/Collection/CollectionTests.cs b/src/DotNetStac.Test/Collection/CollectionTests.cs new file mode 100644 index 00000000..6d6d8f2f --- /dev/null +++ b/src/DotNetStac.Test/Collection/CollectionTests.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GeoJSON.Net; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Stac.Collection; +using Xunit; + +namespace Stac.Test.Item +{ + public class CollectionTests : TestBase + { + [Fact] + public void CanDeserializeSentinel2Sample() + { + var json = GetExpectedJson("Collection"); + + var item = JsonConvert.DeserializeObject(json); + + Assert.NotNull(item); + + Assert.NotNull(item.Summaries); + + Assert.Equal("1.0.0-beta.1", item.StacVersion); + + Assert.Empty(item.StacExtensions); + + Assert.NotEmpty(item.Summaries); + + Assert.True(item.Summaries.ContainsKey("datetime")); + Assert.True(item.Summaries.ContainsKey("platform")); + Assert.True(item.Summaries.ContainsKey("constellation")); + Assert.True(item.Summaries.ContainsKey("view:off_nadir")); + Assert.True(item.Summaries.ContainsKey("eo:bands")); + + Assert.IsType>(item.Summaries["datetime"]); + + Assert.Equal(DateTime.Parse("2015-06-23T00:00:00Z").ToUniversalTime(), (item.Summaries["datetime"] as StacSummaryStatsObject).Min); + + + } + + } +} \ No newline at end of file diff --git a/src/DotNetStac.Test/Item/ItemTests.cs b/src/DotNetStac.Test/Item/ItemTests.cs index 4016c6e0..bdac0045 100644 --- a/src/DotNetStac.Test/Item/ItemTests.cs +++ b/src/DotNetStac.Test/Item/ItemTests.cs @@ -91,5 +91,15 @@ public void CanSerializeMinimalSample() JsonAssert.AreEqual(expectedJson, actualJson); } + + [Fact] + public void CanManageDates() + { + var json = GetExpectedJson("Item"); + + var item = JsonConvert.DeserializeObject(json); + + Assert.Equal(item.DateTime, new Itenso.TimePeriod.TimeInterval(DateTime.Parse("2016-05-03T13:22:30Z").ToUniversalTime())); + } } } diff --git a/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanDeserializeSentinel2Sample.json b/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanDeserializeSentinel2Sample.json new file mode 100644 index 00000000..368b2643 --- /dev/null +++ b/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanDeserializeSentinel2Sample.json @@ -0,0 +1,148 @@ +{ + "stac_version": "1.0.0-beta.1", + "stac_extensions": [], + "id": "COPERNICUS/S2", + "title": "Sentinel-2 MSI: MultiSpectral Instrument, Level-1C", + "description": "Sentinel-2 is a wide-swath, high-resolution, multi-spectral\nimaging mission supporting Copernicus Land Monitoring studies,\nincluding the monitoring of vegetation, soil and water cover,\nas well as observation of inland waterways and coastal areas.\n\nThe Sentinel-2 data contain 13 UINT16 spectral bands representing\nTOA reflectance scaled by 10000. See the [Sentinel-2 User Handbook](https://sentinel.esa.int/documents/247904/685211/Sentinel-2_User_Handbook)\nfor details. In addition, three QA bands are present where one\n(QA60) is a bitmask band with cloud mask information. For more\ndetails, [see the full explanation of how cloud masks are computed.](https://sentinel.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-1c/cloud-masks)\n\nEach Sentinel-2 product (zip archive) may contain multiple\ngranules. Each granule becomes a separate Earth Engine asset.\nEE asset ids for Sentinel-2 assets have the following format:\nCOPERNICUS/S2/20151128T002653_20151128T102149_T56MNN. Here the\nfirst numeric part represents the sensing date and time, the\nsecond numeric part represents the product generation date and\ntime, and the final 6-character string is a unique granule identifier\nindicating its UTM grid reference (see [MGRS](https://en.wikipedia.org/wiki/Military_Grid_Reference_System)).\n\nFor more details on Sentinel-2 radiometric resoltuon, [see this page](https://earth.esa.int/web/sentinel/user-guides/sentinel-2-msi/resolutions/radiometric).\n", + "license": "proprietary", + "keywords": [ + "copernicus", + "esa", + "eu", + "msi", + "radiance", + "sentinel" + ], + "providers": [ + { + "name": "European Union/ESA/Copernicus", + "roles": [ + "producer", + "licensor" + ], + "url": "https://sentinel.esa.int/web/sentinel/user-guides/sentinel-2-msi" + } + ], + "extent": { + "spatial": { + "bbox": [ + [ + -180, + -56, + 180, + 83 + ] + ] + }, + "temporal": { + "interval": [ + [ + "2015-06-23T00:00:00Z", + null + ] + ] + } + }, + + "summaries": { + "datetime": { + "min": "2015-06-23T00:00:00Z", + "max": "2019-07-10T13:44:56Z" + }, + "platform": ["sentinel-2a","sentinel-2b"], + "constellation": ["sentinel-2"], + "instruments": ["msi"], + "view:off_nadir": { + "min": 0.0, + "max": 100 + }, + "view:sun_elevation": { + "min": 6.78, + "max": 89.9 + }, + "sci:citation": ["Copernicus Sentinel data [Year]"], + "gsd": [10,30,60], + "proj:epsg": [32601,32602,32603,32604,32605,32606,32607,32608,32609,32610,32611,32612,32613,32614,32615,32616,32617,32618,32619,32620,32621,32622,32623,32624,32625,32626,32627,32628,32629,32630,32631,32632,32633,32634,32635,32636,32637,32638,32639,32640,32641,32642,32643,32644,32645,32646,32647,32648,32649,32650,32651,32652,32653,32654,32655,32656,32657,32658,32659,32660], + "eo:bands": [ + { + "name": "B1", + "common_name": "coastal", + "center_wavelength": 4.439 + }, + { + "name": "B2", + "common_name": "blue", + "center_wavelength": 4.966 + }, + { + "name": "B3", + "common_name": "green", + "center_wavelength": 5.6 + }, + { + "name": "B4", + "common_name": "red", + "center_wavelength": 6.645 + }, + { + "name": "B5", + "center_wavelength": 7.039 + }, + { + "name": "B6", + "center_wavelength": 7.402 + }, + { + "name": "B7", + "center_wavelength": 7.825 + }, + { + "name": "B8", + "common_name": "nir", + "center_wavelength": 8.351 + }, + { + "name": "B8A", + "center_wavelength": 8.648 + }, + { + "name": "B9", + "center_wavelength": 9.45 + }, + { + "name": "B10", + "center_wavelength": 1.3735 + }, + { + "name": "B11", + "common_name": "swir16", + "center_wavelength": 1.6137 + }, + { + "name": "B12", + "common_name": "swir22", + "center_wavelength": 2.2024 + } + ] + }, + "links": [ + { + "rel": "self", + "href": "https://storage.cloud.google.com/earthengine-test/catalog/COPERNICUS_S2.json" + }, + { + "rel": "parent", + "href": "https://storage.cloud.google.com/earthengine-test/catalog/catalog.json" + }, + { + "rel": "root", + "href": "https://storage.cloud.google.com/earthengine-test/catalog/catalog.json" + }, + { + "rel": "license", + "href": "https://scihub.copernicus.eu/twiki/pub/SciHubWebPortal/TermsConditions/Sentinel_Data_Terms_and_Conditions.pdf", + "title": "Legal notice on the use of Copernicus Sentinel Data and Service Information" + } + ] + } + \ No newline at end of file diff --git a/src/DotNetStac.Test/Resources/Item/ItemTests_CanManageDates.json b/src/DotNetStac.Test/Resources/Item/ItemTests_CanManageDates.json new file mode 100644 index 00000000..024a08f7 --- /dev/null +++ b/src/DotNetStac.Test/Resources/Item/ItemTests_CanManageDates.json @@ -0,0 +1,101 @@ +{ + "stac_version": "1.0.0-beta.1", + "stac_extensions": [ + "eo", + "view", + "https://example.com/cs-extension/1.0/schema.json" + ], + "type": "Feature", + "id" : "CS3-20160503_132131_05", + "bbox": [-122.59750209, 37.48803556, -122.2880486, 37.613537207], + "geometry": { + "type": "Polygon", + "coordinates": [ + [ + [-122.308150179, 37.488035566], + [-122.597502109, 37.538869539], + [-122.576687533, 37.613537207], + [-122.288048600, 37.562818007], + [-122.308150179, 37.488035566] + ] + ] + }, + "properties": { + "datetime": "2016-05-03T13:22:30Z", + "title": "A CS3 item", + "license": "PDDL-1.0", + "providers": [ + { + "name": "CoolSat", + "roles": [ + "producer", + "licensor" + ], + "url": "https://cool-sat.com/" + } + ], + "created": "2016-05-04T00:00:01Z", + "updated": "2017-01-01T00:30:55Z", + "view:sun_azimuth": 168.7, + "eo:cloud_cover": 0.12, + "view:off_nadir": 1.4, + "platform": "coolsat2", + "instruments": ["cool_sensor_v1"], + "eo:bands": [ + { + "name": "band1" + }, + { + "name": "band1" + }, + { + "name": "band2" + }, + { + "name": "band3" + } + ], + "view:sun_elevation": 33.4, + "gsd": 0.512, + "cs:type": "scene", + "cs:anomalous_pixels": 0.14, + "cs:earth_sun_distance": 1.0141560, + "cs:sat_id": "CS3", + "cs:product_level": "LV1B" + }, + "collection": "CS3", + "links": [ + {"rel": "self", "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/CS3-20160503_132130_04.json"}, + {"rel": "root", "href": "http://cool-sat.com/catalog/catalog.json"}, + {"rel": "parent", "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/catalog.json"}, + {"rel": "collection", "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/catalog.json"}, + {"rel": "alternate", "type": "text/html", "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/CS3-20160503_132130_04.html"} + ], + "assets": { + "analytic": { + "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/analytic.tif", + "title": "4-Band Analytic" + }, + "thumbnail": { + "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/thumbnail.png", + "title": "Thumbnail", + "type": "image/png", + "roles": [ "thumbnail" ] + }, + "udm": { + "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/UDM.tif", + "title": "Unusable Data Mask" + }, + "json-metadata": { + "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/extended-metadata.json", + "title": "Extended Metadata", + "type": "application/json", + "roles": [ "metadata" ] + }, + "ephemeris": { + "href": "http://cool-sat.com/catalog/CS3-20160503_132130_04/S3-20160503_132130_04.EPH", + "title": "Satellite Ephemeris Metadata" + } + } + + } \ No newline at end of file diff --git a/src/DotNetStac/Collection/IStacSummaryItem.cs b/src/DotNetStac/Collection/IStacSummaryItem.cs new file mode 100644 index 00000000..6e9fa03a --- /dev/null +++ b/src/DotNetStac/Collection/IStacSummaryItem.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Stac.Collection +{ + public interface IStacSummaryItem : IEnumerable + { + SummaryItemType SummaryType { get; } + + Type ValueType { get; } + } +} \ No newline at end of file diff --git a/src/DotNetStac/Collection/StacCollection.cs b/src/DotNetStac/Collection/StacCollection.cs new file mode 100644 index 00000000..15c6c5a9 --- /dev/null +++ b/src/DotNetStac/Collection/StacCollection.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using DotNetStac; +using DotNetStac.Converters; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Stac.Converters; +using Stac.Extensions; + +namespace Stac.Collection +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + public class StacCollection : IStacObject + { + private readonly string id; + private Collection links; + + private string stacVersion = StacVersionList.Current; + + private Collection extensions; + + private string description; + private readonly string license; + private StacExtent extent; + private Dictionary summaries; + + [JsonConstructor] + public StacCollection(string id, string description, StacExtent extent, IEnumerable links, string license = "proprietary") + { + this.id = id; + this.description = description; + this.license = license; + this.extent = extent; + this.links = new Collection(links.ToList()); + } + + [JsonProperty("stac_extensions")] + [JsonConverter(typeof(StacExtensionConverter))] + public Collection StacExtensions + { + get + { + if (extensions == null) + extensions = new Collection(); + return extensions; + } + set + { + extensions = value; + } + } + + [JsonProperty("stac_version")] + public string StacVersion + { + get + { + return stacVersion; + } + + set + { + stacVersion = value; + } + } + + [JsonConverter(typeof(CollectionConverter))] + [JsonProperty("links")] + public Collection Links + { + get + { + if (links == null) + links = new Collection(); + return links; + } + set + { + links = value; + } + } + + [JsonProperty("description")] + public string Description + { + get + { + return description; + } + set + { + description = value; + } + } + + [JsonProperty("extent")] + public StacExtent Extent { get => extent; set => extent = value; } + + [JsonProperty("summaries")] + [JsonConverter(typeof(StacSummariesConverter))] + public Dictionary Summaries + { + get + { + return summaries; + } + set + { + summaries = value; + } + } + + public string Id => id; + } +} diff --git a/src/DotNetStac/Collection/StacStatsObject.cs b/src/DotNetStac/Collection/StacStatsObject.cs new file mode 100644 index 00000000..3ecf40be --- /dev/null +++ b/src/DotNetStac/Collection/StacStatsObject.cs @@ -0,0 +1,6 @@ +namespace Stac.Collection +{ + public class StacStatsObject + { + } +} \ No newline at end of file diff --git a/src/DotNetStac/Collection/StacSummaryItem.cs b/src/DotNetStac/Collection/StacSummaryItem.cs new file mode 100644 index 00000000..64e3d937 --- /dev/null +++ b/src/DotNetStac/Collection/StacSummaryItem.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections; + +namespace Stac.Collection +{ + public abstract class StacSummaryItem : IStacSummaryItem + { + public abstract SummaryItemType SummaryType { get; } + public abstract Type ValueType { get; } + + public abstract IEnumerator GetEnumerator(); + } +} \ No newline at end of file diff --git a/src/DotNetStac/Collection/StacSummaryStatsObject.cs b/src/DotNetStac/Collection/StacSummaryStatsObject.cs new file mode 100644 index 00000000..2d3286cf --- /dev/null +++ b/src/DotNetStac/Collection/StacSummaryStatsObject.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Stac.Collection +{ + [JsonObject] + public class StacSummaryStatsObject : StacSummaryItem + { + [JsonProperty("min")] + public T Min { get; set; } + + [JsonProperty("max")] + public T Max { get; set; } + + [JsonExtensionData] + public IDictionary Extensions { get; set; } + + public override SummaryItemType SummaryType => SummaryItemType.StatsObject; + + public override Type ValueType => typeof(T); + + public override IEnumerator GetEnumerator() + { + foreach (T value in new T[2] { Min, Max }) + { + yield return value; + } + } + } +} \ No newline at end of file diff --git a/src/DotNetStac/Collection/StacSummaryValueSet.cs b/src/DotNetStac/Collection/StacSummaryValueSet.cs new file mode 100644 index 00000000..23ff04b1 --- /dev/null +++ b/src/DotNetStac/Collection/StacSummaryValueSet.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; +using Stac.Collection; + +namespace Stac.Collection +{ + public class StacSummaryValueSet : StacSummaryItem + { + private IEnumerable enumerable; + + [JsonConstructor] + public StacSummaryValueSet(IEnumerable enumerable) + { + this.enumerable = new List(enumerable); + } + + public override Type ValueType => typeof(T); + + public override SummaryItemType SummaryType => SummaryItemType.Set; + + public override IEnumerator GetEnumerator() + { + return enumerable.GetEnumerator(); + } + } +} \ No newline at end of file diff --git a/src/DotNetStac/Collection/SummaryItemType.cs b/src/DotNetStac/Collection/SummaryItemType.cs new file mode 100644 index 00000000..9088d190 --- /dev/null +++ b/src/DotNetStac/Collection/SummaryItemType.cs @@ -0,0 +1,9 @@ +namespace Stac.Collection +{ + public enum SummaryItemType + { + Set, + + StatsObject + } +} \ No newline at end of file diff --git a/src/DotNetStac/Converters/StacExtensionConverter.cs b/src/DotNetStac/Converters/StacExtensionConverter.cs index 2af00103..ed2cc40d 100644 --- a/src/DotNetStac/Converters/StacExtensionConverter.cs +++ b/src/DotNetStac/Converters/StacExtensionConverter.cs @@ -34,7 +34,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist List extensionPrefixes = token.ToObject>(); foreach (var extensionPrefix in extensionPrefixes) { - var stacExtension = stacExtensionFactory.CreateStacExtension(extensionPrefix); + var stacExtension = stacExtensionFactory.CreateStacExtension(extensionPrefix, null); if (stacExtension != null) stacExtensions.Add(stacExtension); } diff --git a/src/DotNetStac/Converters/StacSummariesConverter.cs b/src/DotNetStac/Converters/StacSummariesConverter.cs new file mode 100644 index 00000000..b276d8b0 --- /dev/null +++ b/src/DotNetStac/Converters/StacSummariesConverter.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac.Collection; + +namespace Stac.Converters +{ + internal class StacSummariesConverter : JsonConverter + { + public override bool CanConvert(Type objectType) + { + return (objectType == typeof(Dictionary)); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + Dictionary summaries = new Dictionary(); + Dictionary objDic = serializer.Deserialize>(reader); + + foreach (var key in objDic.Keys) + { + if (objDic[key] is JArray) + { + JArray enumerable = (objDic[key] as JArray); + { + switch (enumerable.First().Type) + { + case JTokenType.Boolean: + StacSummaryValueSet boolset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); + summaries.Add(key, boolset); + break; + case JTokenType.Date: + StacSummaryValueSet dateset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); + summaries.Add(key, dateset); + break; + case JTokenType.String: + StacSummaryValueSet stringset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); + summaries.Add(key, stringset); + break; + case JTokenType.Integer: + StacSummaryValueSet intset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); + summaries.Add(key, intset); + break; + case JTokenType.Float: + StacSummaryValueSet floatset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); + summaries.Add(key, floatset); + break; + case JTokenType.Object: + StacSummaryValueSet> objset = new StacSummaryValueSet>(serializer.Deserialize>>(enumerable.CreateReader())); + summaries.Add(key, objset); + break; + } + + } + } + if (objDic[key] is JObject) + { + JObject obj = (objDic[key] as JObject); + if ( obj.ContainsKey("min") && obj.ContainsKey("max") ){ + switch(obj["min"].Type){ + case JTokenType.Date: + StacSummaryStatsObject datestat = serializer.Deserialize>(obj.CreateReader()); + summaries.Add(key, datestat); + break; + case JTokenType.String: + StacSummaryStatsObject stringstat = serializer.Deserialize>(obj.CreateReader()); + summaries.Add(key, stringstat); + break; + case JTokenType.Integer: + StacSummaryStatsObject intstat = serializer.Deserialize>(obj.CreateReader()); + summaries.Add(key, intstat); + break; + case JTokenType.Float: + StacSummaryStatsObject doublestat = serializer.Deserialize>(obj.CreateReader()); + summaries.Add(key, doublestat); + break; + } + } + } + } + + return summaries; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/DotNetStac/DotNetStac.csproj b/src/DotNetStac/DotNetStac.csproj index c877c17b..60a3203d 100644 --- a/src/DotNetStac/DotNetStac.csproj +++ b/src/DotNetStac/DotNetStac.csproj @@ -3,8 +3,10 @@ netstandard2.0 + + \ No newline at end of file diff --git a/src/DotNetStac/Extensions/GenericStacExtension.cs b/src/DotNetStac/Extensions/GenericStacExtension.cs new file mode 100644 index 00000000..7d31d138 --- /dev/null +++ b/src/DotNetStac/Extensions/GenericStacExtension.cs @@ -0,0 +1,26 @@ +using System; + +namespace Stac.Extensions +{ + internal class GenericStacExtension : IStacExtension + { + private string prefix; + + public GenericStacExtension(string prefix) + { + this.prefix = prefix; + } + + public string Id => prefix; + + internal static IStacExtension CreateForStacObject(string prefix, IStacObject stacObject) + { + return new GenericStacExtension(prefix); + } + + public IStacExtension CopyForStacObject(IStacObject stacObject) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/DotNetStac/Extensions/IStacExtension.cs b/src/DotNetStac/Extensions/IStacExtension.cs index 00178fbd..f701f6f3 100644 --- a/src/DotNetStac/Extensions/IStacExtension.cs +++ b/src/DotNetStac/Extensions/IStacExtension.cs @@ -4,5 +4,6 @@ public interface IStacExtension { string Id { get; } + IStacExtension CopyForStacObject(IStacObject stacObject); } } \ No newline at end of file diff --git a/src/DotNetStac/Extensions/IStacExtensionsFactory.cs b/src/DotNetStac/Extensions/IStacExtensionsFactory.cs index 658b4b0a..6f725697 100644 --- a/src/DotNetStac/Extensions/IStacExtensionsFactory.cs +++ b/src/DotNetStac/Extensions/IStacExtensionsFactory.cs @@ -3,7 +3,7 @@ namespace Stac.Extensions public interface IStacExtensionsFactory { - IStacExtension CreateStacExtension(string prefix); + IStacExtension CreateStacExtension(string prefix, IStacObject stacObject); } } \ No newline at end of file diff --git a/src/DotNetStac/Extensions/Sat/SatStacExtension.cs b/src/DotNetStac/Extensions/Sat/SatStacExtension.cs index c2ed5ceb..7a5d4f69 100644 --- a/src/DotNetStac/Extensions/Sat/SatStacExtension.cs +++ b/src/DotNetStac/Extensions/Sat/SatStacExtension.cs @@ -1,4 +1,5 @@ using System; +using Stac; using Stac.Extensions; namespace DotNetStac.Extensions.Sat @@ -10,5 +11,10 @@ public SatStacExtension() } public string Id => "sat"; + + public IStacExtension CopyForStacObject(IStacObject stacObject) + { + return new SatStacExtension(); + } } } diff --git a/src/DotNetStac/Extensions/StacExtensionsFactory.cs b/src/DotNetStac/Extensions/StacExtensionsFactory.cs index 665a7437..46962d2d 100644 --- a/src/DotNetStac/Extensions/StacExtensionsFactory.cs +++ b/src/DotNetStac/Extensions/StacExtensionsFactory.cs @@ -34,9 +34,13 @@ public static StacExtensionsFactory CreateDefaultFactory() return new StacExtensionsFactory(); } - public IStacExtension CreateStacExtension(string prefix) + public IStacExtension CreateStacExtension(string prefix, IStacObject stacObject) { - throw new NotImplementedException(); + if ( stacExtensionsDictionary.ContainsKey(prefix) ) + return stacExtensionsDictionary[prefix].CopyForStacObject(stacObject); + + return GenericStacExtension.CreateForStacObject(prefix, stacObject); } + } } \ No newline at end of file diff --git a/src/DotNetStac/Item/StacItem.cs b/src/DotNetStac/Item/StacItem.cs index 5596b098..b880bfcf 100644 --- a/src/DotNetStac/Item/StacItem.cs +++ b/src/DotNetStac/Item/StacItem.cs @@ -20,6 +20,7 @@ public class StacItem : GeoJSON.Net.Feature.Feature, IStacObject private string stacVersion = StacVersionList.Current; private Collection extensions; + private string collection; [JsonConstructor] public StacItem(IGeometryObject geometry, IDictionary properties = null, string id = null) : base(geometry, properties, id) @@ -84,5 +85,62 @@ public Dictionary Assets return assets; } } + + [JsonProperty("collection")] + public string Collection + { + get + { + return collection; + } + set + { + collection = value; + } + } + + [JsonIgnore] + public Itenso.TimePeriod.ITimePeriod DateTime + { + get + { + if (Properties.ContainsKey("datetime")) + { + if (Properties["datetime"] is DateTime) + return new Itenso.TimePeriod.TimeInterval((DateTime)Properties["datetime"]); + else + { + try + { + return new Itenso.TimePeriod.TimeInterval(System.DateTime.Parse(Properties["datetime"].ToString())); + } + catch (Exception e) + { + throw new FormatException(string.Format("{0} is not a valid"), e); + } + } + } + if (Properties.ContainsKey("start_datetime") && Properties.ContainsKey("end_datetime")) + { + if (Properties["start_datetime"] is DateTime && Properties["end_datetime"] is DateTime) + return new Itenso.TimePeriod.TimeInterval((DateTime)Properties["start_datetime"], + (DateTime)Properties["end_datetime"]); + else + { + try + { + return new Itenso.TimePeriod.TimeInterval(System.DateTime.Parse(Properties["start_datetime"].ToString()), + System.DateTime.Parse(Properties["end_datetime"].ToString())); + } + catch (Exception e) + { + throw new FormatException(string.Format("{0} is not a valid"), e); + } + } + } + + return null; + } + } } } diff --git a/src/DotNetStac/StacExtent.cs b/src/DotNetStac/StacExtent.cs new file mode 100644 index 00000000..ef7732a7 --- /dev/null +++ b/src/DotNetStac/StacExtent.cs @@ -0,0 +1,6 @@ +namespace Stac +{ + public class StacExtent + { + } +} \ No newline at end of file diff --git a/src/DotNetStac/StacObject.cs b/src/DotNetStac/StacObject.cs index 5ea138f4..312bca7f 100644 --- a/src/DotNetStac/StacObject.cs +++ b/src/DotNetStac/StacObject.cs @@ -7,12 +7,8 @@ namespace Stac { - /// - /// A STACObject is the base class for any element of STAC that - /// has an Id, stac version and extensions, links e.g. (Catalogs, Collections, or Items). - /// - [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] public abstract class StacObject : IStacObject { private readonly string id; From d8dee0036a82b636a8e62809685935bddb5a11c4 Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Wed, 17 Jun 2020 23:33:32 +0200 Subject: [PATCH 04/21] Stac collection summary + Tests --- .../Collection/CollectionTests.cs | 35 +++++ ...tionTests_CanSerializeSentinel2Sample.json | 148 ++++++++++++++++++ src/DotNetStac/Collection/IStacSummaryItem.cs | 8 +- src/DotNetStac/Collection/StacCollection.cs | 7 +- src/DotNetStac/Collection/StacSummaryItem.cs | 33 +++- .../Collection/StacSummaryStatsObject.cs | 28 ++-- .../Collection/StacSummaryValueSet.cs | 19 +-- .../Converters/StacSummariesConverter.cs | 66 ++++---- src/DotNetStac/DotNetStac.csproj | 3 +- src/DotNetStac/StacExtent.cs | 8 + src/DotNetStac/StacSpatialExtent.cs | 20 +++ src/DotNetStac/StacTemporalExtent.cs | 21 +++ 12 files changed, 326 insertions(+), 70 deletions(-) create mode 100644 src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json create mode 100644 src/DotNetStac/StacSpatialExtent.cs create mode 100644 src/DotNetStac/StacTemporalExtent.cs diff --git a/src/DotNetStac.Test/Collection/CollectionTests.cs b/src/DotNetStac.Test/Collection/CollectionTests.cs index 6d6d8f2f..d5187d0c 100644 --- a/src/DotNetStac.Test/Collection/CollectionTests.cs +++ b/src/DotNetStac.Test/Collection/CollectionTests.cs @@ -38,7 +38,42 @@ public void CanDeserializeSentinel2Sample() Assert.Equal(DateTime.Parse("2015-06-23T00:00:00Z").ToUniversalTime(), (item.Summaries["datetime"] as StacSummaryStatsObject).Min); + Assert.Equal(32601, (item.Summaries["proj:epsg"] as StacSummaryValueSet).Min()); + Assert.Equal(32660, (item.Summaries["proj:epsg"] as StacSummaryValueSet).Max()); + Assert.Equal(13, item.Summaries["eo:bands"].LongCount()); + Assert.Equal("B1", item.Summaries["eo:bands"][0]["name"]); + Assert.Equal(4.439, item.Summaries["eo:bands"][0]["center_wavelength"]); + + Assert.Equal(2, item.Summaries["view:sun_elevation"].LongCount()); + + + + } + + [Fact] + public void CanSerializeSentinel2Sample() + { + StacExtent extent = new StacExtent(); + extent.Spatial = new StacSpatialExtent( -180, -56, 180, 83); + extent.Temporal = new StacTemporalExtent(DateTime.Parse("2015-06-23T00:00:00Z").ToUniversalTime(), null); + + StacCollection collection = new StacCollection("COPERNICUS/S2", + "Sentinel-2 is a wide-swath, high-resolution, multi-spectral\nimaging mission supporting Copernicus Land Monitoring studies,\nincluding the monitoring of vegetation, soil and water cover,\nas well as observation of inland waterways and coastal areas.\n\nThe Sentinel-2 data contain 13 UINT16 spectral bands representing\nTOA reflectance scaled by 10000. See the [Sentinel-2 User Handbook](https://sentinel.esa.int/documents/247904/685211/Sentinel-2_User_Handbook)\nfor details. In addition, three QA bands are present where one\n(QA60) is a bitmask band with cloud mask information. For more\ndetails, [see the full explanation of how cloud masks are computed.](https://sentinel.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-1c/cloud-masks)\n\nEach Sentinel-2 product (zip archive) may contain multiple\ngranules. Each granule becomes a separate Earth Engine asset.\nEE asset ids for Sentinel-2 assets have the following format:\nCOPERNICUS/S2/20151128T002653_20151128T102149_T56MNN. Here the\nfirst numeric part represents the sensing date and time, the\nsecond numeric part represents the product generation date and\ntime, and the final 6-character string is a unique granule identifier\nindicating its UTM grid reference (see [MGRS](https://en.wikipedia.org/wiki/Military_Grid_Reference_System)).\n\nFor more details on Sentinel-2 radiometric resoltuon, [see this page](https://earth.esa.int/web/sentinel/user-guides/sentinel-2-msi/resolutions/radiometric).\n", + extent); + + collection.Links.Add(StacLink.CreateSelfLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/COPERNICUS_S2.json"))); + collection.Links.Add(StacLink.CreateParentLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/catalog.json"))); + collection.Links.Add(StacLink.CreateRootLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/catalog.json"))); + collection.Links.Add(new StacLink(new Uri("https://scihub.copernicus.eu/twiki/pub/SciHubWebPortal/TermsConditions/Sentinel_Data_Terms_and_Conditions.pdf"), "license", "Legal notice on the use of Copernicus Sentinel Data and Service Information", null)); + + var actualJson = JsonConvert.SerializeObject(collection); + + Console.WriteLine(actualJson); + + var expectedJson = GetExpectedJson("Collection"); + + JsonAssert.AreEqual(expectedJson, actualJson); } } diff --git a/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json b/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json new file mode 100644 index 00000000..368b2643 --- /dev/null +++ b/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json @@ -0,0 +1,148 @@ +{ + "stac_version": "1.0.0-beta.1", + "stac_extensions": [], + "id": "COPERNICUS/S2", + "title": "Sentinel-2 MSI: MultiSpectral Instrument, Level-1C", + "description": "Sentinel-2 is a wide-swath, high-resolution, multi-spectral\nimaging mission supporting Copernicus Land Monitoring studies,\nincluding the monitoring of vegetation, soil and water cover,\nas well as observation of inland waterways and coastal areas.\n\nThe Sentinel-2 data contain 13 UINT16 spectral bands representing\nTOA reflectance scaled by 10000. See the [Sentinel-2 User Handbook](https://sentinel.esa.int/documents/247904/685211/Sentinel-2_User_Handbook)\nfor details. In addition, three QA bands are present where one\n(QA60) is a bitmask band with cloud mask information. For more\ndetails, [see the full explanation of how cloud masks are computed.](https://sentinel.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-1c/cloud-masks)\n\nEach Sentinel-2 product (zip archive) may contain multiple\ngranules. Each granule becomes a separate Earth Engine asset.\nEE asset ids for Sentinel-2 assets have the following format:\nCOPERNICUS/S2/20151128T002653_20151128T102149_T56MNN. Here the\nfirst numeric part represents the sensing date and time, the\nsecond numeric part represents the product generation date and\ntime, and the final 6-character string is a unique granule identifier\nindicating its UTM grid reference (see [MGRS](https://en.wikipedia.org/wiki/Military_Grid_Reference_System)).\n\nFor more details on Sentinel-2 radiometric resoltuon, [see this page](https://earth.esa.int/web/sentinel/user-guides/sentinel-2-msi/resolutions/radiometric).\n", + "license": "proprietary", + "keywords": [ + "copernicus", + "esa", + "eu", + "msi", + "radiance", + "sentinel" + ], + "providers": [ + { + "name": "European Union/ESA/Copernicus", + "roles": [ + "producer", + "licensor" + ], + "url": "https://sentinel.esa.int/web/sentinel/user-guides/sentinel-2-msi" + } + ], + "extent": { + "spatial": { + "bbox": [ + [ + -180, + -56, + 180, + 83 + ] + ] + }, + "temporal": { + "interval": [ + [ + "2015-06-23T00:00:00Z", + null + ] + ] + } + }, + + "summaries": { + "datetime": { + "min": "2015-06-23T00:00:00Z", + "max": "2019-07-10T13:44:56Z" + }, + "platform": ["sentinel-2a","sentinel-2b"], + "constellation": ["sentinel-2"], + "instruments": ["msi"], + "view:off_nadir": { + "min": 0.0, + "max": 100 + }, + "view:sun_elevation": { + "min": 6.78, + "max": 89.9 + }, + "sci:citation": ["Copernicus Sentinel data [Year]"], + "gsd": [10,30,60], + "proj:epsg": [32601,32602,32603,32604,32605,32606,32607,32608,32609,32610,32611,32612,32613,32614,32615,32616,32617,32618,32619,32620,32621,32622,32623,32624,32625,32626,32627,32628,32629,32630,32631,32632,32633,32634,32635,32636,32637,32638,32639,32640,32641,32642,32643,32644,32645,32646,32647,32648,32649,32650,32651,32652,32653,32654,32655,32656,32657,32658,32659,32660], + "eo:bands": [ + { + "name": "B1", + "common_name": "coastal", + "center_wavelength": 4.439 + }, + { + "name": "B2", + "common_name": "blue", + "center_wavelength": 4.966 + }, + { + "name": "B3", + "common_name": "green", + "center_wavelength": 5.6 + }, + { + "name": "B4", + "common_name": "red", + "center_wavelength": 6.645 + }, + { + "name": "B5", + "center_wavelength": 7.039 + }, + { + "name": "B6", + "center_wavelength": 7.402 + }, + { + "name": "B7", + "center_wavelength": 7.825 + }, + { + "name": "B8", + "common_name": "nir", + "center_wavelength": 8.351 + }, + { + "name": "B8A", + "center_wavelength": 8.648 + }, + { + "name": "B9", + "center_wavelength": 9.45 + }, + { + "name": "B10", + "center_wavelength": 1.3735 + }, + { + "name": "B11", + "common_name": "swir16", + "center_wavelength": 1.6137 + }, + { + "name": "B12", + "common_name": "swir22", + "center_wavelength": 2.2024 + } + ] + }, + "links": [ + { + "rel": "self", + "href": "https://storage.cloud.google.com/earthengine-test/catalog/COPERNICUS_S2.json" + }, + { + "rel": "parent", + "href": "https://storage.cloud.google.com/earthengine-test/catalog/catalog.json" + }, + { + "rel": "root", + "href": "https://storage.cloud.google.com/earthengine-test/catalog/catalog.json" + }, + { + "rel": "license", + "href": "https://scihub.copernicus.eu/twiki/pub/SciHubWebPortal/TermsConditions/Sentinel_Data_Terms_and_Conditions.pdf", + "title": "Legal notice on the use of Copernicus Sentinel Data and Service Information" + } + ] + } + \ No newline at end of file diff --git a/src/DotNetStac/Collection/IStacSummaryItem.cs b/src/DotNetStac/Collection/IStacSummaryItem.cs index 6e9fa03a..48af1c83 100644 --- a/src/DotNetStac/Collection/IStacSummaryItem.cs +++ b/src/DotNetStac/Collection/IStacSummaryItem.cs @@ -1,13 +1,17 @@ using System; using System.Collections; using System.Collections.Generic; +using Newtonsoft.Json.Linq; namespace Stac.Collection { - public interface IStacSummaryItem : IEnumerable + public interface IStacSummaryItem : IEnumerable { SummaryItemType SummaryType { get; } - Type ValueType { get; } + JToken this[object key] { get; } + + JToken AsJToken { get; } + } } \ No newline at end of file diff --git a/src/DotNetStac/Collection/StacCollection.cs b/src/DotNetStac/Collection/StacCollection.cs index 15c6c5a9..8eb1cf48 100644 --- a/src/DotNetStac/Collection/StacCollection.cs +++ b/src/DotNetStac/Collection/StacCollection.cs @@ -27,13 +27,16 @@ public class StacCollection : IStacObject private Dictionary summaries; [JsonConstructor] - public StacCollection(string id, string description, StacExtent extent, IEnumerable links, string license = "proprietary") + public StacCollection(string id, string description, StacExtent extent, IEnumerable links = null, string license = "proprietary") { this.id = id; this.description = description; this.license = license; this.extent = extent; - this.links = new Collection(links.ToList()); + if ( links == null ) + this.links = new Collection(); + else + this.links = new Collection(links.ToList()); } [JsonProperty("stac_extensions")] diff --git a/src/DotNetStac/Collection/StacSummaryItem.cs b/src/DotNetStac/Collection/StacSummaryItem.cs index 64e3d937..08c895ad 100644 --- a/src/DotNetStac/Collection/StacSummaryItem.cs +++ b/src/DotNetStac/Collection/StacSummaryItem.cs @@ -1,13 +1,40 @@ using System; using System.Collections; +using System.Collections.Generic; +using Newtonsoft.Json.Linq; namespace Stac.Collection { - public abstract class StacSummaryItem : IStacSummaryItem + public abstract class StacSummaryItem : IStacSummaryItem { + protected readonly JToken summary; + + protected StacSummaryItem(JToken summary) + { + this.summary = summary; + } + + public JToken this[object key] + { + get + { + return summary[key]; + } + } + public abstract SummaryItemType SummaryType { get; } - public abstract Type ValueType { get; } - public abstract IEnumerator GetEnumerator(); + public JToken AsJToken => summary; + + public IEnumerator GetEnumerator() + { + return summary.Children().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return summary.Children().GetEnumerator(); + } + } } \ No newline at end of file diff --git a/src/DotNetStac/Collection/StacSummaryStatsObject.cs b/src/DotNetStac/Collection/StacSummaryStatsObject.cs index 2d3286cf..e6ddc7c2 100644 --- a/src/DotNetStac/Collection/StacSummaryStatsObject.cs +++ b/src/DotNetStac/Collection/StacSummaryStatsObject.cs @@ -6,28 +6,26 @@ namespace Stac.Collection { - [JsonObject] - public class StacSummaryStatsObject : StacSummaryItem + public class StacSummaryStatsObject : StacSummaryItem { - [JsonProperty("min")] + public StacSummaryStatsObject(JObject summary) : base(summary) + { + Min = summary["min"].Value(); + Max = summary["max"].Value(); + } + + public StacSummaryStatsObject(T min, T max) : base(null) + { + Min = min; + Max = max; + } + public T Min { get; set; } - [JsonProperty("max")] public T Max { get; set; } - [JsonExtensionData] - public IDictionary Extensions { get; set; } - public override SummaryItemType SummaryType => SummaryItemType.StatsObject; - public override Type ValueType => typeof(T); - public override IEnumerator GetEnumerator() - { - foreach (T value in new T[2] { Min, Max }) - { - yield return value; - } - } } } \ No newline at end of file diff --git a/src/DotNetStac/Collection/StacSummaryValueSet.cs b/src/DotNetStac/Collection/StacSummaryValueSet.cs index 23ff04b1..f37049c9 100644 --- a/src/DotNetStac/Collection/StacSummaryValueSet.cs +++ b/src/DotNetStac/Collection/StacSummaryValueSet.cs @@ -3,27 +3,28 @@ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using Stac.Collection; namespace Stac.Collection { - public class StacSummaryValueSet : StacSummaryItem + public class StacSummaryValueSet : StacSummaryItem, IEnumerable { - private IEnumerable enumerable; + private readonly List summarySet; - [JsonConstructor] - public StacSummaryValueSet(IEnumerable enumerable) + public StacSummaryValueSet(JArray summarySet) : base(summarySet) { - this.enumerable = new List(enumerable); + this.summarySet = summarySet.ToObject>(); } - public override Type ValueType => typeof(T); - public override SummaryItemType SummaryType => SummaryItemType.Set; - public override IEnumerator GetEnumerator() + public int Count => summary.Count(); + + IEnumerator IEnumerable.GetEnumerator() { - return enumerable.GetEnumerator(); + return summarySet.GetEnumerator(); } + } } \ No newline at end of file diff --git a/src/DotNetStac/Converters/StacSummariesConverter.cs b/src/DotNetStac/Converters/StacSummariesConverter.cs index b276d8b0..cd3d934c 100644 --- a/src/DotNetStac/Converters/StacSummariesConverter.cs +++ b/src/DotNetStac/Converters/StacSummariesConverter.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Net.Mime; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Stac.Collection; @@ -25,57 +26,46 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist if (objDic[key] is JArray) { JArray enumerable = (objDic[key] as JArray); + switch (enumerable.First().Type) { - switch (enumerable.First().Type) - { - case JTokenType.Boolean: - StacSummaryValueSet boolset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); - summaries.Add(key, boolset); - break; - case JTokenType.Date: - StacSummaryValueSet dateset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); - summaries.Add(key, dateset); - break; - case JTokenType.String: - StacSummaryValueSet stringset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); - summaries.Add(key, stringset); - break; - case JTokenType.Integer: - StacSummaryValueSet intset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); - summaries.Add(key, intset); - break; - case JTokenType.Float: - StacSummaryValueSet floatset = new StacSummaryValueSet(serializer.Deserialize>(enumerable.CreateReader())); - summaries.Add(key, floatset); - break; - case JTokenType.Object: - StacSummaryValueSet> objset = new StacSummaryValueSet>(serializer.Deserialize>>(enumerable.CreateReader())); - summaries.Add(key, objset); - break; - } - + case JTokenType.Boolean: + summaries.Add(key, new StacSummaryValueSet(enumerable)); + break; + case JTokenType.Date: + summaries.Add(key, new StacSummaryValueSet(enumerable)); + break; + case JTokenType.String: + summaries.Add(key, new StacSummaryValueSet(enumerable)); + break; + case JTokenType.Integer: + summaries.Add(key, new StacSummaryValueSet(enumerable)); + break; + case JTokenType.Float: + summaries.Add(key, new StacSummaryValueSet(enumerable)); + break; + case JTokenType.Object: + summaries.Add(key, new StacSummaryValueSet(enumerable)); + break; } } if (objDic[key] is JObject) { JObject obj = (objDic[key] as JObject); - if ( obj.ContainsKey("min") && obj.ContainsKey("max") ){ - switch(obj["min"].Type){ + if (obj.ContainsKey("min") && obj.ContainsKey("max")) + { + switch (obj["min"].Type) + { case JTokenType.Date: - StacSummaryStatsObject datestat = serializer.Deserialize>(obj.CreateReader()); - summaries.Add(key, datestat); + summaries.Add(key, new StacSummaryStatsObject(obj)); break; case JTokenType.String: - StacSummaryStatsObject stringstat = serializer.Deserialize>(obj.CreateReader()); - summaries.Add(key, stringstat); + summaries.Add(key, new StacSummaryStatsObject(obj)); break; case JTokenType.Integer: - StacSummaryStatsObject intstat = serializer.Deserialize>(obj.CreateReader()); - summaries.Add(key, intstat); + summaries.Add(key, new StacSummaryStatsObject(obj)); break; case JTokenType.Float: - StacSummaryStatsObject doublestat = serializer.Deserialize>(obj.CreateReader()); - summaries.Add(key, doublestat); + summaries.Add(key, new StacSummaryStatsObject(obj)); break; } } diff --git a/src/DotNetStac/DotNetStac.csproj b/src/DotNetStac/DotNetStac.csproj index 60a3203d..51708f11 100644 --- a/src/DotNetStac/DotNetStac.csproj +++ b/src/DotNetStac/DotNetStac.csproj @@ -3,10 +3,11 @@ netstandard2.0 - + + \ No newline at end of file diff --git a/src/DotNetStac/StacExtent.cs b/src/DotNetStac/StacExtent.cs index ef7732a7..2fa9d90c 100644 --- a/src/DotNetStac/StacExtent.cs +++ b/src/DotNetStac/StacExtent.cs @@ -1,6 +1,14 @@ +using Newtonsoft.Json; + namespace Stac { + [JsonObject] public class StacExtent { + [JsonProperty("spatial")] + public StacSpatialExtent Spatial { get; set; } + + [JsonProperty("temporal")] + public StacTemporalExtent Temporal { get; set; } } } \ No newline at end of file diff --git a/src/DotNetStac/StacSpatialExtent.cs b/src/DotNetStac/StacSpatialExtent.cs new file mode 100644 index 00000000..d06bf248 --- /dev/null +++ b/src/DotNetStac/StacSpatialExtent.cs @@ -0,0 +1,20 @@ +using Newtonsoft.Json; + +namespace Stac +{ + [JsonObject] + public class StacSpatialExtent + { + public StacSpatialExtent() + { + } + + public StacSpatialExtent(double minX, double minY, double maxX, double maxY) + { + BoundingBoxes = new double[1][] { new double[4] { minX, minY, maxX, maxY } }; + } + + [JsonProperty("bbox")] + public double[][] BoundingBoxes { get; set; } + } +} \ No newline at end of file diff --git a/src/DotNetStac/StacTemporalExtent.cs b/src/DotNetStac/StacTemporalExtent.cs new file mode 100644 index 00000000..3378a011 --- /dev/null +++ b/src/DotNetStac/StacTemporalExtent.cs @@ -0,0 +1,21 @@ +using System; +using Newtonsoft.Json; + +namespace Stac +{ + [JsonObject] + public class StacTemporalExtent + { + public StacTemporalExtent() + { + } + + public StacTemporalExtent(DateTime? start, DateTime? end) + { + Interval = new DateTime?[1][] { new DateTime?[2] { start, end } }; + } + + [JsonProperty("interval")] + public DateTime?[][] Interval { get; set; } + } +} \ No newline at end of file From a5456c8e2ac9522f0b9adc22665806559af50a5f Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 23 Jun 2020 21:01:39 +0200 Subject: [PATCH 05/21] Stac Catalog + minimal tests --- src/DotNetStac.Test/Catalog/CatalogTests.cs | 55 +++++++++++ .../Collection/CollectionTests.cs | 2 +- ...alogTests_CanDeserializeMinimalSample.json | 10 ++ ...atalogTests_CanSerializeMinimalSample.json | 11 +++ src/DotNetStac/Catalog/StacCollection.cs | 99 +++++++++++++++++++ src/DotNetStac/Collection/StacCollection.cs | 80 +-------------- 6 files changed, 180 insertions(+), 77 deletions(-) create mode 100644 src/DotNetStac.Test/Catalog/CatalogTests.cs create mode 100644 src/DotNetStac.Test/Resources/Catalog/CatalogTests_CanDeserializeMinimalSample.json create mode 100644 src/DotNetStac.Test/Resources/Catalog/CatalogTests_CanSerializeMinimalSample.json create mode 100644 src/DotNetStac/Catalog/StacCollection.cs diff --git a/src/DotNetStac.Test/Catalog/CatalogTests.cs b/src/DotNetStac.Test/Catalog/CatalogTests.cs new file mode 100644 index 00000000..38d0b19e --- /dev/null +++ b/src/DotNetStac.Test/Catalog/CatalogTests.cs @@ -0,0 +1,55 @@ +using System; +using System.Linq; +using Newtonsoft.Json; +using Stac.Catalog; +using Xunit; + +namespace Stac.Test.Catalog +{ + public class CatalogTests : TestBase + { + [Fact] + public void CanDeserializeMinimalSample() + { + var json = GetExpectedJson("Catalog"); + + var catalog = JsonConvert.DeserializeObject(json); + + Assert.NotNull(catalog); + + Assert.Equal("1.0.0-beta.1", catalog.StacVersion); + + Assert.Empty(catalog.StacExtensions); + + Assert.Equal("NAIP", catalog.Id); + + Assert.Equal("Catalog of NAIP Imagery", catalog.Description); + + Assert.Contains(catalog.Links, link => link.RelationshipType == "self" && link.Uri == new Uri("https://www.fsa.usda.gov/naip/catalog.json") ); + Assert.Contains(catalog.Links, link => link.RelationshipType == "child" && link.Uri == new Uri("https://www.fsa.usda.gov/naip/30087/catalog.json") ); + Assert.Contains(catalog.Links, link => link.RelationshipType == "root" && link.Uri == new Uri("https://www.fsa.usda.gov/catalog.json") ); + + + } + + [Fact] + public void CanSerializeMinimalSample() + { + + StacCatalog collection = new StacCatalog("NAIP", "Catalog of NAIP Imagery"); + + collection.Links.Add(StacLink.CreateSelfLink(new Uri("https://www.fsa.usda.gov/naip/catalog.json"))); + collection.Links.Add(new StacLink(new Uri("https://www.fsa.usda.gov/naip/30087/catalog.json"), "child", null, null)); + collection.Links.Add(StacLink.CreateRootLink(new Uri("https://www.fsa.usda.gov/catalog.json"))); + + var actualJson = JsonConvert.SerializeObject(collection); + + Console.WriteLine(actualJson); + + var expectedJson = GetExpectedJson("Catalog"); + + JsonAssert.AreEqual(expectedJson, actualJson); + } + + } +} \ No newline at end of file diff --git a/src/DotNetStac.Test/Collection/CollectionTests.cs b/src/DotNetStac.Test/Collection/CollectionTests.cs index d5187d0c..2f793934 100644 --- a/src/DotNetStac.Test/Collection/CollectionTests.cs +++ b/src/DotNetStac.Test/Collection/CollectionTests.cs @@ -7,7 +7,7 @@ using Stac.Collection; using Xunit; -namespace Stac.Test.Item +namespace Stac.Test.Collection { public class CollectionTests : TestBase { diff --git a/src/DotNetStac.Test/Resources/Catalog/CatalogTests_CanDeserializeMinimalSample.json b/src/DotNetStac.Test/Resources/Catalog/CatalogTests_CanDeserializeMinimalSample.json new file mode 100644 index 00000000..2143f65c --- /dev/null +++ b/src/DotNetStac.Test/Resources/Catalog/CatalogTests_CanDeserializeMinimalSample.json @@ -0,0 +1,10 @@ +{ + "stac_version": "1.0.0-beta.1", + "id": "NAIP", + "description": "Catalog of NAIP Imagery", + "links": [ + { "rel": "self", "href": "https://www.fsa.usda.gov/naip/catalog.json" }, + { "rel": "child", "href": "https://www.fsa.usda.gov/naip/30087/catalog.json" }, + { "rel": "root", "href": "https://www.fsa.usda.gov/catalog.json" } + ] + } \ No newline at end of file diff --git a/src/DotNetStac.Test/Resources/Catalog/CatalogTests_CanSerializeMinimalSample.json b/src/DotNetStac.Test/Resources/Catalog/CatalogTests_CanSerializeMinimalSample.json new file mode 100644 index 00000000..740d41db --- /dev/null +++ b/src/DotNetStac.Test/Resources/Catalog/CatalogTests_CanSerializeMinimalSample.json @@ -0,0 +1,11 @@ +{ + "stac_version": "1.0.0-beta.1", + "stac_extensions": [], + "id": "NAIP", + "description": "Catalog of NAIP Imagery", + "links": [ + { "rel": "self", "href": "https://www.fsa.usda.gov/naip/catalog.json" }, + { "rel": "child", "href": "https://www.fsa.usda.gov/naip/30087/catalog.json" }, + { "rel": "root", "href": "https://www.fsa.usda.gov/catalog.json" } + ] + } \ No newline at end of file diff --git a/src/DotNetStac/Catalog/StacCollection.cs b/src/DotNetStac/Catalog/StacCollection.cs new file mode 100644 index 00000000..2ee9dbba --- /dev/null +++ b/src/DotNetStac/Catalog/StacCollection.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using DotNetStac; +using DotNetStac.Converters; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Stac.Converters; +using Stac.Extensions; + +namespace Stac.Catalog +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + public class StacCatalog : IStacObject + { + private readonly string id; + private Collection links; + + private string stacVersion = StacVersionList.Current; + + private Collection extensions; + + private string description; + + [JsonConstructor] + public StacCatalog(string id, string description, IEnumerable links = null) + { + this.id = id; + this.description = description; + if ( links == null ) + this.links = new Collection(); + else + this.links = new Collection(links.ToList()); + } + + [JsonProperty("stac_extensions")] + [JsonConverter(typeof(StacExtensionConverter))] + public Collection StacExtensions + { + get + { + if (extensions == null) + extensions = new Collection(); + return extensions; + } + set + { + extensions = value; + } + } + + [JsonProperty("stac_version")] + public string StacVersion + { + get + { + return stacVersion; + } + + set + { + stacVersion = value; + } + } + + [JsonConverter(typeof(CollectionConverter))] + [JsonProperty("links")] + public Collection Links + { + get + { + if (links == null) + links = new Collection(); + return links; + } + set + { + links = value; + } + } + + [JsonProperty("description")] + public string Description + { + get + { + return description; + } + set + { + description = value; + } + } + + [JsonProperty("id")] + public string Id => id; + } +} diff --git a/src/DotNetStac/Collection/StacCollection.cs b/src/DotNetStac/Collection/StacCollection.cs index 8eb1cf48..8f29f3b3 100644 --- a/src/DotNetStac/Collection/StacCollection.cs +++ b/src/DotNetStac/Collection/StacCollection.cs @@ -6,96 +6,25 @@ using DotNetStac.Converters; using GeoJSON.Net.Geometry; using Newtonsoft.Json; +using Stac.Catalog; using Stac.Converters; using Stac.Extensions; namespace Stac.Collection { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public class StacCollection : IStacObject + public class StacCollection : StacCatalog, IStacObject { - private readonly string id; - private Collection links; - - private string stacVersion = StacVersionList.Current; - - private Collection extensions; - - private string description; private readonly string license; private StacExtent extent; private Dictionary summaries; [JsonConstructor] - public StacCollection(string id, string description, StacExtent extent, IEnumerable links = null, string license = "proprietary") + public StacCollection(string id, string description, StacExtent extent, IEnumerable links = null, string license = "proprietary"): + base(id, description, links) { - this.id = id; - this.description = description; this.license = license; this.extent = extent; - if ( links == null ) - this.links = new Collection(); - else - this.links = new Collection(links.ToList()); - } - - [JsonProperty("stac_extensions")] - [JsonConverter(typeof(StacExtensionConverter))] - public Collection StacExtensions - { - get - { - if (extensions == null) - extensions = new Collection(); - return extensions; - } - set - { - extensions = value; - } - } - - [JsonProperty("stac_version")] - public string StacVersion - { - get - { - return stacVersion; - } - - set - { - stacVersion = value; - } - } - - [JsonConverter(typeof(CollectionConverter))] - [JsonProperty("links")] - public Collection Links - { - get - { - if (links == null) - links = new Collection(); - return links; - } - set - { - links = value; - } - } - - [JsonProperty("description")] - public string Description - { - get - { - return description; - } - set - { - description = value; - } } [JsonProperty("extent")] @@ -115,6 +44,5 @@ public Dictionary Summaries } } - public string Id => id; } } From 7105b164519372457628f7f6972aa81c8fa5f989 Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 23 Jun 2020 21:09:11 +0200 Subject: [PATCH 06/21] travis build --- .travis.yaml | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .travis.yaml diff --git a/.travis.yaml b/.travis.yaml new file mode 100644 index 00000000..d04ba2af --- /dev/null +++ b/.travis.yaml @@ -0,0 +1,10 @@ +language: csharp +dist: trusty +mono: none +dotnet: 2.0.0 +solution: "./src/DotNetStac.sln" +install: +- dotnet restore src/ +script: +- dotnet build src/ +- dotnet test src/DotNetStac.Test \ No newline at end of file From d8bec9c61c6d653efdfe46c8589a8affaef78613 Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 23 Jun 2020 21:13:57 +0200 Subject: [PATCH 07/21] double tests --- .../CollectionTests_CanSerializeSentinel2Sample.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json b/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json index 368b2643..95670ce7 100644 --- a/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json +++ b/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json @@ -27,10 +27,10 @@ "spatial": { "bbox": [ [ - -180, - -56, - 180, - 83 + -180.0, + -56.0, + 180.0, + 83.0 ] ] }, From 82b4e5eeadc79bfc471e120697493de8eec892e5 Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 23 Jun 2020 21:16:40 +0200 Subject: [PATCH 08/21] .travis.yml --- .travis.yaml => .travis.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .travis.yaml => .travis.yml (100%) diff --git a/.travis.yaml b/.travis.yml similarity index 100% rename from .travis.yaml rename to .travis.yml From 3c1e0571750f84bdf819d42fcaf79bf84cd9b292 Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 23 Jun 2020 21:18:42 +0200 Subject: [PATCH 09/21] dotnet 3.0.0 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d04ba2af..45280230 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: csharp dist: trusty mono: none -dotnet: 2.0.0 +dotnet: 3.0.0 solution: "./src/DotNetStac.sln" install: - dotnet restore src/ From 3a1d5fd9a04c9852504df5d9bfb38b43ae2c5f28 Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 23 Jun 2020 21:22:16 +0200 Subject: [PATCH 10/21] dotnet 3.0 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 45280230..d4dc1407 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: csharp dist: trusty mono: none -dotnet: 3.0.0 +dotnet: 3.0 solution: "./src/DotNetStac.sln" install: - dotnet restore src/ From 3efbf55b549d8d2ac5dcf181dca2992d29c017fb Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 23 Jun 2020 21:24:57 +0200 Subject: [PATCH 11/21] xenial --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d4dc1407..5ef10c3d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: csharp -dist: trusty +dist: xenial mono: none dotnet: 3.0 solution: "./src/DotNetStac.sln" From d7b2e6761d4aa8a4175d4c1a9b215b80686f1e70 Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 23 Jun 2020 22:31:13 +0200 Subject: [PATCH 12/21] More properties and more tests --- LICENSE | 661 ++++++++++++++++++ README.md | 6 +- .../Collection/CollectionTests.cs | 18 +- src/DotNetStac.Test/JsonAssert.cs | 32 +- src/DotNetStac/Catalog/StacCollection.cs | 20 + src/DotNetStac/Collection/StacCollection.cs | 18 +- src/DotNetStac/Collection/StacProvider.cs | 35 + src/DotNetStac/Collection/StacProviderRole.cs | 15 + src/DotNetStac/StacLink.cs | 15 +- 9 files changed, 801 insertions(+), 19 deletions(-) create mode 100644 LICENSE create mode 100644 src/DotNetStac/Collection/StacProvider.cs create mode 100644 src/DotNetStac/Collection/StacProviderRole.cs diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..0ad25db4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 364adc05..0cac8e33 100644 --- a/README.md +++ b/README.md @@ -1 +1,5 @@ -DotNetStac +[![Build Status](https://travis-ci.com/Terradue/DotNetStac.svg?branch=develop)](https://travis-ci.com/Terradue/DotNetStac) + +# DotNetStac +.Net library for working with any SpatioTemporal Asset Catalog (STAC) + diff --git a/src/DotNetStac.Test/Collection/CollectionTests.cs b/src/DotNetStac.Test/Collection/CollectionTests.cs index 2f793934..381847ec 100644 --- a/src/DotNetStac.Test/Collection/CollectionTests.cs +++ b/src/DotNetStac.Test/Collection/CollectionTests.cs @@ -61,12 +61,28 @@ public void CanSerializeSentinel2Sample() StacCollection collection = new StacCollection("COPERNICUS/S2", "Sentinel-2 is a wide-swath, high-resolution, multi-spectral\nimaging mission supporting Copernicus Land Monitoring studies,\nincluding the monitoring of vegetation, soil and water cover,\nas well as observation of inland waterways and coastal areas.\n\nThe Sentinel-2 data contain 13 UINT16 spectral bands representing\nTOA reflectance scaled by 10000. See the [Sentinel-2 User Handbook](https://sentinel.esa.int/documents/247904/685211/Sentinel-2_User_Handbook)\nfor details. In addition, three QA bands are present where one\n(QA60) is a bitmask band with cloud mask information. For more\ndetails, [see the full explanation of how cloud masks are computed.](https://sentinel.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-1c/cloud-masks)\n\nEach Sentinel-2 product (zip archive) may contain multiple\ngranules. Each granule becomes a separate Earth Engine asset.\nEE asset ids for Sentinel-2 assets have the following format:\nCOPERNICUS/S2/20151128T002653_20151128T102149_T56MNN. Here the\nfirst numeric part represents the sensing date and time, the\nsecond numeric part represents the product generation date and\ntime, and the final 6-character string is a unique granule identifier\nindicating its UTM grid reference (see [MGRS](https://en.wikipedia.org/wiki/Military_Grid_Reference_System)).\n\nFor more details on Sentinel-2 radiometric resoltuon, [see this page](https://earth.esa.int/web/sentinel/user-guides/sentinel-2-msi/resolutions/radiometric).\n", extent); - + + collection.Title = "Sentinel-2 MSI: MultiSpectral Instrument, Level-1C"; + collection.Links.Add(StacLink.CreateSelfLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/COPERNICUS_S2.json"))); collection.Links.Add(StacLink.CreateParentLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/catalog.json"))); collection.Links.Add(StacLink.CreateRootLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/catalog.json"))); collection.Links.Add(new StacLink(new Uri("https://scihub.copernicus.eu/twiki/pub/SciHubWebPortal/TermsConditions/Sentinel_Data_Terms_and_Conditions.pdf"), "license", "Legal notice on the use of Copernicus Sentinel Data and Service Information", null)); + collection.Keywords = new System.Collections.ObjectModel.Collection(new string[] { + "copernicus", + "esa", + "eu", + "msi", + "radiance", + "sentinel"}); + + collection.Providers = new System.Collections.ObjectModel.Collection( + new StacProvider[]{new StacProvider("European Union/ESA/Copernicus"){ + Roles = new List() { StacProviderRole.producer, StacProviderRole.licensor}, + Uri = new Uri("https://sentinel.esa.int/web/sentinel/user-guides/sentinel-2-msi") + }}); + var actualJson = JsonConvert.SerializeObject(collection); Console.WriteLine(actualJson); diff --git a/src/DotNetStac.Test/JsonAssert.cs b/src/DotNetStac.Test/JsonAssert.cs index 5cd03ab9..cde6cb99 100644 --- a/src/DotNetStac.Test/JsonAssert.cs +++ b/src/DotNetStac.Test/JsonAssert.cs @@ -52,10 +52,40 @@ private static JObject SortProperties(this JObject jObject) { value = value.SortProperties(); result.Add(property.Name, value); + continue; + } + + var avalues = property.Value as JArray; + + if (avalues != null) + { + avalues = avalues.SortProperties(); + result.Add(property.Name, avalues); + continue; + } + + result.Add(property.Name, property.Value); + } + + return result; + } + + private static JArray SortProperties(this JArray jArray) + { + var result = new JArray(); + + foreach (var item in jArray) + { + var value = item as JObject; + + if (value != null) + { + value = value.SortProperties(); + result.Add(value); } else { - result.Add(property.Name, property.Value); + result.Add(item); } } diff --git a/src/DotNetStac/Catalog/StacCollection.cs b/src/DotNetStac/Catalog/StacCollection.cs index 2ee9dbba..0f12a91f 100644 --- a/src/DotNetStac/Catalog/StacCollection.cs +++ b/src/DotNetStac/Catalog/StacCollection.cs @@ -22,6 +22,9 @@ public class StacCatalog : IStacObject private Collection extensions; private string description; + private Collection keywords; + + private string title; [JsonConstructor] public StacCatalog(string id, string description, IEnumerable links = null) @@ -80,6 +83,21 @@ public Collection Links } } + [JsonProperty("keywords", DefaultValueHandling = DefaultValueHandling.Ignore)] + public Collection Keywords + { + get + { + if (keywords == null) + keywords = new Collection(); + return keywords; + } + set + { + keywords = value; + } + } + [JsonProperty("description")] public string Description { @@ -95,5 +113,7 @@ public string Description [JsonProperty("id")] public string Id => id; + + public string Title { get => title; set => title = value; } } } diff --git a/src/DotNetStac/Collection/StacCollection.cs b/src/DotNetStac/Collection/StacCollection.cs index 8f29f3b3..4f57e61b 100644 --- a/src/DotNetStac/Collection/StacCollection.cs +++ b/src/DotNetStac/Collection/StacCollection.cs @@ -15,12 +15,14 @@ namespace Stac.Collection [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] public class StacCollection : StacCatalog, IStacObject { - private readonly string license; + private string license; private StacExtent extent; private Dictionary summaries; + private Collection providers; + [JsonConstructor] - public StacCollection(string id, string description, StacExtent extent, IEnumerable links = null, string license = "proprietary"): + public StacCollection(string id, string description, StacExtent extent, IEnumerable links = null, string license = "proprietary") : base(id, description, links) { this.license = license; @@ -44,5 +46,17 @@ public Dictionary Summaries } } + [JsonProperty("license")] + public string License { get => license; set => license = value; } + + [JsonProperty("providers")] + public Collection Providers + { + get { return providers; } + set + { + providers = value; + } + } } } diff --git a/src/DotNetStac/Collection/StacProvider.cs b/src/DotNetStac/Collection/StacProvider.cs new file mode 100644 index 00000000..1bda4b69 --- /dev/null +++ b/src/DotNetStac/Collection/StacProvider.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Stac.Collection +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + public class StacProvider + { + private string name; + + private string description; + + private List roles; + private Uri uri; + + public StacProvider(string name) + { + this.name = name; + } + + [JsonProperty("name")] + public string Name { get => name; set => name = value; } + + [JsonProperty("description")] + public string Description { get => description; set => description = value; } + + [JsonProperty("roles")] + public List Roles { get => roles; set => roles = value; } + + [JsonProperty("url")] + public Uri Uri { get => uri; set => uri = value; } + } +} \ No newline at end of file diff --git a/src/DotNetStac/Collection/StacProviderRole.cs b/src/DotNetStac/Collection/StacProviderRole.cs new file mode 100644 index 00000000..50bd525a --- /dev/null +++ b/src/DotNetStac/Collection/StacProviderRole.cs @@ -0,0 +1,15 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Stac.Collection +{ + [JsonConverter(typeof(StringEnumConverter))] + public enum StacProviderRole + { + licensor, + producer, + processor, + host + + } +} \ No newline at end of file diff --git a/src/DotNetStac/StacLink.cs b/src/DotNetStac/StacLink.cs index 5f72ec27..845e9688 100644 --- a/src/DotNetStac/StacLink.cs +++ b/src/DotNetStac/StacLink.cs @@ -41,7 +41,7 @@ public static StacLink CreateAlternateLink(Uri uri, string mediaType = null) #endregion - Uri base_uri, href; + Uri href; string rel, title, type; public StacLink() @@ -65,25 +65,12 @@ public StacLink(StacLink source) { if (source == null) throw new ArgumentNullException("source"); - base_uri = source.base_uri; href = source.href; rel = source.rel; title = source.title; type = source.type; } - [JsonIgnore] - public Uri BaseUri - { - get { return base_uri; } - set - { - if (value != null && !value.IsAbsoluteUri) - throw new ArgumentException("Base URI must not be relative"); - base_uri = value; - } - } - [JsonProperty("type")] public string MediaType { From e131e521c1e1d29cb13f660439f51bcef9a47af6 Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Thu, 25 Jun 2020 22:30:16 +0200 Subject: [PATCH 13/21] Load Catalog helpers + Tests --- src/DotNetStac.Test/PriorityOrderer.cs | 46 ++ .../Resources/UseCases/Sentinel2/catalog.json | 19 + .../Sentinel2/sentinel-2-l1c/catalog.json | 524 ++++++++++++++++++ src/DotNetStac.Test/TestBase.cs | 13 + src/DotNetStac.Test/TestPriorityAttribute.cs | 15 + src/DotNetStac.Test/UseCases/Sentinel2.cs | 33 ++ .../Catalog/StacCollection.Helper.cs | 52 ++ ...cCollection.cs => StacCollection.Model.cs} | 2 +- 8 files changed, 703 insertions(+), 1 deletion(-) create mode 100644 src/DotNetStac.Test/PriorityOrderer.cs create mode 100644 src/DotNetStac.Test/Resources/UseCases/Sentinel2/catalog.json create mode 100644 src/DotNetStac.Test/Resources/UseCases/Sentinel2/sentinel-2-l1c/catalog.json create mode 100644 src/DotNetStac.Test/TestPriorityAttribute.cs create mode 100644 src/DotNetStac.Test/UseCases/Sentinel2.cs create mode 100644 src/DotNetStac/Catalog/StacCollection.Helper.cs rename src/DotNetStac/Catalog/{StacCollection.cs => StacCollection.Model.cs} (98%) diff --git a/src/DotNetStac.Test/PriorityOrderer.cs b/src/DotNetStac.Test/PriorityOrderer.cs new file mode 100644 index 00000000..2d6d92a4 --- /dev/null +++ b/src/DotNetStac.Test/PriorityOrderer.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit.Abstractions; +using Xunit.Sdk; + +namespace Stac.Test +{ + public class PriorityOrderer : ITestCaseOrderer +{ + public IEnumerable OrderTestCases(IEnumerable testCases) where TTestCase : ITestCase + { + var sortedMethods = new SortedDictionary>(); + + foreach (TTestCase testCase in testCases) + { + int priority = 0; + + foreach (IAttributeInfo attr in testCase.TestMethod.Method.GetCustomAttributes((typeof(TestPriorityAttribute).AssemblyQualifiedName))) + priority = attr.GetNamedArgument("Priority"); + + GetOrCreate(sortedMethods, priority).Add(testCase); + } + + foreach (var list in sortedMethods.Keys.Select(priority => sortedMethods[priority])) + { + list.Sort((x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.TestMethod.Method.Name, y.TestMethod.Method.Name)); + foreach (TTestCase testCase in list) yield return testCase; + + } + } + + static TValue GetOrCreate(IDictionary dictionary, TKey key) + where TValue : new() + { + TValue result; + + if (dictionary.TryGetValue(key, out result)) return result; + + result = new TValue(); + dictionary[key] = result; + + return result; + } +} +} diff --git a/src/DotNetStac.Test/Resources/UseCases/Sentinel2/catalog.json b/src/DotNetStac.Test/Resources/UseCases/Sentinel2/catalog.json new file mode 100644 index 00000000..77314207 --- /dev/null +++ b/src/DotNetStac.Test/Resources/UseCases/Sentinel2/catalog.json @@ -0,0 +1,19 @@ +{ + "id": "sentinel-stac", + "stac_version": "0.6.0", + "description": "STAC for Sentinel data", + "links": [ + { + "rel": "self", + "href": "https://sentinel-stac.s3.amazonaws.com/catalog.json" + }, + { + "rel": "root", + "href": "./catalog.json" + }, + { + "rel": "child", + "href": "sentinel-2-l1c/catalog.json" + } + ] +} \ No newline at end of file diff --git a/src/DotNetStac.Test/Resources/UseCases/Sentinel2/sentinel-2-l1c/catalog.json b/src/DotNetStac.Test/Resources/UseCases/Sentinel2/sentinel-2-l1c/catalog.json new file mode 100644 index 00000000..f0e74b74 --- /dev/null +++ b/src/DotNetStac.Test/Resources/UseCases/Sentinel2/sentinel-2-l1c/catalog.json @@ -0,0 +1,524 @@ +{ + "id": "sentinel-2-l1c", + "title": "Sentinel 2 L1C", + "description": "Sentinel-2a and Sentinel-2b imagery", + "keywords": [ + "sentinel", + "earth observation", + "esa" + ], + "version": "0.1.0", + "stac_version": "0.6.0", + "extent": { + "spatial": { + "bbox": [ + [ + -180, + -90, + 180, + 90 + ] + ] + }, + "temporal": { + "interval": [[ + "2013-06-01", + null + ]] + } + }, + "providers": [ + { + "name": "ESA", + "roles": [ + "producer" + ], + "url": "https://earth.esa.int/web/guest/home" + }, + { + "name": "Synergise", + "roles": [ + "processor" + ], + "url": "https://registry.opendata.aws/sentinel-2/" + }, + { + "name": "AWS", + "roles": [ + "host" + ], + "url": "http://sentinel-pds.s3-website.eu-central-1.amazonaws.com/" + }, + { + "name": "Development Seed", + "roles": [ + "processor" + ], + "url": "https://github.com/sat-utils/sat-stac-sentinel" + } + ], + "license": "proprietary", + "properties": { + "collection": "sentinel-2-l1c", + "eo:gsd": 10, + "eo:instrument": "MSI", + "eo:off_nadir": 0, + "eo:bands": [ + { + "name": "B01", + "common_name": "coastal", + "gsd": 60.0, + "center_wavelength": 0.4439, + "full_width_half_max": 0.027 + }, + { + "name": "B02", + "common_name": "blue", + "gsd": 10.0, + "center_wavelength": 0.4966, + "full_width_half_max": 0.098 + }, + { + "name": "B03", + "common_name": "green", + "gsd": 10.0, + "center_wavelength": 0.56, + "full_width_half_max": 0.045 + }, + { + "name": "B04", + "common_name": "red", + "gsd": 10.0, + "center_wavelength": 0.6645, + "full_width_half_max": 0.038 + }, + { + "name": "B05", + "gsd": 20.0, + "center_wavelength": 0.7039, + "full_width_half_max": 0.019 + }, + { + "name": "B06", + "gsd": 20.0, + "center_wavelength": 0.7402, + "full_width_half_max": 0.018 + }, + { + "name": "B07", + "gsd": 20.0, + "center_wavelength": 0.7825, + "full_width_half_max": 0.028 + }, + { + "name": "B08", + "common_name": "nir", + "gsd": 10.0, + "center_wavelength": 0.8351, + "full_width_half_max": 0.145 + }, + { + "name": "B8A", + "gsd": 20.0, + "center_wavelength": 0.8648, + "full_width_half_max": 0.033 + }, + { + "name": "B09", + "gsd": 60.0, + "center_wavelength": 0.945, + "full_width_half_max": 0.026 + }, + { + "name": "B10", + "common_name": "cirrus", + "gsd": 60.0, + "center_wavelength": 1.3735, + "full_width_half_max": 0.075 + }, + { + "name": "B11", + "common_name": "swir16", + "gsd": 20.0, + "center_wavelength": 1.6137, + "full_width_half_max": 0.143 + }, + { + "name": "B12", + "common_name": "swir22", + "gsd": 20.0, + "center_wavelength": 2.22024, + "full_width_half_max": 0.242 + } + ] + }, + "assets": { + "thumbnail": { + "title": "Thumbnail" + }, + "info": { + "title": "Basic JSON metadata" + }, + "metadata": { + "title": "Complete XML metadata" + }, + "tki": { + "title": "True color image", + "type": "image/jp2", + "eo:bands": [ + 3, + 2, + 1 + ] + }, + "B01": { + "title": "Band 1 (coastal)", + "type": "image/jp2", + "eo:bands": [ + 0 + ] + }, + "B02": { + "title": "Band 2 (blue)", + "type": "image/jp2", + "eo:bands": [ + 2 + ] + }, + "B03": { + "title": "Band 3 (green)", + "type": "image/jp2", + "eo:bands": [ + 2 + ] + }, + "B04": { + "title": "Band 4 (red)", + "type": "image/jp2", + "eo:bands": [ + 3 + ] + }, + "B05": { + "title": "Band 5", + "type": "image/jp2", + "eo:bands": [ + 4 + ] + }, + "B06": { + "title": "Band 6", + "type": "image/jp2", + "eo:bands": [ + 5 + ] + }, + "B07": { + "title": "Band 7", + "type": "image/jp2", + "eo:bands": [ + 6 + ] + }, + "B08": { + "title": "Band 8 (nir)", + "type": "image/jp2", + "eo:bands": [ + 7 + ] + }, + "B8A": { + "title": "Band 8A", + "type": "image/jp2", + "eo:bands": [ + 8 + ] + }, + "B09": { + "title": "Band 9", + "type": "image/jp2", + "eo:bands": [ + 9 + ] + }, + "B10": { + "title": "Band 10 (cirrus)", + "type": "image/jp2", + "eo:bands": [ + 10 + ] + }, + "B11": { + "title": "Band 11 (swir16)", + "type": "image/jp2", + "eo:bands": [ + 11 + ] + }, + "B12": { + "title": "Band 12 (swir22)", + "type": "image/jp2", + "eo:bands": [ + 12 + ] + } + }, + "links": [ + { + "rel": "license", + "href": "https://sentinel.esa.int/documents/247904/690755/Sentinel_Data_Legal_Notice" + }, + { + "rel": "self", + "href": "https://sentinel-stac.s3.amazonaws.com/sentinel-2-l1c/catalog.json" + }, + { + "rel": "root", + "href": "../catalog.json" + }, + { + "rel": "parent", + "href": "../catalog.json" + }, + { + "rel": "child", + "href": "9/catalog.json" + }, + { + "rel": "child", + "href": "47/catalog.json" + }, + { + "rel": "child", + "href": "2/catalog.json" + }, + { + "rel": "child", + "href": "42/catalog.json" + }, + { + "rel": "child", + "href": "35/catalog.json" + }, + { + "rel": "child", + "href": "55/catalog.json" + }, + { + "rel": "child", + "href": "33/catalog.json" + }, + { + "rel": "child", + "href": "7/catalog.json" + }, + { + "rel": "child", + "href": "51/catalog.json" + }, + { + "rel": "child", + "href": "39/catalog.json" + }, + { + "rel": "child", + "href": "30/catalog.json" + }, + { + "rel": "child", + "href": "41/catalog.json" + }, + { + "rel": "child", + "href": "23/catalog.json" + }, + { + "rel": "child", + "href": "6/catalog.json" + }, + { + "rel": "child", + "href": "40/catalog.json" + }, + { + "rel": "child", + "href": "53/catalog.json" + }, + { + "rel": "child", + "href": "60/catalog.json" + }, + { + "rel": "child", + "href": "16/catalog.json" + }, + { + "rel": "child", + "href": "50/catalog.json" + }, + { + "rel": "child", + "href": "27/catalog.json" + }, + { + "rel": "child", + "href": "19/catalog.json" + }, + { + "rel": "child", + "href": "12/catalog.json" + }, + { + "rel": "child", + "href": "32/catalog.json" + }, + { + "rel": "child", + "href": "37/catalog.json" + }, + { + "rel": "child", + "href": "11/catalog.json" + }, + { + "rel": "child", + "href": "54/catalog.json" + }, + { + "rel": "child", + "href": "29/catalog.json" + }, + { + "rel": "child", + "href": "24/catalog.json" + }, + { + "rel": "child", + "href": "49/catalog.json" + }, + { + "rel": "child", + "href": "5/catalog.json" + }, + { + "rel": "child", + "href": "34/catalog.json" + }, + { + "rel": "child", + "href": "13/catalog.json" + }, + { + "rel": "child", + "href": "59/catalog.json" + }, + { + "rel": "child", + "href": "57/catalog.json" + }, + { + "rel": "child", + "href": "20/catalog.json" + }, + { + "rel": "child", + "href": "4/catalog.json" + }, + { + "rel": "child", + "href": "46/catalog.json" + }, + { + "rel": "child", + "href": "45/catalog.json" + }, + { + "rel": "child", + "href": "21/catalog.json" + }, + { + "rel": "child", + "href": "18/catalog.json" + }, + { + "rel": "child", + "href": "31/catalog.json" + }, + { + "rel": "child", + "href": "17/catalog.json" + }, + { + "rel": "child", + "href": "3/catalog.json" + }, + { + "rel": "child", + "href": "36/catalog.json" + }, + { + "rel": "child", + "href": "14/catalog.json" + }, + { + "rel": "child", + "href": "38/catalog.json" + }, + { + "rel": "child", + "href": "25/catalog.json" + }, + { + "rel": "child", + "href": "58/catalog.json" + }, + { + "rel": "child", + "href": "22/catalog.json" + }, + { + "rel": "child", + "href": "43/catalog.json" + }, + { + "rel": "child", + "href": "44/catalog.json" + }, + { + "rel": "child", + "href": "1/catalog.json" + }, + { + "rel": "child", + "href": "28/catalog.json" + }, + { + "rel": "child", + "href": "15/catalog.json" + }, + { + "rel": "child", + "href": "48/catalog.json" + }, + { + "rel": "child", + "href": "8/catalog.json" + }, + { + "rel": "child", + "href": "56/catalog.json" + }, + { + "rel": "child", + "href": "10/catalog.json" + }, + { + "rel": "child", + "href": "52/catalog.json" + }, + { + "rel": "child", + "href": "26/catalog.json" + } + ] +} \ No newline at end of file diff --git a/src/DotNetStac.Test/TestBase.cs b/src/DotNetStac.Test/TestBase.cs index c4f80647..2633b89a 100644 --- a/src/DotNetStac.Test/TestBase.cs +++ b/src/DotNetStac.Test/TestBase.cs @@ -37,5 +37,18 @@ protected string GetExpectedJson(string folder, [CallerMemberName] string name = return File.ReadAllText(path); } + + protected Uri GetUseCaseFileUri(string name) + { + var type = GetType().Name; + var path = Path.Combine(AssemblyDirectory, @"../../..", "Resources/UseCases", type, name); + + if (!File.Exists(path)) + { + throw new FileNotFoundException("file not found at " + path); + } + + return new Uri(path); + } } } \ No newline at end of file diff --git a/src/DotNetStac.Test/TestPriorityAttribute.cs b/src/DotNetStac.Test/TestPriorityAttribute.cs new file mode 100644 index 00000000..ea193020 --- /dev/null +++ b/src/DotNetStac.Test/TestPriorityAttribute.cs @@ -0,0 +1,15 @@ +using System; + +namespace Stac.Test +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class TestPriorityAttribute : Attribute + { + public TestPriorityAttribute(int priority) + { + Priority = priority; + } + + public int Priority { get; private set; } + } +} diff --git a/src/DotNetStac.Test/UseCases/Sentinel2.cs b/src/DotNetStac.Test/UseCases/Sentinel2.cs new file mode 100644 index 00000000..5f80cee8 --- /dev/null +++ b/src/DotNetStac.Test/UseCases/Sentinel2.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Stac.Catalog; +using Stac.Collection; +using Stac.Test; +using Xunit; + +namespace Stac.Test.UseCases +{ + [TestCaseOrderer("DotNetStac.Test.PriorityOrderer", "Sentinel2UseCase")] + public class Sentinel2 : TestBase + { + [Fact, TestPriority(1)] + public void LoadRootCatalog() + { + var catalog = StacCatalog.LoadUri(GetUseCaseFileUri("catalog.json")).Result; + + Assert.NotNull(catalog); + Assert.IsType(catalog); + Assert.Equal("sentinel-stac", catalog.Id); + + IDictionary children = catalog.GetChildren(); + + Assert.Equal(1, children.Count); + + Assert.IsType(children.First().Value); + + } + + + } +} diff --git a/src/DotNetStac/Catalog/StacCollection.Helper.cs b/src/DotNetStac/Catalog/StacCollection.Helper.cs new file mode 100644 index 00000000..d3bb2139 --- /dev/null +++ b/src/DotNetStac/Catalog/StacCollection.Helper.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Runtime.Serialization; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac.Collection; + +namespace Stac.Catalog +{ + public partial class StacCatalog : IStacObject + { + private Uri sourceUri; + + public static async Task LoadUri(Uri uri) + { + WebClient client = new WebClient(); + + return await client.DownloadStringTaskAsync(uri).ContinueWith(json => { + JToken jsonRoot = JsonConvert.DeserializeObject(json.Result); + StacCatalog catalog = null; + if ( jsonRoot["extent"] != null ) + catalog = jsonRoot.ToObject(); + else + catalog = jsonRoot.ToObject(); + catalog.sourceUri = uri; + return catalog; + }); + } + + protected async Task LoadUriRelatively(Uri uri) + { + if (uri.IsAbsoluteUri) + return await StacCatalog.LoadUri(uri); + + return await StacCatalog.LoadUri(new Uri(new Uri(sourceUri.AbsoluteUri.Substring(0, sourceUri.AbsoluteUri.LastIndexOf('/') + 1 )), uri)); + } + + public IDictionary GetChildren() + { + return GetChildrenAsync().ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Result); + } + + public IDictionary> GetChildrenAsync() + { + return Links.Where(l => l.RelationshipType == "child").ToDictionary(link => link.Uri, link => LoadUriRelatively(link.Uri)); + } + } +} diff --git a/src/DotNetStac/Catalog/StacCollection.cs b/src/DotNetStac/Catalog/StacCollection.Model.cs similarity index 98% rename from src/DotNetStac/Catalog/StacCollection.cs rename to src/DotNetStac/Catalog/StacCollection.Model.cs index 0f12a91f..0bd487cd 100644 --- a/src/DotNetStac/Catalog/StacCollection.cs +++ b/src/DotNetStac/Catalog/StacCollection.Model.cs @@ -12,7 +12,7 @@ namespace Stac.Catalog { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public class StacCatalog : IStacObject + public partial class StacCatalog : IStacObject { private readonly string id; private Collection links; From 72a479061070407bd3790c794d34510c9401d30d Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Thu, 25 Jun 2020 22:52:58 +0200 Subject: [PATCH 14/21] tests working with prio --- src/DotNetStac.Test/UseCases/Sentinel2.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/DotNetStac.Test/UseCases/Sentinel2.cs b/src/DotNetStac.Test/UseCases/Sentinel2.cs index 5f80cee8..ff8650b2 100644 --- a/src/DotNetStac.Test/UseCases/Sentinel2.cs +++ b/src/DotNetStac.Test/UseCases/Sentinel2.cs @@ -8,24 +8,30 @@ namespace Stac.Test.UseCases { - [TestCaseOrderer("DotNetStac.Test.PriorityOrderer", "Sentinel2UseCase")] + [TestCaseOrderer("Stac.Test.PriorityOrderer", "DotNetStac.Test")] public class Sentinel2 : TestBase { + private static StacCatalog catalog; + [Fact, TestPriority(1)] public void LoadRootCatalog() { - var catalog = StacCatalog.LoadUri(GetUseCaseFileUri("catalog.json")).Result; + catalog = StacCatalog.LoadUri(GetUseCaseFileUri("catalog.json")).Result; Assert.NotNull(catalog); Assert.IsType(catalog); Assert.Equal("sentinel-stac", catalog.Id); + } + + [Fact, TestPriority(2)] + public void LoadRootChildren() + { IDictionary children = catalog.GetChildren(); Assert.Equal(1, children.Count); Assert.IsType(children.First().Value); - } From e4de99755a0e165b3b7916b5a52a5a25ee6711fe Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Sun, 28 Jun 2020 23:21:57 +0200 Subject: [PATCH 15/21] versioning management --- .../Sentinel2/sentinel-2-l1c/catalog.json | 26 ++-- src/DotNetStac/Catalog/StacCatalog.Helper.cs | 85 ++++++++++ ...llection.Model.cs => StacCatalog.Model.cs} | 30 ++-- .../Catalog/StacCollection.Helper.cs | 52 ------- .../Collection/StacCollection.Helper.cs | 51 ++++++ ...cCollection.cs => StacCollection.Model.cs} | 26 +++- .../Model/IStacCatalogModelVersion.cs | 7 + .../Model/IStacCollectionModelVersion.cs | 7 + src/DotNetStac/Model/SchemaDictionary.cs | 41 +++++ src/DotNetStac/Model/v060/StacCatalog.cs | 114 ++++++++++++++ src/DotNetStac/Model/v060/StacCollection.cs | 81 ++++++++++ src/DotNetStac/Model/v060/StacExtent.cs | 23 +++ src/DotNetStac/Model/v060/StacItem.cs | 146 ++++++++++++++++++ src/DotNetStac/Model/v070/StacCatalog.cs | 118 ++++++++++++++ src/DotNetStac/Model/v070/StacCollection.cs | 83 ++++++++++ src/DotNetStac/Model/v070/StacItem.cs | 146 ++++++++++++++++++ 16 files changed, 948 insertions(+), 88 deletions(-) create mode 100644 src/DotNetStac/Catalog/StacCatalog.Helper.cs rename src/DotNetStac/Catalog/{StacCollection.Model.cs => StacCatalog.Model.cs} (82%) delete mode 100644 src/DotNetStac/Catalog/StacCollection.Helper.cs create mode 100644 src/DotNetStac/Collection/StacCollection.Helper.cs rename src/DotNetStac/Collection/{StacCollection.cs => StacCollection.Model.cs} (70%) create mode 100644 src/DotNetStac/Model/IStacCatalogModelVersion.cs create mode 100644 src/DotNetStac/Model/IStacCollectionModelVersion.cs create mode 100644 src/DotNetStac/Model/SchemaDictionary.cs create mode 100644 src/DotNetStac/Model/v060/StacCatalog.cs create mode 100644 src/DotNetStac/Model/v060/StacCollection.cs create mode 100644 src/DotNetStac/Model/v060/StacExtent.cs create mode 100644 src/DotNetStac/Model/v060/StacItem.cs create mode 100644 src/DotNetStac/Model/v070/StacCatalog.cs create mode 100644 src/DotNetStac/Model/v070/StacCollection.cs create mode 100644 src/DotNetStac/Model/v070/StacItem.cs diff --git a/src/DotNetStac.Test/Resources/UseCases/Sentinel2/sentinel-2-l1c/catalog.json b/src/DotNetStac.Test/Resources/UseCases/Sentinel2/sentinel-2-l1c/catalog.json index f0e74b74..09088856 100644 --- a/src/DotNetStac.Test/Resources/UseCases/Sentinel2/sentinel-2-l1c/catalog.json +++ b/src/DotNetStac.Test/Resources/UseCases/Sentinel2/sentinel-2-l1c/catalog.json @@ -10,22 +10,16 @@ "version": "0.1.0", "stac_version": "0.6.0", "extent": { - "spatial": { - "bbox": [ - [ - -180, - -90, - 180, - 90 - ] - ] - }, - "temporal": { - "interval": [[ - "2013-06-01", - null - ]] - } + "spatial": [ + -180, + -90, + 180, + 90 + ], + "temporal": [ + "2013-06-01", + null + ], }, "providers": [ { diff --git a/src/DotNetStac/Catalog/StacCatalog.Helper.cs b/src/DotNetStac/Catalog/StacCatalog.Helper.cs new file mode 100644 index 00000000..21973650 --- /dev/null +++ b/src/DotNetStac/Catalog/StacCatalog.Helper.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Runtime.Serialization; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac.Collection; +using Stac.Model; + +namespace Stac.Catalog +{ + public partial class StacCatalog : IStacObject + { + private Uri sourceUri; + + + + public static async Task LoadUri(Uri uri) + { + WebClient client = new WebClient(); + + return await client.DownloadStringTaskAsync(uri).ContinueWith(json => LoadJsonToken(JsonConvert.DeserializeObject(json.Result), uri)); + } + + private static StacCatalog LoadJsonToken(JToken jsonRoot, Uri uri) + { + StacCatalog catalog; + if (jsonRoot["extent"] != null) + catalog = Stac.Collection.StacCollection.LoadStacCollection(jsonRoot); + else + catalog = LoadStacCatalog(jsonRoot); + catalog.sourceUri = uri; + return catalog; + + } + + private static StacCatalog LoadStacCatalog(JToken jsonRoot) + { + Type catalogType = null; + if (jsonRoot["stac_version"] == null) + { + throw new InvalidDataException("The document is not a STAC document. No 'stac_version' property found"); + } + + try + { + catalogType = Stac.Model.SchemaDictionary.GetCatalogTypeFromVersion(jsonRoot["stac_version"].Value()); + } + catch (KeyNotFoundException) + { + throw new NotSupportedException(string.Format("The document has a non supprted version: '{0}'.", jsonRoot["stac_version"].Value())); + } + + IStacCatalogModelVersion catalog = (IStacCatalogModelVersion)jsonRoot.ToObject(catalogType); + + while (catalog.GetType() != typeof(StacCatalog)) + { + catalog = catalog.Upgrade(); + } + + return (StacCatalog)catalog; + } + + protected async Task LoadUriRelatively(Uri uri) + { + if (uri.IsAbsoluteUri) + return await StacCatalog.LoadUri(uri); + + return await StacCatalog.LoadUri(new Uri(new Uri(sourceUri.AbsoluteUri.Substring(0, sourceUri.AbsoluteUri.LastIndexOf('/') + 1)), uri)); + } + + public IDictionary GetChildren() + { + return GetChildrenAsync().ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Result); + } + + public IDictionary> GetChildrenAsync() + { + return Links.Where(l => l.RelationshipType == "child").ToDictionary(link => link.Uri, link => LoadUriRelatively(link.Uri)); + } + } +} diff --git a/src/DotNetStac/Catalog/StacCollection.Model.cs b/src/DotNetStac/Catalog/StacCatalog.Model.cs similarity index 82% rename from src/DotNetStac/Catalog/StacCollection.Model.cs rename to src/DotNetStac/Catalog/StacCatalog.Model.cs index 0bd487cd..4ce0fb38 100644 --- a/src/DotNetStac/Catalog/StacCollection.Model.cs +++ b/src/DotNetStac/Catalog/StacCatalog.Model.cs @@ -8,11 +8,12 @@ using Newtonsoft.Json; using Stac.Converters; using Stac.Extensions; +using Stac.Model; namespace Stac.Catalog { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public partial class StacCatalog : IStacObject + public partial class StacCatalog : IStacObject, Model.IStacCatalogModelVersion { private readonly string id; private Collection links; @@ -22,16 +23,18 @@ public partial class StacCatalog : IStacObject private Collection extensions; private string description; - private Collection keywords; + private string title; + + [JsonConstructor] public StacCatalog(string id, string description, IEnumerable links = null) { this.id = id; this.description = description; - if ( links == null ) + if (links == null) this.links = new Collection(); else this.links = new Collection(links.ToList()); @@ -83,21 +86,6 @@ public Collection Links } } - [JsonProperty("keywords", DefaultValueHandling = DefaultValueHandling.Ignore)] - public Collection Keywords - { - get - { - if (keywords == null) - keywords = new Collection(); - return keywords; - } - set - { - keywords = value; - } - } - [JsonProperty("description")] public string Description { @@ -115,5 +103,11 @@ public string Description public string Id => id; public string Title { get => title; set => title = value; } + + public IStacCatalogModelVersion Upgrade() + { + return this; + } + } } diff --git a/src/DotNetStac/Catalog/StacCollection.Helper.cs b/src/DotNetStac/Catalog/StacCollection.Helper.cs deleted file mode 100644 index d3bb2139..00000000 --- a/src/DotNetStac/Catalog/StacCollection.Helper.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Runtime.Serialization; -using System.Threading.Tasks; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Stac.Collection; - -namespace Stac.Catalog -{ - public partial class StacCatalog : IStacObject - { - private Uri sourceUri; - - public static async Task LoadUri(Uri uri) - { - WebClient client = new WebClient(); - - return await client.DownloadStringTaskAsync(uri).ContinueWith(json => { - JToken jsonRoot = JsonConvert.DeserializeObject(json.Result); - StacCatalog catalog = null; - if ( jsonRoot["extent"] != null ) - catalog = jsonRoot.ToObject(); - else - catalog = jsonRoot.ToObject(); - catalog.sourceUri = uri; - return catalog; - }); - } - - protected async Task LoadUriRelatively(Uri uri) - { - if (uri.IsAbsoluteUri) - return await StacCatalog.LoadUri(uri); - - return await StacCatalog.LoadUri(new Uri(new Uri(sourceUri.AbsoluteUri.Substring(0, sourceUri.AbsoluteUri.LastIndexOf('/') + 1 )), uri)); - } - - public IDictionary GetChildren() - { - return GetChildrenAsync().ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Result); - } - - public IDictionary> GetChildrenAsync() - { - return Links.Where(l => l.RelationshipType == "child").ToDictionary(link => link.Uri, link => LoadUriRelatively(link.Uri)); - } - } -} diff --git a/src/DotNetStac/Collection/StacCollection.Helper.cs b/src/DotNetStac/Collection/StacCollection.Helper.cs new file mode 100644 index 00000000..535be99d --- /dev/null +++ b/src/DotNetStac/Collection/StacCollection.Helper.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Runtime.Serialization; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac.Catalog; +using Stac.Collection; +using Stac.Model; + +namespace Stac.Collection +{ + public partial class StacCollection : IStacObject + { + internal static StacCollection LoadStacCollection(JToken jsonRoot) + { + Type collectionType = null; + if (jsonRoot["stac_version"] == null) + { + throw new InvalidDataException("The document is not a STAC document. No 'stac_version' property found"); + } + + if (jsonRoot["extent"] == null) + { + throw new InvalidDataException("The document is not a STAC collection document. No 'extent' property found. Probably a catalog."); + } + + try + { + collectionType = Stac.Model.SchemaDictionary.GetCollectionTypeFromVersion(jsonRoot["stac_version"].Value()); + } + catch (KeyNotFoundException) + { + throw new NotSupportedException(string.Format("The document has a non supprted version: '{0}'.", jsonRoot["stac_version"].Value())); + } + + IStacCollectionModelVersion catalog = (IStacCollectionModelVersion)jsonRoot.ToObject(collectionType); + + while (catalog.GetType() != typeof(StacCollection)) + { + catalog = catalog.Upgrade(); + } + + return (StacCollection)catalog; + } + + } +} diff --git a/src/DotNetStac/Collection/StacCollection.cs b/src/DotNetStac/Collection/StacCollection.Model.cs similarity index 70% rename from src/DotNetStac/Collection/StacCollection.cs rename to src/DotNetStac/Collection/StacCollection.Model.cs index 4f57e61b..77a44663 100644 --- a/src/DotNetStac/Collection/StacCollection.cs +++ b/src/DotNetStac/Collection/StacCollection.Model.cs @@ -9,17 +9,18 @@ using Stac.Catalog; using Stac.Converters; using Stac.Extensions; +using Stac.Model; namespace Stac.Collection { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public class StacCollection : StacCatalog, IStacObject + public partial class StacCollection : StacCatalog, IStacObject, Model.IStacCollectionModelVersion { private string license; private StacExtent extent; private Dictionary summaries; - private Collection providers; + private Collection keywords; [JsonConstructor] public StacCollection(string id, string description, StacExtent extent, IEnumerable links = null, string license = "proprietary") : @@ -58,5 +59,26 @@ public Collection Providers providers = value; } } + + [JsonProperty("keywords", DefaultValueHandling = DefaultValueHandling.Ignore)] + public Collection Keywords + { + get + { + if (keywords == null) + keywords = new Collection(); + return keywords; + } + set + { + keywords = value; + } + } + + + IStacCollectionModelVersion IStacCollectionModelVersion.Upgrade() + { + return this; + } } } diff --git a/src/DotNetStac/Model/IStacCatalogModelVersion.cs b/src/DotNetStac/Model/IStacCatalogModelVersion.cs new file mode 100644 index 00000000..2f7c3dc4 --- /dev/null +++ b/src/DotNetStac/Model/IStacCatalogModelVersion.cs @@ -0,0 +1,7 @@ +namespace Stac.Model +{ + public interface IStacCatalogModelVersion + { + IStacCatalogModelVersion Upgrade(); + } +} \ No newline at end of file diff --git a/src/DotNetStac/Model/IStacCollectionModelVersion.cs b/src/DotNetStac/Model/IStacCollectionModelVersion.cs new file mode 100644 index 00000000..0d7a7124 --- /dev/null +++ b/src/DotNetStac/Model/IStacCollectionModelVersion.cs @@ -0,0 +1,7 @@ +namespace Stac.Model +{ + internal interface IStacCollectionModelVersion + { + IStacCollectionModelVersion Upgrade(); + } +} \ No newline at end of file diff --git a/src/DotNetStac/Model/SchemaDictionary.cs b/src/DotNetStac/Model/SchemaDictionary.cs new file mode 100644 index 00000000..d95b18ba --- /dev/null +++ b/src/DotNetStac/Model/SchemaDictionary.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Linq; + +namespace Stac.Model +{ + + public static class SchemaDictionary + { + private static Dictionary catalogVersionDictionary = new Dictionary() + { + { "0.6.0", typeof(Stac.Model.v060.StacCatalog060) }, + { "0.7.0", typeof(Stac.Model.v070.StacCatalog070) }, + { "1.0.0-beta.1", typeof(Stac.Catalog.StacCatalog) } + }; + + private static Dictionary collectionVersionDictionary = new Dictionary() + { + { "0.6.0", typeof(Stac.Model.v060.StacCollection060) }, + { "0.7.0", typeof(Stac.Model.v070.StacCollection070) }, + { "1.0.0-beta.1", typeof(Stac.Collection.StacCollection) } + }; + + private static Dictionary itemVersionDictionary = new Dictionary() + { + { "0.6.0", typeof(Stac.Model.v060.StacItem060) }, + { "0.7.0", typeof(Stac.Model.v070.StacItem070) }, + { "1.0.0-beta.1", typeof(Stac.Item.StacItem) } + }; + + internal static Type GetCatalogTypeFromVersion(string version) + { + return catalogVersionDictionary[version]; + } + + internal static Type GetCollectionTypeFromVersion(string version) + { + return collectionVersionDictionary[version]; + } + } +} \ No newline at end of file diff --git a/src/DotNetStac/Model/v060/StacCatalog.cs b/src/DotNetStac/Model/v060/StacCatalog.cs new file mode 100644 index 00000000..199bc0a6 --- /dev/null +++ b/src/DotNetStac/Model/v060/StacCatalog.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using DotNetStac; +using DotNetStac.Converters; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Stac.Converters; +using Stac.Extensions; + +namespace Stac.Model.v060 +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + internal class StacCatalog060 : IStacObject, IStacCatalogModelVersion + { + private readonly string id; + private Collection links; + + private string stacVersion = StacVersionList.Current; + + private Collection extensions; + + private string description; + + + private string title; + + [JsonConstructor] + public StacCatalog060(string id, string description, IEnumerable links = null) + { + this.id = id; + this.description = description; + if ( links == null ) + this.links = new Collection(); + else + this.links = new Collection(links.ToList()); + } + + [JsonProperty("stac_extensions")] + [JsonConverter(typeof(StacExtensionConverter))] + public Collection StacExtensions + { + get + { + if (extensions == null) + extensions = new Collection(); + return extensions; + } + set + { + extensions = value; + } + } + + [JsonProperty("stac_version")] + public string StacVersion + { + get + { + return stacVersion; + } + + set + { + stacVersion = value; + } + } + + [JsonConverter(typeof(CollectionConverter))] + [JsonProperty("links")] + public Collection Links + { + get + { + if (links == null) + links = new Collection(); + return links; + } + set + { + links = value; + } + } + + [JsonProperty("description")] + public string Description + { + get + { + return description; + } + set + { + description = value; + } + } + + [JsonProperty("id")] + public string Id => id; + + public string Title { get => title; set => title = value; } + + public IStacCatalogModelVersion Upgrade() + { + var catalog = new v070.StacCatalog070(this.Id, + this.Description, + this.Links); + catalog.StacExtensions = this.StacExtensions; + catalog.Title = this.Title; + return catalog; + } + } +} diff --git a/src/DotNetStac/Model/v060/StacCollection.cs b/src/DotNetStac/Model/v060/StacCollection.cs new file mode 100644 index 00000000..96f94d3c --- /dev/null +++ b/src/DotNetStac/Model/v060/StacCollection.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using DotNetStac; +using DotNetStac.Converters; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac.Catalog; +using Stac.Converters; +using Stac.Extensions; + +namespace Stac.Model.v060 +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + internal class StacCollection060 : StacCatalog060, IStacObject, IStacCollectionModelVersion + { + private string license; + private StacExtent060 extent; + private Dictionary summaries; + private Collection providers; + private Collection keywords; + + [JsonConstructor] + public StacCollection060(string id, string description, StacExtent060 extent, IEnumerable links = null, string license = "proprietary") : + base(id, description, links) + { + this.license = license; + this.extent = extent; + } + + [JsonProperty("extent")] + public StacExtent060 Extent { get => extent; set => extent = value; } + + [JsonProperty("license")] + public string License { get => license; set => license = value; } + + [JsonProperty("providers")] + public Collection Providers + { + get { return providers; } + set + { + providers = value; + } + } + + [JsonProperty("keywords", DefaultValueHandling = DefaultValueHandling.Ignore)] + public Collection Keywords + { + get + { + if (keywords == null) + keywords = new Collection(); + return keywords; + } + set + { + keywords = value; + } + } + + [JsonExtensionData] + public Dictionary Properties { get; set; } + + IStacCollectionModelVersion IStacCollectionModelVersion.Upgrade() + { + var collection = new v070.StacCollection070(this.Id, + this.Description, + this.Extent, + this.Links); + collection.StacExtensions = this.StacExtensions; + collection.Title = this.Title; + collection.Keywords = this.Keywords; + collection.License = this.License; + collection.Providers = this.Providers; + return collection; + } + } +} diff --git a/src/DotNetStac/Model/v060/StacExtent.cs b/src/DotNetStac/Model/v060/StacExtent.cs new file mode 100644 index 00000000..dcb7c111 --- /dev/null +++ b/src/DotNetStac/Model/v060/StacExtent.cs @@ -0,0 +1,23 @@ +using System; +using Newtonsoft.Json; + +namespace Stac.Model.v060 +{ + [JsonObject] + internal class StacExtent060 + { + [JsonProperty("spatial")] + public double[] Spatial { get; set; } + + [JsonProperty("temporal")] + public DateTime?[] Temporal { get; set; } + + internal StacExtent Upgrade() + { + return new StacExtent(){ + Spatial = new StacSpatialExtent(this.Spatial[0], this.Spatial[1], this.Spatial[2], this.Spatial[3]), + Temporal = new StacTemporalExtent(this.Temporal[0], this.Temporal[1]) + }; + } + } +} \ No newline at end of file diff --git a/src/DotNetStac/Model/v060/StacItem.cs b/src/DotNetStac/Model/v060/StacItem.cs new file mode 100644 index 00000000..b875c844 --- /dev/null +++ b/src/DotNetStac/Model/v060/StacItem.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using DotNetStac; +using DotNetStac.Converters; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Stac.Converters; +using Stac.Extensions; + +namespace Stac.Model.v060 +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + internal class StacItem060 : GeoJSON.Net.Feature.Feature, IStacObject + { + private Collection links; + + private Dictionary assets; + + private string stacVersion = StacVersionList.Current; + + private Collection extensions; + private string collection; + + [JsonConstructor] + public StacItem060(IGeometryObject geometry, IDictionary properties = null, string id = null) : base(geometry, properties, id) + { } + + public StacItem060(IGeometryObject geometry, object properties, string id = null) : base(geometry, properties, id) + { } + + [JsonProperty("stac_extensions")] + [JsonConverter(typeof(StacExtensionConverter))] + public Collection StacExtensions + { + get + { + if (extensions == null) + extensions = new Collection(); + return extensions; + } + set + { + extensions = value; + } + } + + [JsonProperty("stac_version")] + public string StacVersion + { + get + { + return stacVersion; + } + + set + { + stacVersion = value; + } + } + + [JsonConverter(typeof(CollectionConverter))] + [JsonProperty("links")] + public Collection Links + { + get + { + if (links == null) + links = new Collection(); + return links; + } + set + { + links = value; + } + } + + [JsonProperty("assets")] + public Dictionary Assets + { + get + { + if (assets == null) + assets = new Dictionary(); + return assets; + } + } + + [JsonProperty("collection")] + public string Collection + { + get + { + return collection; + } + set + { + collection = value; + } + } + + [JsonIgnore] + public Itenso.TimePeriod.ITimePeriod DateTime + { + get + { + if (Properties.ContainsKey("datetime")) + { + if (Properties["datetime"] is DateTime) + return new Itenso.TimePeriod.TimeInterval((DateTime)Properties["datetime"]); + else + { + try + { + return new Itenso.TimePeriod.TimeInterval(System.DateTime.Parse(Properties["datetime"].ToString())); + } + catch (Exception e) + { + throw new FormatException(string.Format("{0} is not a valid"), e); + } + } + } + if (Properties.ContainsKey("start_datetime") && Properties.ContainsKey("end_datetime")) + { + if (Properties["start_datetime"] is DateTime && Properties["end_datetime"] is DateTime) + return new Itenso.TimePeriod.TimeInterval((DateTime)Properties["start_datetime"], + (DateTime)Properties["end_datetime"]); + else + { + try + { + return new Itenso.TimePeriod.TimeInterval(System.DateTime.Parse(Properties["start_datetime"].ToString()), + System.DateTime.Parse(Properties["end_datetime"].ToString())); + } + catch (Exception e) + { + throw new FormatException(string.Format("{0} is not a valid"), e); + } + } + } + + return null; + } + } + } +} diff --git a/src/DotNetStac/Model/v070/StacCatalog.cs b/src/DotNetStac/Model/v070/StacCatalog.cs new file mode 100644 index 00000000..c2dc0e81 --- /dev/null +++ b/src/DotNetStac/Model/v070/StacCatalog.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using DotNetStac; +using DotNetStac.Converters; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Stac.Converters; +using Stac.Extensions; +using Stac.Model.v060; + +namespace Stac.Model.v070 +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + internal class StacCatalog070 : IStacObject, IStacCatalogModelVersion + { + private readonly string id; + private Collection links; + + private string stacVersion = StacVersionList.Current; + + private Collection extensions; + + private string description; + + + private string title; + + [JsonConstructor] + public StacCatalog070(string id, string description, IEnumerable links = null) + { + this.id = id; + this.description = description; + if (links == null) + this.links = new Collection(); + else + this.links = new Collection(links.ToList()); + } + + [JsonProperty("stac_extensions")] + [JsonConverter(typeof(StacExtensionConverter))] + public Collection StacExtensions + { + get + { + if (extensions == null) + extensions = new Collection(); + return extensions; + } + set + { + extensions = value; + } + } + + [JsonProperty("stac_version")] + public string StacVersion + { + get + { + return stacVersion; + } + + set + { + stacVersion = value; + } + } + + [JsonConverter(typeof(CollectionConverter))] + [JsonProperty("links")] + public Collection Links + { + get + { + if (links == null) + links = new Collection(); + return links; + } + set + { + links = value; + } + } + + + + [JsonProperty("description")] + public string Description + { + get + { + return description; + } + set + { + description = value; + } + } + + [JsonProperty("id")] + public string Id => id; + + public string Title { get => title; set => title = value; } + + public IStacCatalogModelVersion Upgrade() + { + var catalog = new Catalog.StacCatalog(this.Id, + this.Description, + this.Links); + catalog.StacExtensions = this.StacExtensions; + catalog.Title = this.Title; + + return catalog; + } + } +} diff --git a/src/DotNetStac/Model/v070/StacCollection.cs b/src/DotNetStac/Model/v070/StacCollection.cs new file mode 100644 index 00000000..e4271216 --- /dev/null +++ b/src/DotNetStac/Model/v070/StacCollection.cs @@ -0,0 +1,83 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; +using Newtonsoft.Json; +using Stac.Converters; + +namespace Stac.Model.v070 +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + internal class StacCollection070 : StacCatalog070, IStacObject, IStacCollectionModelVersion + { + private string license; + private v060.StacExtent060 extent; + private Dictionary summaries; + private Collection providers; + private Collection keywords; + + [JsonConstructor] + public StacCollection070(string id, string description, v060.StacExtent060 extent, IEnumerable links = null, string license = "proprietary") : + base(id, description, links) + { + this.license = license; + this.extent = extent; + } + + [JsonProperty("extent")] + public Stac.Model.v060.StacExtent060 Extent { get => extent; set => extent = value; } + + [JsonProperty("summaries")] + [JsonConverter(typeof(StacSummariesConverter))] + public Dictionary Summaries + { + get + { + return summaries; + } + set + { + summaries = value; + } + } + + [JsonProperty("license")] + public string License { get => license; set => license = value; } + + [JsonProperty("providers")] + public Collection Providers + { + get { return providers; } + set + { + providers = value; + } + } + + [JsonProperty("keywords", DefaultValueHandling = DefaultValueHandling.Ignore)] + public Collection Keywords + { + get + { + if (keywords == null) + keywords = new Collection(); + return keywords; + } + set + { + keywords = value; + } + } + + IStacCollectionModelVersion IStacCollectionModelVersion.Upgrade() + { + var collection = new Collection.StacCollection(this.Id, + this.Description, this.extent.Upgrade(), this.Links); + collection.StacExtensions = this.StacExtensions; + collection.Title = this.Title; + collection.Keywords = this.Keywords; + collection.License = this.License; + collection.Providers = this.Providers; + collection.Summaries = this.Summaries; + return collection; + } + } +} diff --git a/src/DotNetStac/Model/v070/StacItem.cs b/src/DotNetStac/Model/v070/StacItem.cs new file mode 100644 index 00000000..eeae8ea5 --- /dev/null +++ b/src/DotNetStac/Model/v070/StacItem.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using DotNetStac; +using DotNetStac.Converters; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Stac.Converters; +using Stac.Extensions; + +namespace Stac.Model.v070 +{ + [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] + internal class StacItem070 : GeoJSON.Net.Feature.Feature, IStacObject + { + private Collection links; + + private Dictionary assets; + + private string stacVersion = StacVersionList.Current; + + private Collection extensions; + private string collection; + + [JsonConstructor] + public StacItem070(IGeometryObject geometry, IDictionary properties = null, string id = null) : base(geometry, properties, id) + { } + + public StacItem070(IGeometryObject geometry, object properties, string id = null) : base(geometry, properties, id) + { } + + [JsonProperty("stac_extensions")] + [JsonConverter(typeof(StacExtensionConverter))] + public Collection StacExtensions + { + get + { + if (extensions == null) + extensions = new Collection(); + return extensions; + } + set + { + extensions = value; + } + } + + [JsonProperty("stac_version")] + public string StacVersion + { + get + { + return stacVersion; + } + + set + { + stacVersion = value; + } + } + + [JsonConverter(typeof(CollectionConverter))] + [JsonProperty("links")] + public Collection Links + { + get + { + if (links == null) + links = new Collection(); + return links; + } + set + { + links = value; + } + } + + [JsonProperty("assets")] + public Dictionary Assets + { + get + { + if (assets == null) + assets = new Dictionary(); + return assets; + } + } + + [JsonProperty("collection")] + public string Collection + { + get + { + return collection; + } + set + { + collection = value; + } + } + + [JsonIgnore] + public Itenso.TimePeriod.ITimePeriod DateTime + { + get + { + if (Properties.ContainsKey("datetime")) + { + if (Properties["datetime"] is DateTime) + return new Itenso.TimePeriod.TimeInterval((DateTime)Properties["datetime"]); + else + { + try + { + return new Itenso.TimePeriod.TimeInterval(System.DateTime.Parse(Properties["datetime"].ToString())); + } + catch (Exception e) + { + throw new FormatException(string.Format("{0} is not a valid"), e); + } + } + } + if (Properties.ContainsKey("start_datetime") && Properties.ContainsKey("end_datetime")) + { + if (Properties["start_datetime"] is DateTime && Properties["end_datetime"] is DateTime) + return new Itenso.TimePeriod.TimeInterval((DateTime)Properties["start_datetime"], + (DateTime)Properties["end_datetime"]); + else + { + try + { + return new Itenso.TimePeriod.TimeInterval(System.DateTime.Parse(Properties["start_datetime"].ToString()), + System.DateTime.Parse(Properties["end_datetime"].ToString())); + } + catch (Exception e) + { + throw new FormatException(string.Format("{0} is not a valid"), e); + } + } + } + + return null; + } + } + } +} From 4709c6eb544708a7c81037ab50c3c81a8f1199de Mon Sep 17 00:00:00 2001 From: emmanuelmathot Date: Tue, 30 Jun 2020 15:54:56 +0200 Subject: [PATCH 16/21] some refactoring --- src/DotNetStac.Test/UseCases/Sentinel2.cs | 6 +- src/DotNetStac/Catalog/StacCatalog.Helper.cs | 56 ++++++--------- src/DotNetStac/Catalog/StacCatalog.Model.cs | 34 +++++++-- .../Collection/StacCollection.Helper.cs | 2 +- .../Collection/StacCollection.Model.cs | 4 +- src/DotNetStac/IInternalStacObject.cs | 19 +++++ src/DotNetStac/IStacCatalog.cs | 8 +++ src/DotNetStac/IStacCollection.cs | 8 +++ src/DotNetStac/IStacItem.cs | 13 ++++ src/DotNetStac/IStacObject.cs | 2 + src/DotNetStac/Item/StacItem.Helper.cs | 67 ++++++++++++++++++ .../Item/{StacItem.cs => StacItem.Model.cs} | 28 +++++++- .../Model/IStacCatalogModelVersion.cs | 7 -- src/DotNetStac/Model/IStacCatalogVersion.cs | 7 ++ .../Model/IStacCollectionModelVersion.cs | 7 -- .../Model/IStacCollectionVersion.cs | 7 ++ src/DotNetStac/Model/IStacItemVersion.cs | 10 +++ src/DotNetStac/Model/SchemaDictionary.cs | 5 ++ src/DotNetStac/Model/v060/StacCatalog.cs | 21 ++++-- src/DotNetStac/Model/v060/StacCollection.cs | 5 +- src/DotNetStac/Model/v060/StacItem.cs | 59 +++++++--------- src/DotNetStac/Model/v070/StacCatalog.cs | 21 ++++-- src/DotNetStac/Model/v070/StacCollection.cs | 4 +- src/DotNetStac/Model/v070/StacItem.cs | 58 +++++++--------- src/DotNetStac/StacAsset.cs | 40 +++++++---- src/DotNetStac/StacExtensionsHelper.cs | 69 +++++++++++++++++++ src/DotNetStac/StacFactory.cs | 42 +++++++++++ src/DotNetStac/StacLink.cs | 32 +++++++++ src/DotNetStac/StacObject.cs | 59 ---------------- src/DotNetStac/StacVersionList.cs | 6 +- 30 files changed, 488 insertions(+), 218 deletions(-) create mode 100644 src/DotNetStac/IInternalStacObject.cs create mode 100644 src/DotNetStac/IStacCatalog.cs create mode 100644 src/DotNetStac/IStacCollection.cs create mode 100644 src/DotNetStac/IStacItem.cs create mode 100644 src/DotNetStac/Item/StacItem.Helper.cs rename src/DotNetStac/Item/{StacItem.cs => StacItem.Model.cs} (86%) delete mode 100644 src/DotNetStac/Model/IStacCatalogModelVersion.cs create mode 100644 src/DotNetStac/Model/IStacCatalogVersion.cs delete mode 100644 src/DotNetStac/Model/IStacCollectionModelVersion.cs create mode 100644 src/DotNetStac/Model/IStacCollectionVersion.cs create mode 100644 src/DotNetStac/Model/IStacItemVersion.cs create mode 100644 src/DotNetStac/StacExtensionsHelper.cs create mode 100644 src/DotNetStac/StacFactory.cs delete mode 100644 src/DotNetStac/StacObject.cs diff --git a/src/DotNetStac.Test/UseCases/Sentinel2.cs b/src/DotNetStac.Test/UseCases/Sentinel2.cs index ff8650b2..b9ce9d81 100644 --- a/src/DotNetStac.Test/UseCases/Sentinel2.cs +++ b/src/DotNetStac.Test/UseCases/Sentinel2.cs @@ -11,7 +11,7 @@ namespace Stac.Test.UseCases [TestCaseOrderer("Stac.Test.PriorityOrderer", "DotNetStac.Test")] public class Sentinel2 : TestBase { - private static StacCatalog catalog; + private static IStacCatalog catalog; [Fact, TestPriority(1)] public void LoadRootCatalog() @@ -19,7 +19,7 @@ public void LoadRootCatalog() catalog = StacCatalog.LoadUri(GetUseCaseFileUri("catalog.json")).Result; Assert.NotNull(catalog); - Assert.IsType(catalog); + Assert.IsAssignableFrom(catalog); Assert.Equal("sentinel-stac", catalog.Id); } @@ -27,7 +27,7 @@ public void LoadRootCatalog() [Fact, TestPriority(2)] public void LoadRootChildren() { - IDictionary children = catalog.GetChildren(); + IDictionary children = catalog.GetChildren(); Assert.Equal(1, children.Count); diff --git a/src/DotNetStac/Catalog/StacCatalog.Helper.cs b/src/DotNetStac/Catalog/StacCatalog.Helper.cs index 21973650..a3c52ebe 100644 --- a/src/DotNetStac/Catalog/StacCatalog.Helper.cs +++ b/src/DotNetStac/Catalog/StacCatalog.Helper.cs @@ -8,36 +8,43 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Stac.Collection; +using Stac.Item; using Stac.Model; namespace Stac.Catalog { - public partial class StacCatalog : IStacObject + public partial class StacCatalog { - private Uri sourceUri; - - - public static async Task LoadUri(Uri uri) + public static async Task LoadUri(Uri uri) { - WebClient client = new WebClient(); + var catalog = await StacFactory.LoadUri(uri); + if (catalog is IStacCatalog) + return (IStacCatalog)catalog; + throw new InvalidOperationException(string.Format("This is not a STAC catalog {0}", catalog.Uri)); + } - return await client.DownloadStringTaskAsync(uri).ContinueWith(json => LoadJsonToken(JsonConvert.DeserializeObject(json.Result), uri)); + public static async Task LoadStacLink(StacLink link) + { + var catalog = await StacFactory.LoadStacLink(link); + if (catalog is IStacCatalog) + return (IStacCatalog)catalog; + throw new InvalidOperationException(string.Format("This is not a STAC catalog {0}", catalog.Uri)); } - private static StacCatalog LoadJsonToken(JToken jsonRoot, Uri uri) + public static IStacCatalog LoadJToken(JToken jsonRoot, Uri uri) { - StacCatalog catalog; + IStacCatalog catalog; if (jsonRoot["extent"] != null) catalog = Stac.Collection.StacCollection.LoadStacCollection(jsonRoot); else catalog = LoadStacCatalog(jsonRoot); - catalog.sourceUri = uri; + ((IInternalStacObject)catalog).Uri = uri; return catalog; } - private static StacCatalog LoadStacCatalog(JToken jsonRoot) + private static IStacCatalog LoadStacCatalog(JToken jsonRoot) { Type catalogType = null; if (jsonRoot["stac_version"] == null) @@ -54,32 +61,9 @@ private static StacCatalog LoadStacCatalog(JToken jsonRoot) throw new NotSupportedException(string.Format("The document has a non supprted version: '{0}'.", jsonRoot["stac_version"].Value())); } - IStacCatalogModelVersion catalog = (IStacCatalogModelVersion)jsonRoot.ToObject(catalogType); - - while (catalog.GetType() != typeof(StacCatalog)) - { - catalog = catalog.Upgrade(); - } - - return (StacCatalog)catalog; - } - - protected async Task LoadUriRelatively(Uri uri) - { - if (uri.IsAbsoluteUri) - return await StacCatalog.LoadUri(uri); - - return await StacCatalog.LoadUri(new Uri(new Uri(sourceUri.AbsoluteUri.Substring(0, sourceUri.AbsoluteUri.LastIndexOf('/') + 1)), uri)); - } - - public IDictionary GetChildren() - { - return GetChildrenAsync().ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Result); + return (IStacCatalog)jsonRoot.ToObject(catalogType); + } - public IDictionary> GetChildrenAsync() - { - return Links.Where(l => l.RelationshipType == "child").ToDictionary(link => link.Uri, link => LoadUriRelatively(link.Uri)); - } } } diff --git a/src/DotNetStac/Catalog/StacCatalog.Model.cs b/src/DotNetStac/Catalog/StacCatalog.Model.cs index 4ce0fb38..a7c0e00c 100644 --- a/src/DotNetStac/Catalog/StacCatalog.Model.cs +++ b/src/DotNetStac/Catalog/StacCatalog.Model.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using System.Runtime.Serialization; using DotNetStac; using DotNetStac.Converters; using GeoJSON.Net.Geometry; @@ -13,7 +14,7 @@ namespace Stac.Catalog { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public partial class StacCatalog : IStacObject, Model.IStacCatalogModelVersion + public partial class StacCatalog : IStacObject, IStacCatalogVersion, IStacCatalog, IInternalStacObject { private readonly string id; private Collection links; @@ -23,11 +24,14 @@ public partial class StacCatalog : IStacObject, Model.IStacCatalogModelVersion private Collection extensions; private string description; - + private string title; - + private Uri sourceUri; + + public Uri Uri { get => sourceUri; set => sourceUri = value; } + [JsonConstructor] public StacCatalog(string id, string description, IEnumerable links = null) @@ -100,14 +104,32 @@ public string Description } [JsonProperty("id")] - public string Id => id; + public string Id { get => id; } public string Title { get => title; set => title = value; } - public IStacCatalogModelVersion Upgrade() + string IStacObject.Id => throw new NotImplementedException(); + + string IStacObject.StacVersion => throw new NotImplementedException(); + + Uri IStacObject.Uri => throw new NotImplementedException(); + + Collection IStacObject.StacExtensions => throw new NotImplementedException(); + + Collection IStacObject.Links => throw new NotImplementedException(); + + [OnDeserialized] + internal void OnDeserializedMethod(StreamingContext context) { - return this; + foreach (StacLink link in Links) + { + link.Parent = this; + } } + IStacCatalogVersion IStacCatalogVersion.Upgrade() + { + return this; + } } } diff --git a/src/DotNetStac/Collection/StacCollection.Helper.cs b/src/DotNetStac/Collection/StacCollection.Helper.cs index 535be99d..f87bda76 100644 --- a/src/DotNetStac/Collection/StacCollection.Helper.cs +++ b/src/DotNetStac/Collection/StacCollection.Helper.cs @@ -37,7 +37,7 @@ internal static StacCollection LoadStacCollection(JToken jsonRoot) throw new NotSupportedException(string.Format("The document has a non supprted version: '{0}'.", jsonRoot["stac_version"].Value())); } - IStacCollectionModelVersion catalog = (IStacCollectionModelVersion)jsonRoot.ToObject(collectionType); + IStacCollectionVersion catalog = (IStacCollectionVersion)jsonRoot.ToObject(collectionType); while (catalog.GetType() != typeof(StacCollection)) { diff --git a/src/DotNetStac/Collection/StacCollection.Model.cs b/src/DotNetStac/Collection/StacCollection.Model.cs index 77a44663..7fcb3f19 100644 --- a/src/DotNetStac/Collection/StacCollection.Model.cs +++ b/src/DotNetStac/Collection/StacCollection.Model.cs @@ -14,7 +14,7 @@ namespace Stac.Collection { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public partial class StacCollection : StacCatalog, IStacObject, Model.IStacCollectionModelVersion + public partial class StacCollection : StacCatalog, IStacObject, Model.IStacCollectionVersion, IStacCollection { private string license; private StacExtent extent; @@ -76,7 +76,7 @@ public Collection Keywords } - IStacCollectionModelVersion IStacCollectionModelVersion.Upgrade() + IStacCollectionVersion IStacCollectionVersion.Upgrade() { return this; } diff --git a/src/DotNetStac/IInternalStacObject.cs b/src/DotNetStac/IInternalStacObject.cs new file mode 100644 index 00000000..fcc7f06f --- /dev/null +++ b/src/DotNetStac/IInternalStacObject.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.ObjectModel; +using Stac.Extensions; + +namespace Stac +{ + internal interface IInternalStacObject + { + string Id { get; } + + string StacVersion { get; set; } + + Uri Uri { get; set; } + + Collection StacExtensions { get; set; } + + Collection Links { get; set; } + } +} \ No newline at end of file diff --git a/src/DotNetStac/IStacCatalog.cs b/src/DotNetStac/IStacCatalog.cs new file mode 100644 index 00000000..6ec23704 --- /dev/null +++ b/src/DotNetStac/IStacCatalog.cs @@ -0,0 +1,8 @@ +using Stac.Catalog; + +namespace Stac +{ + public interface IStacCatalog: IStacObject + { + } +} \ No newline at end of file diff --git a/src/DotNetStac/IStacCollection.cs b/src/DotNetStac/IStacCollection.cs new file mode 100644 index 00000000..ea4ba655 --- /dev/null +++ b/src/DotNetStac/IStacCollection.cs @@ -0,0 +1,8 @@ +using Stac.Collection; + +namespace Stac +{ + public interface IStacCollection: IStacObject + { + } +} \ No newline at end of file diff --git a/src/DotNetStac/IStacItem.cs b/src/DotNetStac/IStacItem.cs new file mode 100644 index 00000000..a8408975 --- /dev/null +++ b/src/DotNetStac/IStacItem.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using Stac.Item; + +namespace Stac +{ + public interface IStacItem : IStacObject + { + IDictionary Assets { get; } + + IDictionary Properties { get; } + + } +} \ No newline at end of file diff --git a/src/DotNetStac/IStacObject.cs b/src/DotNetStac/IStacObject.cs index 8bcc9172..0302d007 100644 --- a/src/DotNetStac/IStacObject.cs +++ b/src/DotNetStac/IStacObject.cs @@ -10,6 +10,8 @@ public interface IStacObject string StacVersion { get; } + Uri Uri { get; } + Collection StacExtensions { get; } Collection Links { get; } diff --git a/src/DotNetStac/Item/StacItem.Helper.cs b/src/DotNetStac/Item/StacItem.Helper.cs new file mode 100644 index 00000000..ede7c693 --- /dev/null +++ b/src/DotNetStac/Item/StacItem.Helper.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using DotNetStac; +using DotNetStac.Converters; +using GeoJSON.Net.Geometry; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac.Catalog; +using Stac.Converters; +using Stac.Extensions; +using Stac.Model; + +namespace Stac.Item +{ + public partial class StacItem + { + + public static async Task LoadUri(Uri uri) + { + var catalog = await StacFactory.LoadUri(uri); + if (catalog is IStacItem) + return (IStacItem)catalog; + throw new InvalidOperationException(string.Format("This is not a STAC item {0}", catalog.Uri)); + } + + public static async Task LoadStacLink(StacLink link) + { + var catalog = await StacFactory.LoadStacLink(link); + if (catalog is IStacItem) + return (IStacItem)catalog; + throw new InvalidOperationException(string.Format("This is not a STAC item {0}", catalog.Uri)); + } + + public static IStacItem LoadJToken(JToken jsonRoot, Uri uri) + { + IStacItem item = LoadStacItem(jsonRoot); + ((IInternalStacObject)item).Uri = uri; + return item; + } + + private static IStacItem LoadStacItem(JToken jsonRoot) + { + Type itemType = null; + if (jsonRoot["stac_version"] == null) + { + throw new InvalidDataException("The document is not a STAC document. No 'stac_version' property found"); + } + + try + { + itemType = Stac.Model.SchemaDictionary.GetItemTypeFromVersion(jsonRoot["stac_version"].Value()); + } + catch (KeyNotFoundException) + { + throw new NotSupportedException(string.Format("The document has a non supprted version: '{0}'.", jsonRoot["stac_version"].Value())); + } + + return (IStacItem)jsonRoot.ToObject(itemType); + + } + } +} diff --git a/src/DotNetStac/Item/StacItem.cs b/src/DotNetStac/Item/StacItem.Model.cs similarity index 86% rename from src/DotNetStac/Item/StacItem.cs rename to src/DotNetStac/Item/StacItem.Model.cs index b880bfcf..04d205fc 100644 --- a/src/DotNetStac/Item/StacItem.cs +++ b/src/DotNetStac/Item/StacItem.Model.cs @@ -1,17 +1,19 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Runtime.Serialization; using DotNetStac; using DotNetStac.Converters; using GeoJSON.Net.Geometry; using Newtonsoft.Json; using Stac.Converters; using Stac.Extensions; +using Stac.Model; namespace Stac.Item { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public class StacItem : GeoJSON.Net.Feature.Feature, IStacObject + public partial class StacItem : GeoJSON.Net.Feature.Feature, IStacObject, IStacItemVersion, IInternalStacObject { private Collection links; @@ -21,6 +23,8 @@ public class StacItem : GeoJSON.Net.Feature.Feature, IStacObject private Collection extensions; private string collection; + + private Uri sourceUri; [JsonConstructor] public StacItem(IGeometryObject geometry, IDictionary properties = null, string id = null) : base(geometry, properties, id) @@ -76,7 +80,7 @@ public Collection Links } [JsonProperty("assets")] - public Dictionary Assets + public IDictionary Assets { get { @@ -142,5 +146,25 @@ public Itenso.TimePeriod.ITimePeriod DateTime return null; } } + + public Uri Uri { get => sourceUri; set => sourceUri = value; } + + IStacItemVersion IStacItemVersion.Upgrade() + { + return this; + } + + [OnDeserialized] + internal void OnDeserializedMethod(StreamingContext context) + { + foreach (StacLink link in Links) + { + link.Parent = this; + } + foreach (StacAsset asset in Assets.Values) + { + asset.Parent = this; + } + } } } diff --git a/src/DotNetStac/Model/IStacCatalogModelVersion.cs b/src/DotNetStac/Model/IStacCatalogModelVersion.cs deleted file mode 100644 index 2f7c3dc4..00000000 --- a/src/DotNetStac/Model/IStacCatalogModelVersion.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Stac.Model -{ - public interface IStacCatalogModelVersion - { - IStacCatalogModelVersion Upgrade(); - } -} \ No newline at end of file diff --git a/src/DotNetStac/Model/IStacCatalogVersion.cs b/src/DotNetStac/Model/IStacCatalogVersion.cs new file mode 100644 index 00000000..fa58872b --- /dev/null +++ b/src/DotNetStac/Model/IStacCatalogVersion.cs @@ -0,0 +1,7 @@ +namespace Stac.Model +{ + internal interface IStacCatalogVersion : IStacObject + { + IStacCatalogVersion Upgrade(); + } +} \ No newline at end of file diff --git a/src/DotNetStac/Model/IStacCollectionModelVersion.cs b/src/DotNetStac/Model/IStacCollectionModelVersion.cs deleted file mode 100644 index 0d7a7124..00000000 --- a/src/DotNetStac/Model/IStacCollectionModelVersion.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Stac.Model -{ - internal interface IStacCollectionModelVersion - { - IStacCollectionModelVersion Upgrade(); - } -} \ No newline at end of file diff --git a/src/DotNetStac/Model/IStacCollectionVersion.cs b/src/DotNetStac/Model/IStacCollectionVersion.cs new file mode 100644 index 00000000..ea43d7b8 --- /dev/null +++ b/src/DotNetStac/Model/IStacCollectionVersion.cs @@ -0,0 +1,7 @@ +namespace Stac.Model +{ + internal interface IStacCollectionVersion : IStacObject + { + IStacCollectionVersion Upgrade(); + } +} \ No newline at end of file diff --git a/src/DotNetStac/Model/IStacItemVersion.cs b/src/DotNetStac/Model/IStacItemVersion.cs new file mode 100644 index 00000000..2c64971f --- /dev/null +++ b/src/DotNetStac/Model/IStacItemVersion.cs @@ -0,0 +1,10 @@ +using Stac.Item; + +namespace Stac.Model +{ + internal interface IStacItemVersion : IStacObject + { + IStacItemVersion Upgrade(); + + } +} \ No newline at end of file diff --git a/src/DotNetStac/Model/SchemaDictionary.cs b/src/DotNetStac/Model/SchemaDictionary.cs index d95b18ba..37c7ed36 100644 --- a/src/DotNetStac/Model/SchemaDictionary.cs +++ b/src/DotNetStac/Model/SchemaDictionary.cs @@ -37,5 +37,10 @@ internal static Type GetCollectionTypeFromVersion(string version) { return collectionVersionDictionary[version]; } + + internal static Type GetItemTypeFromVersion(string version) + { + return itemVersionDictionary[version]; + } } } \ No newline at end of file diff --git a/src/DotNetStac/Model/v060/StacCatalog.cs b/src/DotNetStac/Model/v060/StacCatalog.cs index 199bc0a6..3ca86261 100644 --- a/src/DotNetStac/Model/v060/StacCatalog.cs +++ b/src/DotNetStac/Model/v060/StacCatalog.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using System.Runtime.Serialization; using DotNetStac; using DotNetStac.Converters; using GeoJSON.Net.Geometry; @@ -12,7 +13,7 @@ namespace Stac.Model.v060 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacCatalog060 : IStacObject, IStacCatalogModelVersion + internal class StacCatalog060 : IStacObject, IStacCatalogVersion, IStacCatalog, IInternalStacObject { private readonly string id; private Collection links; @@ -22,16 +23,17 @@ internal class StacCatalog060 : IStacObject, IStacCatalogModelVersion private Collection extensions; private string description; - + private string title; + private Uri sourceUri; [JsonConstructor] public StacCatalog060(string id, string description, IEnumerable links = null) { this.id = id; this.description = description; - if ( links == null ) + if (links == null) this.links = new Collection(); else this.links = new Collection(links.ToList()); @@ -101,7 +103,9 @@ public string Description public string Title { get => title; set => title = value; } - public IStacCatalogModelVersion Upgrade() + public Uri Uri { get => sourceUri; set => sourceUri = value; } + + public IStacCatalogVersion Upgrade() { var catalog = new v070.StacCatalog070(this.Id, this.Description, @@ -110,5 +114,14 @@ public IStacCatalogModelVersion Upgrade() catalog.Title = this.Title; return catalog; } + + [OnDeserialized] + internal void OnDeserializedMethod(StreamingContext context) + { + foreach (StacLink link in Links) + { + link.Parent = this; + } + } } } diff --git a/src/DotNetStac/Model/v060/StacCollection.cs b/src/DotNetStac/Model/v060/StacCollection.cs index 96f94d3c..e9cc00c1 100644 --- a/src/DotNetStac/Model/v060/StacCollection.cs +++ b/src/DotNetStac/Model/v060/StacCollection.cs @@ -14,11 +14,10 @@ namespace Stac.Model.v060 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacCollection060 : StacCatalog060, IStacObject, IStacCollectionModelVersion + internal class StacCollection060 : StacCatalog060, IStacObject, IStacCollectionVersion, IStacCollection { private string license; private StacExtent060 extent; - private Dictionary summaries; private Collection providers; private Collection keywords; @@ -64,7 +63,7 @@ public Collection Keywords [JsonExtensionData] public Dictionary Properties { get; set; } - IStacCollectionModelVersion IStacCollectionModelVersion.Upgrade() + IStacCollectionVersion IStacCollectionVersion.Upgrade() { var collection = new v070.StacCollection070(this.Id, this.Description, diff --git a/src/DotNetStac/Model/v060/StacItem.cs b/src/DotNetStac/Model/v060/StacItem.cs index b875c844..52da2060 100644 --- a/src/DotNetStac/Model/v060/StacItem.cs +++ b/src/DotNetStac/Model/v060/StacItem.cs @@ -11,7 +11,7 @@ namespace Stac.Model.v060 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacItem060 : GeoJSON.Net.Feature.Feature, IStacObject + internal class StacItem060 : GeoJSON.Net.Feature.Feature, IStacItemVersion, IStacObject, IStacItem { private Collection links; @@ -19,7 +19,6 @@ internal class StacItem060 : GeoJSON.Net.Feature.Feature, IStacObject private string stacVersion = StacVersionList.Current; - private Collection extensions; private string collection; [JsonConstructor] @@ -29,36 +28,6 @@ public StacItem060(IGeometryObject geometry, IDictionary propert public StacItem060(IGeometryObject geometry, object properties, string id = null) : base(geometry, properties, id) { } - [JsonProperty("stac_extensions")] - [JsonConverter(typeof(StacExtensionConverter))] - public Collection StacExtensions - { - get - { - if (extensions == null) - extensions = new Collection(); - return extensions; - } - set - { - extensions = value; - } - } - - [JsonProperty("stac_version")] - public string StacVersion - { - get - { - return stacVersion; - } - - set - { - stacVersion = value; - } - } - [JsonConverter(typeof(CollectionConverter))] [JsonProperty("links")] public Collection Links @@ -76,7 +45,7 @@ public Collection Links } [JsonProperty("assets")] - public Dictionary Assets + public IDictionary Assets { get { @@ -142,5 +111,29 @@ public Itenso.TimePeriod.ITimePeriod DateTime return null; } } + + [JsonIgnore] + public Uri Uri => throw new NotImplementedException(); + + [JsonIgnore] + public string StacVersion => StacVersionList.V060; + + [JsonIgnore] + public Collection StacExtensions => null; + + public IStacItemVersion Upgrade() + { + var item = new v070.StacItem070(this.Geometry, + this.Properties, + this.Id); + item.Links = this.links; + foreach (var asset in this.Assets) + item.Assets.Add(asset.Key, asset.Value); + item.Collection = this.Collection; + item.BoundingBoxes = this.BoundingBoxes; + return item; + } + + } } diff --git a/src/DotNetStac/Model/v070/StacCatalog.cs b/src/DotNetStac/Model/v070/StacCatalog.cs index c2dc0e81..81a710ba 100644 --- a/src/DotNetStac/Model/v070/StacCatalog.cs +++ b/src/DotNetStac/Model/v070/StacCatalog.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using System.Runtime.Serialization; using DotNetStac; using DotNetStac.Converters; using GeoJSON.Net.Geometry; @@ -13,7 +14,7 @@ namespace Stac.Model.v070 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacCatalog070 : IStacObject, IStacCatalogModelVersion + internal class StacCatalog070 : IStacObject, IStacCatalogVersion, IStacCatalog, IInternalStacObject { private readonly string id; private Collection links; @@ -23,9 +24,10 @@ internal class StacCatalog070 : IStacObject, IStacCatalogModelVersion private Collection extensions; private string description; - + private string title; + private Uri sourceUri; [JsonConstructor] public StacCatalog070(string id, string description, IEnumerable links = null) @@ -84,7 +86,7 @@ public Collection Links } } - + [JsonProperty("description")] public string Description @@ -104,7 +106,9 @@ public string Description public string Title { get => title; set => title = value; } - public IStacCatalogModelVersion Upgrade() + public Uri Uri { get => sourceUri; set => sourceUri = value; } + + public IStacCatalogVersion Upgrade() { var catalog = new Catalog.StacCatalog(this.Id, this.Description, @@ -114,5 +118,14 @@ public IStacCatalogModelVersion Upgrade() return catalog; } + + [OnDeserialized] + internal void OnDeserializedMethod(StreamingContext context) + { + foreach (StacLink link in Links) + { + link.Parent = this; + } + } } } diff --git a/src/DotNetStac/Model/v070/StacCollection.cs b/src/DotNetStac/Model/v070/StacCollection.cs index e4271216..a971ee84 100644 --- a/src/DotNetStac/Model/v070/StacCollection.cs +++ b/src/DotNetStac/Model/v070/StacCollection.cs @@ -6,7 +6,7 @@ namespace Stac.Model.v070 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacCollection070 : StacCatalog070, IStacObject, IStacCollectionModelVersion + internal class StacCollection070 : StacCatalog070, IStacObject, IStacCollectionVersion, IStacCollection, IInternalStacObject { private string license; private v060.StacExtent060 extent; @@ -67,7 +67,7 @@ public Collection Keywords } } - IStacCollectionModelVersion IStacCollectionModelVersion.Upgrade() + IStacCollectionVersion IStacCollectionVersion.Upgrade() { var collection = new Collection.StacCollection(this.Id, this.Description, this.extent.Upgrade(), this.Links); diff --git a/src/DotNetStac/Model/v070/StacItem.cs b/src/DotNetStac/Model/v070/StacItem.cs index eeae8ea5..cba99016 100644 --- a/src/DotNetStac/Model/v070/StacItem.cs +++ b/src/DotNetStac/Model/v070/StacItem.cs @@ -11,16 +11,14 @@ namespace Stac.Model.v070 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacItem070 : GeoJSON.Net.Feature.Feature, IStacObject + internal class StacItem070 : GeoJSON.Net.Feature.Feature, IStacItemVersion, IStacObject, IStacItem, IInternalStacObject { private Collection links; private Dictionary assets; - private string stacVersion = StacVersionList.Current; - - private Collection extensions; private string collection; + private Uri sourceUri; [JsonConstructor] public StacItem070(IGeometryObject geometry, IDictionary properties = null, string id = null) : base(geometry, properties, id) @@ -29,36 +27,6 @@ public StacItem070(IGeometryObject geometry, IDictionary propert public StacItem070(IGeometryObject geometry, object properties, string id = null) : base(geometry, properties, id) { } - [JsonProperty("stac_extensions")] - [JsonConverter(typeof(StacExtensionConverter))] - public Collection StacExtensions - { - get - { - if (extensions == null) - extensions = new Collection(); - return extensions; - } - set - { - extensions = value; - } - } - - [JsonProperty("stac_version")] - public string StacVersion - { - get - { - return stacVersion; - } - - set - { - stacVersion = value; - } - } - [JsonConverter(typeof(CollectionConverter))] [JsonProperty("links")] public Collection Links @@ -76,7 +44,7 @@ public Collection Links } [JsonProperty("assets")] - public Dictionary Assets + public IDictionary Assets { get { @@ -142,5 +110,25 @@ public Itenso.TimePeriod.ITimePeriod DateTime return null; } } + + public Uri Uri { get => sourceUri; set => sourceUri = value; } + + public string StacVersion { get => StacVersionList.V070; set { } } + + public Collection StacExtensions { get => null; set { } } + + + public IStacItemVersion Upgrade() + { + var item = new Item.StacItem(this.Geometry, + this.Properties, + this.Id); + item.Links = this.links; + foreach (var asset in this.Assets) + item.Assets.Add(asset.Key, asset.Value); + item.Collection = this.Collection; + item.BoundingBoxes = this.BoundingBoxes; + return item; + } } } diff --git a/src/DotNetStac/StacAsset.cs b/src/DotNetStac/StacAsset.cs index 655c52f9..20aa4f5e 100644 --- a/src/DotNetStac/StacAsset.cs +++ b/src/DotNetStac/StacAsset.cs @@ -40,14 +40,16 @@ public static StacAsset CreateMetadataAsset(Uri uri, string mediaType, string ti string title, type, description; Collection semanticRoles; + private IStacObject hostObject; public StacAsset() { } - public StacAsset(Uri uri) + public StacAsset(Uri uri, IStacObject hostObject) { Uri = uri; + this.hostObject = hostObject; } public StacAsset(Uri uri, IEnumerable semanticRoles, string title, string mediaType) @@ -70,18 +72,6 @@ public StacAsset(StacAsset source) description = source.description; } - [JsonIgnore] - public Uri BaseUri - { - get { return base_uri; } - set - { - if (value != null && !value.IsAbsoluteUri) - throw new ArgumentException("Base URI must not be relative"); - base_uri = value; - } - } - [JsonProperty("type")] public string MediaType { @@ -143,5 +133,29 @@ public virtual StacAsset Clone() { return new StacAsset(this); } + + [JsonIgnore] + public Uri AbsoluteUri + { + get + { + if (Uri.IsAbsoluteUri) + return Uri; + + if (hostObject != null) + return new Uri(new Uri(hostObject.Uri.AbsoluteUri.Substring(0, hostObject.Uri.AbsoluteUri.LastIndexOf('/') + 1)), Uri); + + return null; + } + } + + public IStacObject Parent + { + get => hostObject; + internal set + { + hostObject = value; + } + } } } \ No newline at end of file diff --git a/src/DotNetStac/StacExtensionsHelper.cs b/src/DotNetStac/StacExtensionsHelper.cs new file mode 100644 index 00000000..b1f17103 --- /dev/null +++ b/src/DotNetStac/StacExtensionsHelper.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Runtime.Serialization; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac.Collection; +using Stac.Item; +using Stac.Model; + +namespace Stac.Catalog +{ + public static class StacExtensionsHelper + { + + public static IDictionary GetChildren(this IStacObject stacObject) + { + return GetChildrenAsync(stacObject).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Result); + } + + public static IDictionary> GetChildrenAsync(this IStacObject stacObject) + { + return stacObject.Links.Where(l => l.RelationshipType == "child").ToDictionary(link => link.Uri, link => StacCatalog.LoadStacLink(link)); + } + + public static IDictionary GetItems(this IStacObject stacObject) + { + return GetItemsAsync(stacObject).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Result); + } + + public static IDictionary> GetItemsAsync(this IStacObject stacObject) + { + return stacObject.Links.Where(l => l.RelationshipType == "item").ToDictionary(link => link.Uri, link => StacItem.LoadStacLink(link)); + } + + public static IEnumerable GetChildrenLinks(this IStacObject stacObject, bool absolute = true) + { + return stacObject.Links.Where(l => l.RelationshipType == "child"); + } + + public static IEnumerable GetItemLinks(this IStacObject stacObject, bool absolute = true) + { + return stacObject.Links.Where(l => l.RelationshipType == "item"); + } + + public static StacItem UpgradeToCurrentVersion(this IStacItem item1) + { + IStacItemVersion item = (IStacItemVersion)item1; + while (!(item is Item.StacItem)) + { + item = item.Upgrade(); + } + return (Item.StacItem)item; + } + + public static StacCatalog UpgradeToCurrentVersion(this IStacCatalog catalog1) + { + IStacCatalogVersion catalog = (IStacCatalogVersion)catalog1; + while (!(catalog is StacCatalog)) + { + catalog = catalog.Upgrade(); + } + return (StacCatalog)catalog; + } + } +} diff --git a/src/DotNetStac/StacFactory.cs b/src/DotNetStac/StacFactory.cs new file mode 100644 index 00000000..5156f582 --- /dev/null +++ b/src/DotNetStac/StacFactory.cs @@ -0,0 +1,42 @@ +using System; +using System.Net; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac.Collection; +using Stac.Item; +using Stac.Model; + +namespace Stac +{ + public class StacFactory + { + public static async Task LoadUri(Uri uri) + { + WebClient client = new WebClient(); + return await client.DownloadStringTaskAsync(uri).ContinueWith(json => + { + var jsonToken = JsonConvert.DeserializeObject(json.Result); + if (jsonToken["geometry"] != null) + return StacItem.LoadJToken(jsonToken, uri); + + return StacCollection.LoadJToken(jsonToken, uri); + + }); + } + + public static async Task LoadStacLink(StacLink link) + { + WebClient client = new WebClient(); + var jsonToken = JsonConvert.DeserializeObject(await client.DownloadStringTaskAsync(link.AbsoluteUri)); + if (jsonToken["stac_version"] == null && link.Parent != null && Version.Parse(link.Parent.StacVersion).CompareTo(Version.Parse("0.8.0")) < 0) + jsonToken["stac_version"] = link.Parent.StacVersion; + + if (jsonToken["geometry"] != null) + return StacItem.LoadJToken(jsonToken, link.AbsoluteUri); + + return StacCollection.LoadJToken(jsonToken, link.AbsoluteUri); + } + + } +} diff --git a/src/DotNetStac/StacLink.cs b/src/DotNetStac/StacLink.cs index 845e9688..38974418 100644 --- a/src/DotNetStac/StacLink.cs +++ b/src/DotNetStac/StacLink.cs @@ -43,6 +43,7 @@ public static StacLink CreateAlternateLink(Uri uri, string mediaType = null) Uri href; string rel, title, type; + private IStacObject hostObject; public StacLink() { @@ -53,6 +54,12 @@ public StacLink(Uri uri) Uri = uri; } + public StacLink(Uri uri, IStacObject hostObject) + { + Uri = uri; + this.hostObject = hostObject; + } + public StacLink(Uri uri, string relationshipType, string title, string mediaType) { Uri = uri; @@ -69,6 +76,7 @@ public StacLink(StacLink source) rel = source.rel; title = source.title; type = source.type; + hostObject = source.hostObject; } [JsonProperty("type")] @@ -99,6 +107,30 @@ public Uri Uri set { href = value; } } + [JsonIgnore] + public Uri AbsoluteUri + { + get + { + if (Uri.IsAbsoluteUri) + return Uri; + + if (hostObject != null) + return new Uri(new Uri(hostObject.Uri.AbsoluteUri.Substring(0, hostObject.Uri.AbsoluteUri.LastIndexOf('/') + 1)), Uri); + + return null; + } + } + + public IStacObject Parent + { + get => hostObject; + internal set + { + hostObject = value; + } + } + public virtual StacLink Clone() { return new StacLink(this); diff --git a/src/DotNetStac/StacObject.cs b/src/DotNetStac/StacObject.cs deleted file mode 100644 index 312bca7f..00000000 --- a/src/DotNetStac/StacObject.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using Newtonsoft.Json; -using Stac.Extensions; - -namespace Stac -{ - - [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public abstract class StacObject : IStacObject - { - private readonly string id; - private string stacVersion; - private Collection links; - - public StacObject(string id) - { - this.id = id; - } - - public StacObject(string id, IEnumerable links) : this(id) - { - Links = new Collection(links.ToList()); - } - - public string Id => id; - - public string StacVersion - { - get - { - return stacVersion; - } - - set - { - stacVersion = value; - } - } - - public abstract Collection StacExtensions { get; } - - public Collection Links - { - get - { - if (links == null) - links = new Collection(); - return links; - } - set - { - links = value; - } - } - } -} diff --git a/src/DotNetStac/StacVersionList.cs b/src/DotNetStac/StacVersionList.cs index 1c4cd70b..33d7ce52 100644 --- a/src/DotNetStac/StacVersionList.cs +++ b/src/DotNetStac/StacVersionList.cs @@ -6,6 +6,10 @@ public static class StacVersionList { public static string Current => V100beta1; - public static string V100beta1 => "1.0.0-beta.1"; + public static string V100beta1 => "1.0.0-beta.1"; + + public static string V060 => "0.6.0"; + + public static string V070 => "0.7.0"; } } From dd4366a5068e5aca4f81b9846d768bdd54a7fb56 Mon Sep 17 00:00:00 2001 From: Emmanuel Mathot Date: Thu, 20 Aug 2020 09:20:05 +0200 Subject: [PATCH 17/21] Summeries coimpleted + Tests OK --- .../Collection/CollectionTests.cs | 122 +++++++++++++++++- ...tionTests_CanSerializeSentinel2Sample.json | 2 +- src/DotNetStac/Catalog/StacCatalog.Model.cs | 11 +- .../Collection/StacCollection.Model.cs | 2 + .../Collection/StacSummaryStatsObject.cs | 10 +- .../Collection/StacSummaryValueSet.cs | 14 +- .../Converters/StacSummariesConverter.cs | 4 +- 7 files changed, 141 insertions(+), 24 deletions(-) diff --git a/src/DotNetStac.Test/Collection/CollectionTests.cs b/src/DotNetStac.Test/Collection/CollectionTests.cs index 381847ec..b17a80db 100644 --- a/src/DotNetStac.Test/Collection/CollectionTests.cs +++ b/src/DotNetStac.Test/Collection/CollectionTests.cs @@ -4,6 +4,7 @@ using GeoJSON.Net; using GeoJSON.Net.Geometry; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using Stac.Collection; using Xunit; @@ -47,18 +48,16 @@ public void CanDeserializeSentinel2Sample() Assert.Equal(2, item.Summaries["view:sun_elevation"].LongCount()); - - } [Fact] public void CanSerializeSentinel2Sample() { StacExtent extent = new StacExtent(); - extent.Spatial = new StacSpatialExtent( -180, -56, 180, 83); + extent.Spatial = new StacSpatialExtent(-180, -56, 180, 83); extent.Temporal = new StacTemporalExtent(DateTime.Parse("2015-06-23T00:00:00Z").ToUniversalTime(), null); - StacCollection collection = new StacCollection("COPERNICUS/S2", + StacCollection collection = new StacCollection("COPERNICUS/S2", "Sentinel-2 is a wide-swath, high-resolution, multi-spectral\nimaging mission supporting Copernicus Land Monitoring studies,\nincluding the monitoring of vegetation, soil and water cover,\nas well as observation of inland waterways and coastal areas.\n\nThe Sentinel-2 data contain 13 UINT16 spectral bands representing\nTOA reflectance scaled by 10000. See the [Sentinel-2 User Handbook](https://sentinel.esa.int/documents/247904/685211/Sentinel-2_User_Handbook)\nfor details. In addition, three QA bands are present where one\n(QA60) is a bitmask band with cloud mask information. For more\ndetails, [see the full explanation of how cloud masks are computed.](https://sentinel.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-1c/cloud-masks)\n\nEach Sentinel-2 product (zip archive) may contain multiple\ngranules. Each granule becomes a separate Earth Engine asset.\nEE asset ids for Sentinel-2 assets have the following format:\nCOPERNICUS/S2/20151128T002653_20151128T102149_T56MNN. Here the\nfirst numeric part represents the sensing date and time, the\nsecond numeric part represents the product generation date and\ntime, and the final 6-character string is a unique granule identifier\nindicating its UTM grid reference (see [MGRS](https://en.wikipedia.org/wiki/Military_Grid_Reference_System)).\n\nFor more details on Sentinel-2 radiometric resoltuon, [see this page](https://earth.esa.int/web/sentinel/user-guides/sentinel-2-msi/resolutions/radiometric).\n", extent); @@ -83,6 +82,121 @@ public void CanSerializeSentinel2Sample() Uri = new Uri("https://sentinel.esa.int/web/sentinel/user-guides/sentinel-2-msi") }}); + collection.Summaries.Add("datetime", + new StacSummaryStatsObject( + DateTime.Parse("2015-06-23T00:00:00Z").ToUniversalTime(), + DateTime.Parse("2019-07-10T13:44:56Z").ToUniversalTime() + ) + ); + + collection.Summaries.Add("platform", + new StacSummaryValueSet(new string[] { "sentinel-2a", "sentinel-2b" }) + ); + + collection.Summaries.Add("constellation", + new StacSummaryValueSet(new string[] { "sentinel-2" }) + ); + + collection.Summaries.Add("instruments", + new StacSummaryValueSet(new string[] { "msi" }) + ); + + collection.Summaries.Add("view:off_nadir", + new StacSummaryStatsObject( + 0.0, + 100 + ) + ); + + collection.Summaries.Add("view:sun_elevation", + new StacSummaryStatsObject( + 6.78, + 89.9 + ) + ); + + collection.Summaries.Add("sci:citation", + new StacSummaryValueSet(new string[] { "Copernicus Sentinel data [Year]" }) + ); + + collection.Summaries.Add("gsd", + new StacSummaryValueSet(new int[] { + 10, + 30, + 60 + }) + ); + + collection.Summaries.Add("proj:epsg", + new StacSummaryValueSet(new int[] + { 32601,32602,32603,32604,32605,32606,32607,32608,32609,32610,32611,32612,32613,32614,32615,32616,32617,32618,32619,32620,32621,32622,32623,32624,32625,32626,32627,32628,32629,32630,32631,32632,32633,32634,32635,32636,32637,32638,32639,32640,32641,32642,32643,32644,32645,32646,32647,32648,32649,32650,32651,32652,32653,32654,32655,32656,32657,32658,32659,32660} + ) + ); + + collection.Summaries.Add("eo:bands", + new StacSummaryValueSet(new JObject[] { + new JObject { + { "name", "B1" }, + { "common_name", "coastal" }, + { "center_wavelength", 4.439 } + }, + new JObject { + { "name", "B2"}, + { "common_name", "blue"}, + { "center_wavelength", 4.966} + }, + new JObject { + { "name", "B3"}, + { "common_name", "green"}, + { "center_wavelength", 5.6} + }, + new JObject { + { "name", "B4"}, + { "common_name", "red"}, + { "center_wavelength", 6.645} + }, + new JObject { + { "name", "B5"}, + { "center_wavelength", 7.039} + }, + new JObject { + { "name", "B6"}, + { "center_wavelength", 7.402} + }, + new JObject { + { "name", "B7"}, + { "center_wavelength", 7.825} + }, + new JObject { + { "name", "B8"}, + { "common_name", "nir"}, + { "center_wavelength", 8.351} + }, + new JObject { + { "name", "B8A"}, + { "center_wavelength", 8.648} + }, + new JObject { + { "name", "B9"}, + { "center_wavelength", 9.45} + }, + new JObject { + { "name", "B10"}, + { "center_wavelength", 1.3735} + }, + new JObject { + { "name", "B11"}, + { "common_name", "swir16"}, + { "center_wavelength", 1.6137} + }, + new JObject { + { "name", "B12"}, + { "common_name", "swir22"}, + { "center_wavelength", 2.2024} + } + }) + ); + var actualJson = JsonConvert.SerializeObject(collection); Console.WriteLine(actualJson); diff --git a/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json b/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json index 95670ce7..a3316164 100644 --- a/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json +++ b/src/DotNetStac.Test/Resources/Collection/CollectionTests_CanSerializeSentinel2Sample.json @@ -54,7 +54,7 @@ "instruments": ["msi"], "view:off_nadir": { "min": 0.0, - "max": 100 + "max": 100.0 }, "view:sun_elevation": { "min": 6.78, diff --git a/src/DotNetStac/Catalog/StacCatalog.Model.cs b/src/DotNetStac/Catalog/StacCatalog.Model.cs index a7c0e00c..ca672209 100644 --- a/src/DotNetStac/Catalog/StacCatalog.Model.cs +++ b/src/DotNetStac/Catalog/StacCatalog.Model.cs @@ -106,18 +106,9 @@ public string Description [JsonProperty("id")] public string Id { get => id; } + [JsonProperty("title")] public string Title { get => title; set => title = value; } - string IStacObject.Id => throw new NotImplementedException(); - - string IStacObject.StacVersion => throw new NotImplementedException(); - - Uri IStacObject.Uri => throw new NotImplementedException(); - - Collection IStacObject.StacExtensions => throw new NotImplementedException(); - - Collection IStacObject.Links => throw new NotImplementedException(); - [OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { diff --git a/src/DotNetStac/Collection/StacCollection.Model.cs b/src/DotNetStac/Collection/StacCollection.Model.cs index 7fcb3f19..a0c08eb8 100644 --- a/src/DotNetStac/Collection/StacCollection.Model.cs +++ b/src/DotNetStac/Collection/StacCollection.Model.cs @@ -39,6 +39,8 @@ public Dictionary Summaries { get { + if (summaries == null) + summaries = new Dictionary(); return summaries; } set diff --git a/src/DotNetStac/Collection/StacSummaryStatsObject.cs b/src/DotNetStac/Collection/StacSummaryStatsObject.cs index e6ddc7c2..da1c8612 100644 --- a/src/DotNetStac/Collection/StacSummaryStatsObject.cs +++ b/src/DotNetStac/Collection/StacSummaryStatsObject.cs @@ -10,19 +10,19 @@ public class StacSummaryStatsObject : StacSummaryItem { public StacSummaryStatsObject(JObject summary) : base(summary) { - Min = summary["min"].Value(); - Max = summary["max"].Value(); + if (!summary.ContainsKey("min") || !summary.ContainsKey("max")) + throw new ArgumentException("summary stats must contains min and max"); } - public StacSummaryStatsObject(T min, T max) : base(null) + public StacSummaryStatsObject(T min, T max) : base(new JObject()) { Min = min; Max = max; } - public T Min { get; set; } + public T Min { get => summary["min"].Value(); set => summary["min"] = new JValue(value); } - public T Max { get; set; } + public T Max { get => summary["max"].Value(); set => summary["max"] = new JValue(value); } public override SummaryItemType SummaryType => SummaryItemType.StatsObject; diff --git a/src/DotNetStac/Collection/StacSummaryValueSet.cs b/src/DotNetStac/Collection/StacSummaryValueSet.cs index f37049c9..81a6a436 100644 --- a/src/DotNetStac/Collection/StacSummaryValueSet.cs +++ b/src/DotNetStac/Collection/StacSummaryValueSet.cs @@ -10,20 +10,28 @@ namespace Stac.Collection { public class StacSummaryValueSet : StacSummaryItem, IEnumerable { - private readonly List summarySet; public StacSummaryValueSet(JArray summarySet) : base(summarySet) { - this.summarySet = summarySet.ToObject>(); + } + + public StacSummaryValueSet(IEnumerable summarySet) : base(new JArray(summarySet)) + { + } + + public void Add(T item){ + ((JArray)summary).Add(item); } public override SummaryItemType SummaryType => SummaryItemType.Set; public int Count => summary.Count(); + public IEnumerable SummarySet { get => summary.ToObject>(); } + IEnumerator IEnumerable.GetEnumerator() { - return summarySet.GetEnumerator(); + return SummarySet.GetEnumerator(); } } diff --git a/src/DotNetStac/Converters/StacSummariesConverter.cs b/src/DotNetStac/Converters/StacSummariesConverter.cs index cd3d934c..465ca386 100644 --- a/src/DotNetStac/Converters/StacSummariesConverter.cs +++ b/src/DotNetStac/Converters/StacSummariesConverter.cs @@ -77,7 +77,9 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - throw new NotImplementedException(); + Dictionary summaries = (Dictionary)value; + + serializer.Serialize(writer, summaries.ToDictionary(k => k.Key, k => k.Value.AsJToken)); } } } \ No newline at end of file From 938ae27b2763a671c749b7e379dba760efebf76a Mon Sep 17 00:00:00 2001 From: Emmanuel Mathot Date: Thu, 20 Aug 2020 11:17:45 +0200 Subject: [PATCH 18/21] Initial README + 0.2.0-beta --- .vscode/tasks.json | 18 ++ README.md | 261 +++++++++++++++++- src/DotNetStac.Test/Examples/Example1Test.cs | 182 ++++++++++++ src/DotNetStac/Catalog/StacCatalog.Helper.cs | 2 +- src/DotNetStac/Catalog/StacCatalog.Model.cs | 4 +- .../Collection/StacCollection.Helper.cs | 2 +- .../Collection/StacCollection.Model.cs | 7 +- src/DotNetStac/DotNetStac.csproj | 27 +- src/DotNetStac/IStacObject.cs | 2 + src/DotNetStac/Item/StacItem.Helper.cs | 2 +- src/DotNetStac/Item/StacItem.Model.cs | 4 +- src/DotNetStac/Model/IStacCatalogVersion.cs | 7 - .../Model/IStacCollectionVersion.cs | 7 - src/DotNetStac/Model/IStacItemVersion.cs | 10 - src/DotNetStac/Model/v060/StacCatalog.cs | 4 +- src/DotNetStac/Model/v060/StacCollection.cs | 4 +- src/DotNetStac/Model/v060/StacItem.cs | 4 +- src/DotNetStac/Model/v070/StacCatalog.cs | 4 +- src/DotNetStac/Model/v070/StacCollection.cs | 4 +- src/DotNetStac/Model/v070/StacItem.cs | 4 +- src/DotNetStac/StacExtensionsHelper.cs | 4 +- src/DotNetStac/StacFactory.cs | 7 +- 22 files changed, 508 insertions(+), 62 deletions(-) create mode 100644 src/DotNetStac.Test/Examples/Example1Test.cs delete mode 100644 src/DotNetStac/Model/IStacCatalogVersion.cs delete mode 100644 src/DotNetStac/Model/IStacCollectionVersion.cs delete mode 100644 src/DotNetStac/Model/IStacItemVersion.cs diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 6a6c3dc6..ffa93901 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -20,6 +20,24 @@ "reveal": "silent" }, "problemMatcher": "$msCompile" + }, + { + "label": "pack", + "command": "dotnet", + "type": "shell", + "args": [ + "pack", + // Ask dotnet build to generate full paths for file names. + "/property:GenerateFullPaths=true", + // Do not generate summary otherwise it leads to duplicate errors in Problems panel + "/consoleloggerparameters:NoSummary", + "src/DotNetStac.sln" + ], + "group": "build", + "presentation": { + "reveal": "silent" + }, + "problemMatcher": "$msCompile" } ] } \ No newline at end of file diff --git a/README.md b/README.md index 0cac8e33..2ba4c933 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,260 @@ -[![Build Status](https://travis-ci.com/Terradue/DotNetStac.svg?branch=develop)](https://travis-ci.com/Terradue/DotNetStac) -# DotNetStac -.Net library for working with any SpatioTemporal Asset Catalog (STAC) + +

DotNetStac

+ + +

+.Net library for working with any Spatio Temporal Asset Catalog (STAC) + + ![](docs/logo/logo-wide.png) + +

+ +

+ + [![Build Status](https://travis-ci.com/Terradue/DotNetStac.svg?branch=develop)](https://travis-ci.com/Terradue/DotNetStac) + [![NuGet](https://img.shields.io/nuget/v/:DotNetStac)](https://www.nuget.org/packages/DotNetStac/) + [![Gitter](https://img.shields.io/gitter/room/dotnet/BenchmarkDotNet?color=yellow)](https://gitter.im/dotnet/BenchmarkDotNet) + [![License](https://img.shields.io/badge/license-AGPL3-blue.svg)](LICENSE) + +

+ +

+ Features + · + Getting started + · + Documentation + · + Developing +

+ +**DotNetStac** helps you to work with STAC ([catalog](https://github.com/radiantearth/stac-spec/tree/master/catalog-spec), [collection](https://github.com/radiantearth/stac-spec/tree/master/collection-spec), [item](https://github.com/radiantearth/stac-spec/tree/master/catalog-spec)) + +In a nutshell, the library allows manipulating STAC JSON documents (Serialization/Deserialization using [Newtonsoft.JSON](https://www.newtonsoft.com/json)) with properties represented in enhanced objects such as geometries, time stamp/period/span, numerical values and many more via STAC extension plugins engine. + +## Features + +### Current features + +* (De)Serialization engine supporting current and older versions of the specifications with an upgrade mechanism +* Navigation methods to seamlessly traverse a STAC catalog through collections and items +* Enhanced extensions support with plugin system for embedding extension related functions (e.g. sat: orbit file download, sar: interferometric search, eo: calibration parameters) + +### Other features to come + +* STAC API Client +* Importers from other spatio temporal domains (e.g. OGC O&M, Earth Observation profile…) + +## Getting Started + +### Installation + +DotNetStac can be installed using the Nuget package manager or the `dotnet` CLI. + +``` +dotnet add package DotNetStac +``` + +### Example #1 : Deserialization and Navigation + +The following example load a catalog and loads all its items + +```csharp +using Stac; + + IStacCatalog catalog = (IStacCatalog)StacFactory.Load("https://cbers-stac-0-7.s3.amazonaws.com/CBERS4/MUX/027/069/catalog.json"); + + Console.Out.WriteLine(catalog.Id); + Console.Out.WriteLine(catalog.StacVersion); + + foreach (var item in catalog.GetItems().Values) + { + Console.Out.WriteLine(item.Id); + } + +``` + +### Example #2 : Serialization of a created collection + +The following example load a catalog and loads all its items + +```csharp +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac; +using Stac.Catalog; +using Stac.Collection; +using System; +using System.Collections.Generic; + + StacExtent extent = new StacExtent(); + extent.Spatial = new StacSpatialExtent(-180, -56, 180, 83); + extent.Temporal = new StacTemporalExtent(DateTime.Parse("2015-06-23T00:00:00Z").ToUniversalTime(), null); + + StacCollection collection = new StacCollection("COPERNICUS/S2", + "Sentinel-2 is a wide-swath, high-resolution, multi-spectral\nimaging mission supporting Copernicus Land Monitoring studies,...", + extent); + + collection.Title = "Sentinel-2 MSI: MultiSpectral Instrument, Level-1C"; + + collection.Links.Add(StacLink.CreateSelfLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/COPERNICUS_S2.json"))); + collection.Links.Add(StacLink.CreateParentLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/catalog.json"))); + collection.Links.Add(StacLink.CreateRootLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/catalog.json"))); + collection.Links.Add(new StacLink(new Uri("https://scihub.copernicus.eu/twiki/pub/SciHubWebPortal/TermsConditions/Sentinel_Data_Terms_and_Conditions.pdf"), "license", "Legal notice on the use of Copernicus Sentinel Data and Service Information", null)); + + collection.Keywords = new System.Collections.ObjectModel.Collection(new string[] { + "copernicus", + "esa", + "eu", + "msi", + "radiance", + "sentinel"}); + + collection.Providers = new System.Collections.ObjectModel.Collection( + new StacProvider[]{new StacProvider("European Union/ESA/Copernicus"){ + Roles = new List() { StacProviderRole.producer, StacProviderRole.licensor}, + Uri = new Uri("https://sentinel.esa.int/web/sentinel/user-guides/sentinel-2-msi") + }}); + + collection.Summaries.Add("datetime", + new StacSummaryStatsObject( + DateTime.Parse("2015-06-23T00:00:00Z").ToUniversalTime(), + DateTime.Parse("2019-07-10T13:44:56Z").ToUniversalTime() + ) + ); + + collection.Summaries.Add("platform", + new StacSummaryValueSet(new string[] { "sentinel-2a", "sentinel-2b" }) + ); + + collection.Summaries.Add("constellation", + new StacSummaryValueSet(new string[] { "sentinel-2" }) + ); + + collection.Summaries.Add("instruments", + new StacSummaryValueSet(new string[] { "msi" }) + ); + + collection.Summaries.Add("view:off_nadir", + new StacSummaryStatsObject( + 0.0, + 100 + ) + ); + + collection.Summaries.Add("view:sun_elevation", + new StacSummaryStatsObject( + 6.78, + 89.9 + ) + ); + + collection.Summaries.Add("sci:citation", + new StacSummaryValueSet(new string[] { "Copernicus Sentinel data [Year]" }) + ); + + collection.Summaries.Add("gsd", + new StacSummaryValueSet(new int[] { + 10, + 30, + 60 + }) + ); + + collection.Summaries.Add("proj:epsg", + new StacSummaryValueSet(new int[] + { 32601,32602,32603,32604,32605,32606,32607,32608,32609,32610,32611,32612,32613,32614,32615,32616,32617,32618,32619,32620,32621,32622,32623,32624,32625,32626,32627,32628,32629,32630,32631,32632,32633,32634,32635,32636,32637,32638,32639,32640,32641,32642,32643,32644,32645,32646,32647,32648,32649,32650,32651,32652,32653,32654,32655,32656,32657,32658,32659,32660} + ) + ); + + collection.Summaries.Add("eo:bands", + new StacSummaryValueSet(new JObject[] { + new JObject { + { "name", "B1" }, + { "common_name", "coastal" }, + { "center_wavelength", 4.439 } + }, + new JObject { + { "name", "B2"}, + { "common_name", "blue"}, + { "center_wavelength", 4.966} + }, + new JObject { + { "name", "B3"}, + { "common_name", "green"}, + { "center_wavelength", 5.6} + }, + new JObject { + { "name", "B4"}, + { "common_name", "red"}, + { "center_wavelength", 6.645} + }, + new JObject { + { "name", "B5"}, + { "center_wavelength", 7.039} + }, + new JObject { + { "name", "B6"}, + { "center_wavelength", 7.402} + }, + new JObject { + { "name", "B7"}, + { "center_wavelength", 7.825} + }, + new JObject { + { "name", "B8"}, + { "common_name", "nir"}, + { "center_wavelength", 8.351} + }, + new JObject { + { "name", "B8A"}, + { "center_wavelength", 8.648} + }, + new JObject { + { "name", "B9"}, + { "center_wavelength", 9.45} + }, + new JObject { + { "name", "B10"}, + { "center_wavelength", 1.3735} + }, + new JObject { + { "name", "B11"}, + { "common_name", "swir16"}, + { "center_wavelength", 1.6137} + }, + new JObject { + { "name", "B12"}, + { "common_name", "swir22"}, + { "center_wavelength", 2.2024} + } + }) + ); + + var json = JsonConvert.SerializeObject(collection); + + Console.WriteLine(json); + +``` + +## Documentation + +*Full Documentation shall be available soon* + +## Developing + +To ensure development libraries are installed, restore all dependencies + +``` +> dotnet restore src +``` + +### Unit Tests + +Unit tests are in the `src/DotNetStac.Test` folder. To run unit tests: + +``` +> dotnet test src +``` diff --git a/src/DotNetStac.Test/Examples/Example1Test.cs b/src/DotNetStac.Test/Examples/Example1Test.cs new file mode 100644 index 00000000..ba447613 --- /dev/null +++ b/src/DotNetStac.Test/Examples/Example1Test.cs @@ -0,0 +1,182 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Stac; +using Stac.Catalog; +using Stac.Collection; +using System; +using System.Collections.Generic; +using Xunit; + +namespace Stac.Test.Example +{ + public class Example1Test + { + [Fact] + public void Deserialize() + { + IStacCatalog catalog = (IStacCatalog)StacFactory.Load("https://cbers-stac-0-7.s3.amazonaws.com/CBERS4/MUX/027/069/catalog.json"); + + Console.Out.WriteLine(catalog.Id); + Console.Out.WriteLine(catalog.StacVersion); + + foreach (var item in catalog.GetItems().Values) + { + Console.Out.WriteLine(item.Id); + } + } + + [Fact] + public void CanSerializeSentinel2Sample() + { + StacExtent extent = new StacExtent(); + extent.Spatial = new StacSpatialExtent(-180, -56, 180, 83); + extent.Temporal = new StacTemporalExtent(DateTime.Parse("2015-06-23T00:00:00Z").ToUniversalTime(), null); + + StacCollection collection = new StacCollection("COPERNICUS/S2", + "Sentinel-2 is a wide-swath, high-resolution, multi-spectral\nimaging mission supporting Copernicus Land Monitoring studies,\nincluding the monitoring of vegetation, soil and water cover,\nas well as observation of inland waterways and coastal areas.\n\nThe Sentinel-2 data contain 13 UINT16 spectral bands representing\nTOA reflectance scaled by 10000. See the [Sentinel-2 User Handbook](https://sentinel.esa.int/documents/247904/685211/Sentinel-2_User_Handbook)\nfor details. In addition, three QA bands are present where one\n(QA60) is a bitmask band with cloud mask information. For more\ndetails, [see the full explanation of how cloud masks are computed.](https://sentinel.esa.int/web/sentinel/technical-guides/sentinel-2-msi/level-1c/cloud-masks)\n\nEach Sentinel-2 product (zip archive) may contain multiple\ngranules. Each granule becomes a separate Earth Engine asset.\nEE asset ids for Sentinel-2 assets have the following format:\nCOPERNICUS/S2/20151128T002653_20151128T102149_T56MNN. Here the\nfirst numeric part represents the sensing date and time, the\nsecond numeric part represents the product generation date and\ntime, and the final 6-character string is a unique granule identifier\nindicating its UTM grid reference (see [MGRS](https://en.wikipedia.org/wiki/Military_Grid_Reference_System)).\n\nFor more details on Sentinel-2 radiometric resoltuon, [see this page](https://earth.esa.int/web/sentinel/user-guides/sentinel-2-msi/resolutions/radiometric).\n", + extent); + + collection.Title = "Sentinel-2 MSI: MultiSpectral Instrument, Level-1C"; + + collection.Links.Add(StacLink.CreateSelfLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/COPERNICUS_S2.json"))); + collection.Links.Add(StacLink.CreateParentLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/catalog.json"))); + collection.Links.Add(StacLink.CreateRootLink(new Uri("https://storage.cloud.google.com/earthengine-test/catalog/catalog.json"))); + collection.Links.Add(new StacLink(new Uri("https://scihub.copernicus.eu/twiki/pub/SciHubWebPortal/TermsConditions/Sentinel_Data_Terms_and_Conditions.pdf"), "license", "Legal notice on the use of Copernicus Sentinel Data and Service Information", null)); + + collection.Keywords = new System.Collections.ObjectModel.Collection(new string[] { + "copernicus", + "esa", + "eu", + "msi", + "radiance", + "sentinel"}); + + collection.Providers = new System.Collections.ObjectModel.Collection( + new StacProvider[]{new StacProvider("European Union/ESA/Copernicus"){ + Roles = new List() { StacProviderRole.producer, StacProviderRole.licensor}, + Uri = new Uri("https://sentinel.esa.int/web/sentinel/user-guides/sentinel-2-msi") + }}); + + collection.Summaries.Add("datetime", + new StacSummaryStatsObject( + DateTime.Parse("2015-06-23T00:00:00Z").ToUniversalTime(), + DateTime.Parse("2019-07-10T13:44:56Z").ToUniversalTime() + ) + ); + + collection.Summaries.Add("platform", + new StacSummaryValueSet(new string[] { "sentinel-2a", "sentinel-2b" }) + ); + + collection.Summaries.Add("constellation", + new StacSummaryValueSet(new string[] { "sentinel-2" }) + ); + + collection.Summaries.Add("instruments", + new StacSummaryValueSet(new string[] { "msi" }) + ); + + collection.Summaries.Add("view:off_nadir", + new StacSummaryStatsObject( + 0.0, + 100 + ) + ); + + collection.Summaries.Add("view:sun_elevation", + new StacSummaryStatsObject( + 6.78, + 89.9 + ) + ); + + collection.Summaries.Add("sci:citation", + new StacSummaryValueSet(new string[] { "Copernicus Sentinel data [Year]" }) + ); + + collection.Summaries.Add("gsd", + new StacSummaryValueSet(new int[] { + 10, + 30, + 60 + }) + ); + + collection.Summaries.Add("proj:epsg", + new StacSummaryValueSet(new int[] + { 32601,32602,32603,32604,32605,32606,32607,32608,32609,32610,32611,32612,32613,32614,32615,32616,32617,32618,32619,32620,32621,32622,32623,32624,32625,32626,32627,32628,32629,32630,32631,32632,32633,32634,32635,32636,32637,32638,32639,32640,32641,32642,32643,32644,32645,32646,32647,32648,32649,32650,32651,32652,32653,32654,32655,32656,32657,32658,32659,32660} + ) + ); + + collection.Summaries.Add("eo:bands", + new StacSummaryValueSet(new JObject[] { + new JObject { + { "name", "B1" }, + { "common_name", "coastal" }, + { "center_wavelength", 4.439 } + }, + new JObject { + { "name", "B2"}, + { "common_name", "blue"}, + { "center_wavelength", 4.966} + }, + new JObject { + { "name", "B3"}, + { "common_name", "green"}, + { "center_wavelength", 5.6} + }, + new JObject { + { "name", "B4"}, + { "common_name", "red"}, + { "center_wavelength", 6.645} + }, + new JObject { + { "name", "B5"}, + { "center_wavelength", 7.039} + }, + new JObject { + { "name", "B6"}, + { "center_wavelength", 7.402} + }, + new JObject { + { "name", "B7"}, + { "center_wavelength", 7.825} + }, + new JObject { + { "name", "B8"}, + { "common_name", "nir"}, + { "center_wavelength", 8.351} + }, + new JObject { + { "name", "B8A"}, + { "center_wavelength", 8.648} + }, + new JObject { + { "name", "B9"}, + { "center_wavelength", 9.45} + }, + new JObject { + { "name", "B10"}, + { "center_wavelength", 1.3735} + }, + new JObject { + { "name", "B11"}, + { "common_name", "swir16"}, + { "center_wavelength", 1.6137} + }, + new JObject { + { "name", "B12"}, + { "common_name", "swir22"}, + { "center_wavelength", 2.2024} + } + }) + ); + + var json = JsonConvert.SerializeObject(collection); + + Console.WriteLine(json); + + } + + } +} \ No newline at end of file diff --git a/src/DotNetStac/Catalog/StacCatalog.Helper.cs b/src/DotNetStac/Catalog/StacCatalog.Helper.cs index a3c52ebe..e425eea5 100644 --- a/src/DotNetStac/Catalog/StacCatalog.Helper.cs +++ b/src/DotNetStac/Catalog/StacCatalog.Helper.cs @@ -18,7 +18,7 @@ public partial class StacCatalog public static async Task LoadUri(Uri uri) { - var catalog = await StacFactory.LoadUri(uri); + var catalog = await StacFactory.LoadUriAsync(uri); if (catalog is IStacCatalog) return (IStacCatalog)catalog; throw new InvalidOperationException(string.Format("This is not a STAC catalog {0}", catalog.Uri)); diff --git a/src/DotNetStac/Catalog/StacCatalog.Model.cs b/src/DotNetStac/Catalog/StacCatalog.Model.cs index ca672209..05918d77 100644 --- a/src/DotNetStac/Catalog/StacCatalog.Model.cs +++ b/src/DotNetStac/Catalog/StacCatalog.Model.cs @@ -14,7 +14,7 @@ namespace Stac.Catalog { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public partial class StacCatalog : IStacObject, IStacCatalogVersion, IStacCatalog, IInternalStacObject + public partial class StacCatalog : IStacObject, IStacCatalog, IInternalStacObject { private readonly string id; private Collection links; @@ -118,7 +118,7 @@ internal void OnDeserializedMethod(StreamingContext context) } } - IStacCatalogVersion IStacCatalogVersion.Upgrade() + public IStacObject Upgrade() { return this; } diff --git a/src/DotNetStac/Collection/StacCollection.Helper.cs b/src/DotNetStac/Collection/StacCollection.Helper.cs index f87bda76..9487e4af 100644 --- a/src/DotNetStac/Collection/StacCollection.Helper.cs +++ b/src/DotNetStac/Collection/StacCollection.Helper.cs @@ -37,7 +37,7 @@ internal static StacCollection LoadStacCollection(JToken jsonRoot) throw new NotSupportedException(string.Format("The document has a non supprted version: '{0}'.", jsonRoot["stac_version"].Value())); } - IStacCollectionVersion catalog = (IStacCollectionVersion)jsonRoot.ToObject(collectionType); + IStacObject catalog = (IStacObject)jsonRoot.ToObject(collectionType); while (catalog.GetType() != typeof(StacCollection)) { diff --git a/src/DotNetStac/Collection/StacCollection.Model.cs b/src/DotNetStac/Collection/StacCollection.Model.cs index a0c08eb8..f932b009 100644 --- a/src/DotNetStac/Collection/StacCollection.Model.cs +++ b/src/DotNetStac/Collection/StacCollection.Model.cs @@ -14,7 +14,7 @@ namespace Stac.Collection { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public partial class StacCollection : StacCatalog, IStacObject, Model.IStacCollectionVersion, IStacCollection + public partial class StacCollection : StacCatalog, IStacObject, IStacCollection { private string license; private StacExtent extent; @@ -77,10 +77,5 @@ public Collection Keywords } } - - IStacCollectionVersion IStacCollectionVersion.Upgrade() - { - return this; - } } } diff --git a/src/DotNetStac/DotNetStac.csproj b/src/DotNetStac/DotNetStac.csproj index 51708f11..175c66cf 100644 --- a/src/DotNetStac/DotNetStac.csproj +++ b/src/DotNetStac/DotNetStac.csproj @@ -1,13 +1,26 @@ - netstandard2.0 + <_ExtraTargetFrameworks Condition="'$(OS)' == 'Windows_NT' or '$(MSBuildRuntimeType)' == 'Mono'">net472 + netstandard2.0;$(RoslynPortableTargetFrameworks);$(_ExtraTargetFrameworks) + win;linux + DotNetStac + Terradue .Net library for working with any SpatioTemporal Asset Catalog + LICENSE + 0.2.0-beta + Emmanuel Mathot + Terradue + https://github.com/Terradue/DotNetStac + STAC;Terradue;Geo;Json - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/src/DotNetStac/IStacObject.cs b/src/DotNetStac/IStacObject.cs index 0302d007..c86087d3 100644 --- a/src/DotNetStac/IStacObject.cs +++ b/src/DotNetStac/IStacObject.cs @@ -15,5 +15,7 @@ public interface IStacObject Collection StacExtensions { get; } Collection Links { get; } + + IStacObject Upgrade(); } } \ No newline at end of file diff --git a/src/DotNetStac/Item/StacItem.Helper.cs b/src/DotNetStac/Item/StacItem.Helper.cs index ede7c693..efa1a63f 100644 --- a/src/DotNetStac/Item/StacItem.Helper.cs +++ b/src/DotNetStac/Item/StacItem.Helper.cs @@ -22,7 +22,7 @@ public partial class StacItem public static async Task LoadUri(Uri uri) { - var catalog = await StacFactory.LoadUri(uri); + var catalog = await StacFactory.LoadUriAsync(uri); if (catalog is IStacItem) return (IStacItem)catalog; throw new InvalidOperationException(string.Format("This is not a STAC item {0}", catalog.Uri)); diff --git a/src/DotNetStac/Item/StacItem.Model.cs b/src/DotNetStac/Item/StacItem.Model.cs index 04d205fc..6632ff5d 100644 --- a/src/DotNetStac/Item/StacItem.Model.cs +++ b/src/DotNetStac/Item/StacItem.Model.cs @@ -13,7 +13,7 @@ namespace Stac.Item { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - public partial class StacItem : GeoJSON.Net.Feature.Feature, IStacObject, IStacItemVersion, IInternalStacObject + public partial class StacItem : GeoJSON.Net.Feature.Feature, IStacObject, IInternalStacObject { private Collection links; @@ -149,7 +149,7 @@ public Itenso.TimePeriod.ITimePeriod DateTime public Uri Uri { get => sourceUri; set => sourceUri = value; } - IStacItemVersion IStacItemVersion.Upgrade() + public IStacObject Upgrade() { return this; } diff --git a/src/DotNetStac/Model/IStacCatalogVersion.cs b/src/DotNetStac/Model/IStacCatalogVersion.cs deleted file mode 100644 index fa58872b..00000000 --- a/src/DotNetStac/Model/IStacCatalogVersion.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Stac.Model -{ - internal interface IStacCatalogVersion : IStacObject - { - IStacCatalogVersion Upgrade(); - } -} \ No newline at end of file diff --git a/src/DotNetStac/Model/IStacCollectionVersion.cs b/src/DotNetStac/Model/IStacCollectionVersion.cs deleted file mode 100644 index ea43d7b8..00000000 --- a/src/DotNetStac/Model/IStacCollectionVersion.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Stac.Model -{ - internal interface IStacCollectionVersion : IStacObject - { - IStacCollectionVersion Upgrade(); - } -} \ No newline at end of file diff --git a/src/DotNetStac/Model/IStacItemVersion.cs b/src/DotNetStac/Model/IStacItemVersion.cs deleted file mode 100644 index 2c64971f..00000000 --- a/src/DotNetStac/Model/IStacItemVersion.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Stac.Item; - -namespace Stac.Model -{ - internal interface IStacItemVersion : IStacObject - { - IStacItemVersion Upgrade(); - - } -} \ No newline at end of file diff --git a/src/DotNetStac/Model/v060/StacCatalog.cs b/src/DotNetStac/Model/v060/StacCatalog.cs index 3ca86261..6c2e840e 100644 --- a/src/DotNetStac/Model/v060/StacCatalog.cs +++ b/src/DotNetStac/Model/v060/StacCatalog.cs @@ -13,7 +13,7 @@ namespace Stac.Model.v060 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacCatalog060 : IStacObject, IStacCatalogVersion, IStacCatalog, IInternalStacObject + internal class StacCatalog060 : IStacObject, IStacCatalog, IInternalStacObject { private readonly string id; private Collection links; @@ -105,7 +105,7 @@ public string Description public Uri Uri { get => sourceUri; set => sourceUri = value; } - public IStacCatalogVersion Upgrade() + public virtual IStacObject Upgrade() { var catalog = new v070.StacCatalog070(this.Id, this.Description, diff --git a/src/DotNetStac/Model/v060/StacCollection.cs b/src/DotNetStac/Model/v060/StacCollection.cs index e9cc00c1..2a004a2e 100644 --- a/src/DotNetStac/Model/v060/StacCollection.cs +++ b/src/DotNetStac/Model/v060/StacCollection.cs @@ -14,7 +14,7 @@ namespace Stac.Model.v060 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacCollection060 : StacCatalog060, IStacObject, IStacCollectionVersion, IStacCollection + internal class StacCollection060 : StacCatalog060, IStacObject, IStacCollection { private string license; private StacExtent060 extent; @@ -63,7 +63,7 @@ public Collection Keywords [JsonExtensionData] public Dictionary Properties { get; set; } - IStacCollectionVersion IStacCollectionVersion.Upgrade() + public override IStacObject Upgrade() { var collection = new v070.StacCollection070(this.Id, this.Description, diff --git a/src/DotNetStac/Model/v060/StacItem.cs b/src/DotNetStac/Model/v060/StacItem.cs index 52da2060..756ddb6a 100644 --- a/src/DotNetStac/Model/v060/StacItem.cs +++ b/src/DotNetStac/Model/v060/StacItem.cs @@ -11,7 +11,7 @@ namespace Stac.Model.v060 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacItem060 : GeoJSON.Net.Feature.Feature, IStacItemVersion, IStacObject, IStacItem + internal class StacItem060 : GeoJSON.Net.Feature.Feature, IStacObject, IStacItem { private Collection links; @@ -121,7 +121,7 @@ public Itenso.TimePeriod.ITimePeriod DateTime [JsonIgnore] public Collection StacExtensions => null; - public IStacItemVersion Upgrade() + public IStacObject Upgrade() { var item = new v070.StacItem070(this.Geometry, this.Properties, diff --git a/src/DotNetStac/Model/v070/StacCatalog.cs b/src/DotNetStac/Model/v070/StacCatalog.cs index 81a710ba..2176b385 100644 --- a/src/DotNetStac/Model/v070/StacCatalog.cs +++ b/src/DotNetStac/Model/v070/StacCatalog.cs @@ -14,7 +14,7 @@ namespace Stac.Model.v070 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacCatalog070 : IStacObject, IStacCatalogVersion, IStacCatalog, IInternalStacObject + internal class StacCatalog070 : IStacObject, IStacCatalog, IInternalStacObject { private readonly string id; private Collection links; @@ -108,7 +108,7 @@ public string Description public Uri Uri { get => sourceUri; set => sourceUri = value; } - public IStacCatalogVersion Upgrade() + public virtual IStacObject Upgrade() { var catalog = new Catalog.StacCatalog(this.Id, this.Description, diff --git a/src/DotNetStac/Model/v070/StacCollection.cs b/src/DotNetStac/Model/v070/StacCollection.cs index a971ee84..ae900eda 100644 --- a/src/DotNetStac/Model/v070/StacCollection.cs +++ b/src/DotNetStac/Model/v070/StacCollection.cs @@ -6,7 +6,7 @@ namespace Stac.Model.v070 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacCollection070 : StacCatalog070, IStacObject, IStacCollectionVersion, IStacCollection, IInternalStacObject + internal class StacCollection070 : StacCatalog070, IStacObject, IStacCollection, IInternalStacObject { private string license; private v060.StacExtent060 extent; @@ -67,7 +67,7 @@ public Collection Keywords } } - IStacCollectionVersion IStacCollectionVersion.Upgrade() + public override IStacObject Upgrade() { var collection = new Collection.StacCollection(this.Id, this.Description, this.extent.Upgrade(), this.Links); diff --git a/src/DotNetStac/Model/v070/StacItem.cs b/src/DotNetStac/Model/v070/StacItem.cs index cba99016..7847abc0 100644 --- a/src/DotNetStac/Model/v070/StacItem.cs +++ b/src/DotNetStac/Model/v070/StacItem.cs @@ -11,7 +11,7 @@ namespace Stac.Model.v070 { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] - internal class StacItem070 : GeoJSON.Net.Feature.Feature, IStacItemVersion, IStacObject, IStacItem, IInternalStacObject + internal class StacItem070 : GeoJSON.Net.Feature.Feature, IStacObject, IStacItem, IInternalStacObject { private Collection links; @@ -118,7 +118,7 @@ public Itenso.TimePeriod.ITimePeriod DateTime public Collection StacExtensions { get => null; set { } } - public IStacItemVersion Upgrade() + public IStacObject Upgrade() { var item = new Item.StacItem(this.Geometry, this.Properties, diff --git a/src/DotNetStac/StacExtensionsHelper.cs b/src/DotNetStac/StacExtensionsHelper.cs index b1f17103..64f2c647 100644 --- a/src/DotNetStac/StacExtensionsHelper.cs +++ b/src/DotNetStac/StacExtensionsHelper.cs @@ -48,7 +48,7 @@ public static IEnumerable GetItemLinks(this IStacObject stacObject, bo public static StacItem UpgradeToCurrentVersion(this IStacItem item1) { - IStacItemVersion item = (IStacItemVersion)item1; + IStacObject item = (IStacObject)item1; while (!(item is Item.StacItem)) { item = item.Upgrade(); @@ -58,7 +58,7 @@ public static StacItem UpgradeToCurrentVersion(this IStacItem item1) public static StacCatalog UpgradeToCurrentVersion(this IStacCatalog catalog1) { - IStacCatalogVersion catalog = (IStacCatalogVersion)catalog1; + IStacObject catalog = (IStacObject)catalog1; while (!(catalog is StacCatalog)) { catalog = catalog.Upgrade(); diff --git a/src/DotNetStac/StacFactory.cs b/src/DotNetStac/StacFactory.cs index 5156f582..4e523e20 100644 --- a/src/DotNetStac/StacFactory.cs +++ b/src/DotNetStac/StacFactory.cs @@ -11,7 +11,7 @@ namespace Stac { public class StacFactory { - public static async Task LoadUri(Uri uri) + public static async Task LoadUriAsync(Uri uri) { WebClient client = new WebClient(); return await client.DownloadStringTaskAsync(uri).ContinueWith(json => @@ -25,6 +25,11 @@ public static async Task LoadUri(Uri uri) }); } + public static IStacObject Load(string uri) + { + return LoadUriAsync(new Uri(uri)).Result; + } + public static async Task LoadStacLink(StacLink link) { WebClient client = new WebClient(); From 0d74d7fca551a2ac3a032e456f43a564e03ef9d6 Mon Sep 17 00:00:00 2001 From: Emmanuel Mathot Date: Thu, 20 Aug 2020 11:22:27 +0200 Subject: [PATCH 19/21] updated readme --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2ba4c933..6044735a 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

-.Net library for working with any Spatio Temporal Asset Catalog (STAC) +.Net library for working with any Spatio Temporal Asset Catalog (STAC) ![](docs/logo/logo-wide.png) @@ -14,7 +14,7 @@ [![Build Status](https://travis-ci.com/Terradue/DotNetStac.svg?branch=develop)](https://travis-ci.com/Terradue/DotNetStac) [![NuGet](https://img.shields.io/nuget/v/:DotNetStac)](https://www.nuget.org/packages/DotNetStac/) - [![Gitter](https://img.shields.io/gitter/room/dotnet/BenchmarkDotNet?color=yellow)](https://gitter.im/dotnet/BenchmarkDotNet) + [![Gitter](https://img.shields.io/gitter/room/SpatioTemporal-Asset-Catalog/Lobby?color=yellow)](https://gitter.im/SpatioTemporal-Asset-Catalog/Lobby) [![License](https://img.shields.io/badge/license-AGPL3-blue.svg)](LICENSE)

@@ -29,7 +29,7 @@ Developing -**DotNetStac** helps you to work with STAC ([catalog](https://github.com/radiantearth/stac-spec/tree/master/catalog-spec), [collection](https://github.com/radiantearth/stac-spec/tree/master/collection-spec), [item](https://github.com/radiantearth/stac-spec/tree/master/catalog-spec)) +**DotNetStac** helps you to work with [STAC](https://stacspec.org) ([catalog](https://github.com/radiantearth/stac-spec/tree/master/catalog-spec), [collection](https://github.com/radiantearth/stac-spec/tree/master/collection-spec), [item](https://github.com/radiantearth/stac-spec/tree/master/catalog-spec)) In a nutshell, the library allows manipulating STAC JSON documents (Serialization/Deserialization using [Newtonsoft.JSON](https://www.newtonsoft.com/json)) with properties represented in enhanced objects such as geometries, time stamp/period/span, numerical values and many more via STAC extension plugins engine. From 021395e048e60423132f35809f752a84d19fe2d2 Mon Sep 17 00:00:00 2001 From: Emmanuel Mathot Date: Thu, 20 Aug 2020 11:24:06 +0200 Subject: [PATCH 20/21] version 0.2.0-beta --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6044735a..ecabce4d 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@

[![Build Status](https://travis-ci.com/Terradue/DotNetStac.svg?branch=develop)](https://travis-ci.com/Terradue/DotNetStac) - [![NuGet](https://img.shields.io/nuget/v/:DotNetStac)](https://www.nuget.org/packages/DotNetStac/) + [![NuGet](https://img.shields.io/nuget/vpre/DotNetStac)](https://www.nuget.org/packages/DotNetStac/) [![Gitter](https://img.shields.io/gitter/room/SpatioTemporal-Asset-Catalog/Lobby?color=yellow)](https://gitter.im/SpatioTemporal-Asset-Catalog/Lobby) [![License](https://img.shields.io/badge/license-AGPL3-blue.svg)](LICENSE) From 8dc0eb7e812dfe1f99a52c57ef5a36d50f24cd13 Mon Sep 17 00:00:00 2001 From: Emmanuel Mathot Date: Thu, 20 Aug 2020 11:25:30 +0200 Subject: [PATCH 21/21] some update --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ecabce4d..8a4672dc 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

-.Net library for working with any Spatio Temporal Asset Catalog (STAC) +.Net library for working with Spatio Temporal Asset Catalogs (STAC) ![](docs/logo/logo-wide.png)