From ed011c3ab7650dd46de68de986ca245d1e5cfc69 Mon Sep 17 00:00:00 2001 From: Francois Prunayre Date: Tue, 19 Sep 2023 13:30:36 +0200 Subject: [PATCH] Formatter / Remove unused Groovy mode. Groovy formatter is unused and unmaintained in GeoNetwork. It is also unused in the (only one?) project which used it (geocat.ch) since 2 years now. This PR propose to remove it. --- code_quality/findbugs-excludes.xml | 9 - pom.xml | 7 - schemas-test/pom.xml | 4 - .../java/cswrecord/FullViewFormatterTest.java | 108 --- .../java/cswrecord/XmlViewFormatterTest.java | 107 --- .../dublincore/FullViewFormatterTest.java | 108 --- .../java/dublincore/XmlViewFormatterTest.java | 107 --- .../AbstractFullViewFormatterTest.java | 170 ----- .../FullViewFormatterLocalizationTest.java | 68 -- .../FullViewFormatterServiceTest.java | 72 -- .../java/iso19139/FullViewFormatterTest.java | 107 --- .../test/java/iso19139/IsoMatchersTest.java | 92 --- .../java/iso19139/XmlViewFormatterTest.java | 107 --- .../src/test/resources/cswrecord/example.xml | 62 -- .../src/test/resources/dublincore/example.xml | 40 -- .../formatter/full_view/view.groovy | 24 - .../groovy/cswrecord/Handlers.groovy | 102 --- .../formatter/full_view/view.groovy | 24 - .../groovy/dublincore/Handlers.groovy | 142 ---- .../iso19110/formatter/full_view/view.groovy | 28 - .../formatter/groovy/iso19110/Handlers.groovy | 59 -- .../iso19139/formatter/full_view/view.groovy | 30 - .../groovy/iso19139/Functions.groovy | 109 ---- .../formatter/groovy/iso19139/Handlers.groovy | 464 ------------- .../formatter/groovy/iso19139/Matchers.groovy | 93 --- .../groovy/iso19139/SummaryFactory.groovy | 232 ------- .../iso19139/formatter/html/citation.html | 40 -- .../formatter/html/coupled-resources.html | 35 - .../iso19139/formatter/html/format.html | 47 -- .../formatter/html/graphic-overview.html | 35 - .../iso19139/formatter/html/keyword.html | 33 - .../iso19139/formatter/html/locale.html | 30 - .../formatter/html/online-resource.html | 30 - .../formatter/html/single-resource.html | 32 - .../iso19139/formatter/loc/ca-strings.json | 30 - .../iso19139/formatter/loc/en-strings.json | 30 - .../iso19139/formatter/loc/es-strings.json | 30 - .../iso19139/formatter/loc/fr-strings.json | 26 - .../iso19139/formatter/loc/ge-strings.json | 26 - .../iso19139/formatter/loc/it-strings.json | 26 - .../iso19139/formatter/loc/ko-strings.json | 8 - .../iso19139/formatter/loc/nl-strings.json | 8 - .../iso19139/formatter/loc/sk-strings.json | 30 - .../formatter/partial_view/config.properties | 24 - .../formatter/partial_view/view.groovy | 28 - schemas/pom.xml | 11 - services/pom.xml | 5 - .../formatters/AbstractFormatService.java | 7 +- .../{groovy => }/CurrentLanguageHolder.java | 3 +- .../records/formatters/FormatterAdminApi.java | 9 - .../api/records/formatters/FormatterApi.java | 8 +- .../formatters/FormatterConstants.java | 2 - .../records/formatters/GroovyFormatter.java | 220 ------- .../formatters/SchemaLocalizations.java | 57 +- .../formatters/groovy/Environment.java | 164 ----- .../formatters/groovy/EnvironmentImpl.java | 257 -------- .../formatters/groovy/EnvironmentProxy.java | 173 ----- .../records/formatters/groovy/Functions.java | 218 ------- .../records/formatters/groovy/Handler.java | 125 ---- .../groovy/HandlerFunctionSelect.java | 68 -- .../formatters/groovy/HandlerNameSelect.java | 56 -- .../formatters/groovy/HandlerPathSelect.java | 61 -- .../formatters/groovy/HandlerResult.java | 32 - .../records/formatters/groovy/Handlers.java | 614 ------------------ .../records/formatters/groovy/Logging.java | 93 --- .../records/formatters/groovy/MapConfig.java | 92 --- .../api/records/formatters/groovy/Mode.java | 69 -- .../records/formatters/groovy/ParamValue.java | 58 -- .../records/formatters/groovy/Selectable.java | 117 ---- .../formatters/groovy/SkipElement.java | 66 -- .../formatters/groovy/SkipElementClosure.java | 52 -- .../formatters/groovy/SkipElementPattern.java | 47 -- .../api/records/formatters/groovy/Sorter.java | 56 -- .../groovy/SorterFunctionSelect.java | 54 -- .../formatters/groovy/SorterNameSelect.java | 51 -- .../formatters/groovy/SorterPathSelect.java | 57 -- .../formatters/groovy/StartEndHandler.java | 48 -- .../formatters/groovy/TransformEngine.java | 152 ----- .../groovy/TransformationContext.java | 87 --- .../formatters/groovy/Transformer.java | 126 ---- .../groovy/template/AttributesFiltered.java | 114 ---- .../groovy/template/FileResult.java | 59 -- .../groovy/template/FilterCapitalize.java | 54 -- .../groovy/template/FilterEscapeXmlAttrs.java | 43 -- .../template/FilterEscapeXmlContent.java | 43 -- .../groovy/template/FilterGenerateUUID.java | 47 -- .../groovy/template/FilterLastUUID.java | 48 -- .../groovy/template/FilterLowerCase.java | 40 -- .../groovy/template/FilterUpperCase.java | 40 -- .../groovy/template/SimpleTNode.java | 44 -- .../formatters/groovy/template/TNode.java | 168 ----- .../groovy/template/TNodeFactory.java | 86 --- .../template/TNodeFactoryByAttName.java | 48 -- .../groovy/template/TNodeFactoryIf.java | 60 -- .../groovy/template/TNodeFactoryInclude.java | 97 --- .../groovy/template/TNodeFactoryRepeat.java | 76 --- .../template/TNodeFactoryTransclude.java | 132 ---- .../template/TNodeFactoryTranslate.java | 74 --- .../formatters/groovy/template/TNodeIf.java | 184 ------ .../groovy/template/TNodeRepeatIter.java | 140 ---- .../groovy/template/TNodeRepeatMap.java | 109 ---- .../groovy/template/TNodeTextContent.java | 51 -- .../groovy/template/TNodeTranslate.java | 160 ----- .../groovy/template/TRenderContext.java | 255 -------- .../groovy/template/TemplateCache.java | 228 ------- .../groovy/template/TemplateException.java | 43 -- .../groovy/template/TemplateParser.java | 185 ------ .../groovy/template/TemplateType.java | 61 -- .../formatters/groovy/template/TextBlock.java | 55 -- .../groovy/template/TextContent.java | 33 - .../groovy/template/TextContentFilter.java | 46 -- .../groovy/template/TextContentParser.java | 82 --- .../template/TextContentReplacement.java | 61 -- .../groovy/template/TextContentStatic.java | 45 -- .../groovy/util/AssociatedLink.java | 75 --- .../formatters/groovy/util/Direction.java | 53 -- .../records/formatters/groovy/util/Link.java | 85 --- .../formatters/groovy/util/LinkBlock.java | 121 ---- .../formatters/groovy/util/LinkType.java | 108 --- .../formatters/groovy/util/NavBarItem.java | 103 --- .../formatters/groovy/util/Summary.java | 225 ------- .../formatters/AbstractFormatterTest.java | 58 +- .../FormatterApiIntegrationTest.java | 177 +---- .../api/records/formatters/ResourceTest.java | 4 - .../SchemaLocalizationsIntegrationTest.java | 2 +- .../formatters/SchemaLocalizationsTest.java | 28 +- .../formatters/XmlViewFormatterTest.java | 120 ---- .../formatters/groovy/FunctionsTest.java | 185 ------ .../formatters/groovy/HandlersTest.java | 86 --- .../template/AbstractTemplateParserTest.java | 57 -- .../groovy/template/FilterCapitalizeTest.java | 36 - .../template/FilterEscapeXmlAttrsTest.java | 36 - .../template/FilterEscapeXmlContentTest.java | 36 - .../groovy/template/FilterLowerCaseTest.java | 36 - .../groovy/template/FilterUUIDTest.java | 63 -- .../groovy/template/FilterUpperCaseTest.java | 36 - .../groovy/template/TNodeIfTest.java | 224 ------- .../groovy/template/TNodeIncludeTest.java | 88 --- .../groovy/template/TNodeRepeatIterTest.java | 48 -- .../groovy/template/TNodeRepeatMapTest.java | 47 -- .../groovy/template/TNodeRepeatTest.java | 135 ---- .../groovy/template/TNodeTranscludeTest.java | 101 --- .../groovy/template/TNodeTranslateTest.java | 73 --- .../groovy/template/TRenderContextTest.java | 196 ------ .../TemplateCacheIntegrationTest.java | 86 --- .../groovy/template/TemplateCacheTest.java | 107 --- .../groovy/template/TemplateParserTest.java | 88 --- .../template/TextContentParserTest.java | 99 --- .../template/TextContentReplacementTest.java | 69 -- .../view.groovy | 31 - .../Iso19139Functions.groovy | 28 - .../groovy-test-formatter/block.html | 28 - .../groovy-test-formatter/dublin-core-groovy | 6 - .../groovy-test-formatter/view.groovy | 354 ---------- .../formatters/groovy/SharedFunctions.groovy | 28 - .../formatters/groovy/online-resource.html | 29 - .../groovy/template/if-children-only.html | 28 - .../template/include-template-replace.html | 26 - .../groovy/template/include-template.html | 26 - .../multiple-directives-per-el-template.html | 27 - .../groovy/template/non-empty-template.html | 31 - .../template/repeat-object-template.html | 26 - .../repeat-only-children-template.html | 31 - .../groovy/template/repeat-template.html | 29 - .../groovy/template/template-spacing.html | 28 - .../template/transclude-template-replace.html | 29 - .../groovy/template/transclude-template.html | 29 - .../formatters/groovy/template/translate.html | 35 - .../groovy/template/uuid-filter-template.html | 26 - .../formatter-dir/loc/en-other-strings.json | 4 - .../formatter-dir/loc/en-strings.json | 4 - .../formatter/loc/en-more-strings.json | 4 - .../formatter/loc/en-strings.json | 4 - .../schema-dir/formatter/config.properties | 24 - .../schema-dir/formatter/loc/en-strings.json | 3 - .../api/records/formatters/xml_view/test.xml | 27 - .../resources/catalog/style/gn_metadata.less | 11 - .../formatter/groovy/common/Functions.groovy | 69 -- .../formatter/groovy/common/Handlers.groovy | 279 -------- .../formatter/groovy/common/Matchers.groovy | 11 - .../hierarchy_view/config.properties | 1 - .../data/formatter/hierarchy_view/view.groovy | 3 - .../data/formatter/html/2-level-entry.html | 15 - .../data/data/formatter/html/associated.html | 54 -- .../data/data/formatter/html/bbox.html | 36 - .../data/data/formatter/html/links.html | 4 - .../data/data/formatter/html/list-entry.html | 7 - .../data/data/formatter/html/single-link.html | 31 - .../data/data/formatter/html/text-el.html | 4 - .../data/data/formatter/html/url-el.html | 4 - .../data/data/formatter/html/view-header.html | 86 --- .../data/data/formatter/html/wikitext-el.html | 4 - .../formatter/xml_view/highlight-json-xml.js | 1 - .../data/formatter/xml_view/highlightjs.css | 153 ----- .../data/data/formatter/xml_view/view.groovy | 19 - workers/pom.xml | 5 - 196 files changed, 15 insertions(+), 14167 deletions(-) delete mode 100644 schemas-test/src/test/java/cswrecord/FullViewFormatterTest.java delete mode 100644 schemas-test/src/test/java/cswrecord/XmlViewFormatterTest.java delete mode 100644 schemas-test/src/test/java/dublincore/FullViewFormatterTest.java delete mode 100644 schemas-test/src/test/java/dublincore/XmlViewFormatterTest.java delete mode 100644 schemas-test/src/test/java/iso19139/AbstractFullViewFormatterTest.java delete mode 100644 schemas-test/src/test/java/iso19139/FullViewFormatterLocalizationTest.java delete mode 100644 schemas-test/src/test/java/iso19139/FullViewFormatterServiceTest.java delete mode 100644 schemas-test/src/test/java/iso19139/FullViewFormatterTest.java delete mode 100644 schemas-test/src/test/java/iso19139/IsoMatchersTest.java delete mode 100644 schemas-test/src/test/java/iso19139/XmlViewFormatterTest.java delete mode 100644 schemas-test/src/test/resources/cswrecord/example.xml delete mode 100644 schemas-test/src/test/resources/dublincore/example.xml delete mode 100644 schemas/csw-record/src/main/plugin/csw-record/formatter/full_view/view.groovy delete mode 100644 schemas/csw-record/src/main/plugin/csw-record/formatter/groovy/cswrecord/Handlers.groovy delete mode 100644 schemas/dublin-core/src/main/plugin/dublin-core/formatter/full_view/view.groovy delete mode 100644 schemas/dublin-core/src/main/plugin/dublin-core/formatter/groovy/dublincore/Handlers.groovy delete mode 100644 schemas/iso19110/src/main/plugin/iso19110/formatter/full_view/view.groovy delete mode 100644 schemas/iso19110/src/main/plugin/iso19110/formatter/groovy/iso19110/Handlers.groovy delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/full_view/view.groovy delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Functions.groovy delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Handlers.groovy delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Matchers.groovy delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/SummaryFactory.groovy delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/html/citation.html delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/html/coupled-resources.html delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/html/format.html delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/html/graphic-overview.html delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/html/keyword.html delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/html/locale.html delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/html/online-resource.html delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/html/single-resource.html delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ca-strings.json delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/loc/en-strings.json delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/loc/es-strings.json delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/loc/fr-strings.json delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ge-strings.json delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/loc/it-strings.json delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ko-strings.json delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/loc/nl-strings.json delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/loc/sk-strings.json delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/partial_view/config.properties delete mode 100644 schemas/iso19139/src/main/plugin/iso19139/formatter/partial_view/view.groovy rename services/src/main/java/org/fao/geonet/api/records/formatters/{groovy => }/CurrentLanguageHolder.java (95%) delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/GroovyFormatter.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Environment.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/EnvironmentImpl.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/EnvironmentProxy.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Functions.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Handler.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerFunctionSelect.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerNameSelect.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerPathSelect.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerResult.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Handlers.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Logging.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/MapConfig.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Mode.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/ParamValue.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Selectable.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElement.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElementClosure.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElementPattern.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Sorter.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterFunctionSelect.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterNameSelect.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterPathSelect.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/StartEndHandler.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/TransformEngine.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/TransformationContext.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Transformer.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/AttributesFiltered.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FileResult.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterCapitalize.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlAttrs.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlContent.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterGenerateUUID.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLastUUID.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLowerCase.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUpperCase.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/SimpleTNode.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNode.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactory.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryByAttName.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryIf.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryInclude.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryRepeat.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryTransclude.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryTranslate.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIf.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatIter.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatMap.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTextContent.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranslate.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TRenderContext.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCache.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateException.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateParser.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateType.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextBlock.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContent.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentFilter.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentParser.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentReplacement.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentStatic.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/AssociatedLink.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Direction.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Link.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/LinkBlock.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/LinkType.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/NavBarItem.java delete mode 100644 services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Summary.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/XmlViewFormatterTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/FunctionsTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/HandlersTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/AbstractTemplateParserTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterCapitalizeTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlAttrsTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlContentTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLowerCaseTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUUIDTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUpperCaseTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIfTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIncludeTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatIterTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatMapTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranscludeTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranslateTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TRenderContextTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCacheIntegrationTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCacheTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateParserTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentParserTest.java delete mode 100644 services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentReplacementTest.java delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-illegal-env-access-formatter/view.groovy delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/Iso19139Functions.groovy delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/block.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/dublin-core-groovy delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/view.groovy delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/SharedFunctions.groovy delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/online-resource.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/if-children-only.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/include-template-replace.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/include-template.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/multiple-directives-per-el-template.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/non-empty-template.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-object-template.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-only-children-template.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-template.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/template-spacing.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/transclude-template-replace.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/transclude-template.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/translate.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/uuid-filter-template.html delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/formatter-dir/loc/en-other-strings.json delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/formatter-dir/loc/en-strings.json delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/parent-schema/formatter/loc/en-more-strings.json delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/parent-schema/formatter/loc/en-strings.json delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/schema-dir/formatter/config.properties delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/schema-dir/formatter/loc/en-strings.json delete mode 100644 services/src/test/resources/org/fao/geonet/api/records/formatters/xml_view/test.xml delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Functions.groovy delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Handlers.groovy delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Matchers.groovy delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/hierarchy_view/config.properties delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/hierarchy_view/view.groovy delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/2-level-entry.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/associated.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/bbox.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/links.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/list-entry.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/single-link.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/text-el.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/url-el.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/view-header.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/html/wikitext-el.html delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/xml_view/highlight-json-xml.js delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/xml_view/highlightjs.css delete mode 100644 web/src/main/webapp/WEB-INF/data/data/formatter/xml_view/view.groovy diff --git a/code_quality/findbugs-excludes.xml b/code_quality/findbugs-excludes.xml index d04d3b14941e..6e225396aef7 100644 --- a/code_quality/findbugs-excludes.xml +++ b/code_quality/findbugs-excludes.xml @@ -230,15 +230,6 @@ - - - - - - - - - diff --git a/pom.xml b/pom.xml index 60cd62174003..3be41e4fbc40 100644 --- a/pom.xml +++ b/pom.xml @@ -386,19 +386,12 @@ - org.jsoup jsoup 1.15.3 - - org.codehaus.groovy - groovy-all - 2.4.21 - - com.googlecode.juniversalchardet diff --git a/schemas-test/pom.xml b/schemas-test/pom.xml index 08b792e06849..10ffc41fddba 100644 --- a/schemas-test/pom.xml +++ b/schemas-test/pom.xml @@ -36,10 +36,6 @@ Tests for schema plugins - - org.codehaus.groovy - groovy-all - ${project.groupId} gn-services diff --git a/schemas-test/src/test/java/cswrecord/FullViewFormatterTest.java b/schemas-test/src/test/java/cswrecord/FullViewFormatterTest.java deleted file mode 100644 index 3b2dc954e2e8..000000000000 --- a/schemas-test/src/test/java/cswrecord/FullViewFormatterTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package cswrecord; - -import com.google.common.collect.Lists; - -import org.fao.geonet.api.records.formatters.AbstractFormatterTest; -import org.fao.geonet.utils.Xml; -import org.jdom.Content; -import org.jdom.Element; -import org.jdom.Text; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.context.request.ServletWebRequest; - -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import static org.fao.geonet.api.records.formatters.FormatterWidth._100; - -/** - * @author Jesse on 10/17/2014. - */ -public class FullViewFormatterTest extends AbstractFormatterTest { - - // TODOES - @Ignore - @Test - public void testBasicFormat() throws Exception { - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession(); - request.addParameter("html", "true"); - - final String formatterId = "full_view"; - -// measureFormatterPerformance(request, formatterId); - - final MockHttpServletResponse response = new MockHttpServletResponse(); - formatService.exec("eng", "html", "" + id, null, formatterId, "true", false, _100, new ServletWebRequest(request, response)); - final String view = response.getContentAsString(); -// Files.write(view, new File("e:/tmp/view.html"), Constants.CHARSET); - - List excludes = new ArrayList<>(); - - final Element xmlEl = Xml.loadString(xml, false); - final List text = Lists.newArrayList(Xml.selectNodes(xmlEl, "*//text()")); - - StringBuilder missingStrings = new StringBuilder(); - for (Object t : text) { - Text textEl = (Text) t; - final String requiredText = textEl.getTextTrim(); - if (!requiredText.isEmpty() && !view.contains(requiredText)) { - final String path = getXPath(textEl).trim(); - if (!excludes.contains(path)) { - missingStrings.append("\n").append(path).append(" -> ").append(requiredText); - } - } - } - - if (missingStrings.length() > 0) { - throw new AssertionError("The following text elements are missing from the view:" + missingStrings); - } - } - - private String getXPath(Content el) { - String path = ""; - if (el.getParentElement() != null) { - path = getXPath(el.getParentElement()); - } - if (el instanceof Element) { - return path + " > " + ((Element) el).getQualifiedName(); - } else { - return path + " > " + el.getClass().getSimpleName(); - } - } - - @Override - protected File getTestMetadataFile() throws Exception { - final URL mdFile = FullViewFormatterTest.class.getResource("/cswrecord/example.xml"); - return new File(mdFile.toURI()); - } -} diff --git a/schemas-test/src/test/java/cswrecord/XmlViewFormatterTest.java b/schemas-test/src/test/java/cswrecord/XmlViewFormatterTest.java deleted file mode 100644 index f990ffbea9b4..000000000000 --- a/schemas-test/src/test/java/cswrecord/XmlViewFormatterTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package cswrecord; - -import com.google.common.collect.Lists; - -import org.fao.geonet.api.records.formatters.AbstractFormatterTest; -import org.fao.geonet.utils.Xml; -import org.jdom.Content; -import org.jdom.Element; -import org.jdom.Text; -import org.junit.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.context.request.ServletWebRequest; - -import java.io.File; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.List; - -import static org.fao.geonet.api.records.formatters.FormatterWidth._100; - -/** - * @author Jesse on 10/17/2014. - */ -public class XmlViewFormatterTest extends AbstractFormatterTest { - - @Test - public void testBasicFormat() throws Exception { - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession(); - request.addParameter("html", "true"); - - final String formatterId = "xml_view"; - -// measureFormatterPerformance(request, formatterId); - - final MockHttpServletResponse response = new MockHttpServletResponse(); - formatService.exec("eng", "html", "" + id, null, formatterId, "true", false, _100, new ServletWebRequest(request, response)); - String view = response.getContentAsString(); -// Files.write(view, new File("e:/tmp/view.html"), Constants.CHARSET); - view = view.replaceAll("\\s+", " "); - - List excludes = Lists.newArrayList( - ); - - final Element xmlEl = Xml.loadString(xml, false); - final List text = Lists.newArrayList(Xml.selectNodes(xmlEl, "*//text()")); - - StringBuilder missingStrings = new StringBuilder(); - for (Object t : text) { - Text textEl = (Text) t; - final String requiredText = escapeXmlText(textEl.getTextTrim()); - if (!requiredText.isEmpty() && !view.contains(requiredText)) { - final String path = getXPath(textEl).trim(); - if (!excludes.contains(path)) { - missingStrings.append("\n").append(path).append(" -> ").append(requiredText); - } - } - } - - if (missingStrings.length() > 0) { - throw new AssertionError("The following text elements are missing from the view:" + missingStrings); - } - } - - private String getXPath(Content el) { - String path = ""; - if (el.getParentElement() != null) { - path = getXPath(el.getParentElement()); - } - if (el instanceof Element) { - return path + " > " + ((Element) el).getQualifiedName(); - } else { - return path + " > " + el.getClass().getSimpleName(); - } - } - - @Override - protected File getTestMetadataFile() throws URISyntaxException { - final URL mdFile = XmlViewFormatterTest.class.getResource("/cswrecord/example.xml"); - return new File(mdFile.toURI()); - } -} diff --git a/schemas-test/src/test/java/dublincore/FullViewFormatterTest.java b/schemas-test/src/test/java/dublincore/FullViewFormatterTest.java deleted file mode 100644 index 610af020e98c..000000000000 --- a/schemas-test/src/test/java/dublincore/FullViewFormatterTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package dublincore; - -import com.google.common.collect.Lists; - -import org.fao.geonet.api.records.formatters.AbstractFormatterTest; -import org.fao.geonet.utils.Xml; -import org.jdom.Content; -import org.jdom.Element; -import org.jdom.Text; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.context.request.ServletWebRequest; - -import java.io.File; -import java.net.URL; -import java.util.List; - -import static org.fao.geonet.api.records.formatters.FormatterWidth._100; - -/** - * @author Jesse on 10/17/2014. - */ -public class FullViewFormatterTest extends AbstractFormatterTest { - - // TODOES - @Ignore - @Test - public void testBasicFormat() throws Exception { - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession(); - request.addParameter("html", "true"); - - final String formatterId = "full_view"; - -// measureFormatterPerformance(request, formatterId); - - final MockHttpServletResponse response = new MockHttpServletResponse(); - formatService.exec("eng", "html", "" + id, null, formatterId, "true", false, _100, new ServletWebRequest(request, response)); - final String view = response.getContentAsString(); -// Files.write(view, new File("e:/tmp/view.html"), Constants.CHARSET); - - List excludes = Lists.newArrayList( - ); - - final Element xmlEl = Xml.loadString(xml, false); - final List text = Lists.newArrayList(Xml.selectNodes(xmlEl, "*//text()")); - - StringBuilder missingStrings = new StringBuilder(); - for (Object t : text) { - Text textEl = (Text) t; - final String requiredText = textEl.getTextTrim(); - if (!requiredText.isEmpty() && !view.contains(requiredText)) { - final String path = getXPath(textEl).trim(); - if (!excludes.contains(path)) { - missingStrings.append("\n").append(path).append(" -> ").append(requiredText); - } - } - } - - if (missingStrings.length() > 0) { - throw new AssertionError("The following text elements are missing from the view:" + missingStrings); - } - } - - private String getXPath(Content el) { - String path = ""; - if (el.getParentElement() != null) { - path = getXPath(el.getParentElement()); - } - if (el instanceof Element) { - return path + " > " + ((Element) el).getQualifiedName(); - } else { - return path + " > " + el.getClass().getSimpleName(); - } - } - - @Override - protected File getTestMetadataFile() throws Exception { - final URL mdFile = FullViewFormatterTest.class.getResource("/dublincore/example.xml"); - return new File(mdFile.toURI()); - } -} diff --git a/schemas-test/src/test/java/dublincore/XmlViewFormatterTest.java b/schemas-test/src/test/java/dublincore/XmlViewFormatterTest.java deleted file mode 100644 index 5b36dedd3536..000000000000 --- a/schemas-test/src/test/java/dublincore/XmlViewFormatterTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package dublincore; - -import com.google.common.collect.Lists; - -import org.fao.geonet.api.records.formatters.AbstractFormatterTest; -import org.fao.geonet.utils.Xml; -import org.jdom.Content; -import org.jdom.Element; -import org.jdom.Text; -import org.junit.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.context.request.ServletWebRequest; - -import java.io.File; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.List; - -import static org.fao.geonet.api.records.formatters.FormatterWidth._100; - -/** - * @author Jesse on 10/17/2014. - */ -public class XmlViewFormatterTest extends AbstractFormatterTest { - - @Test - public void testBasicFormat() throws Exception { - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession(); - request.addParameter("html", "true"); - - final String formatterId = "xml_view"; - -// measureFormatterPerformance(request, formatterId); - - final MockHttpServletResponse response = new MockHttpServletResponse(); - formatService.exec("eng", "html", "" + id, null, formatterId, "true", false, _100, new ServletWebRequest(request, response)); - String view = response.getContentAsString(); -// Files.write(view, new File("e:/tmp/view.html"), Constants.CHARSET); - view = view.replaceAll("\\s+", " "); - - List excludes = Lists.newArrayList( - ); - - final Element xmlEl = Xml.loadString(xml, false); - final List text = Lists.newArrayList(Xml.selectNodes(xmlEl, "*//text()")); - - StringBuilder missingStrings = new StringBuilder(); - for (Object t : text) { - Text textEl = (Text) t; - final String requiredText = escapeXmlText(textEl.getTextTrim()); - if (!requiredText.isEmpty() && !view.contains(requiredText)) { - final String path = getXPath(textEl).trim(); - if (!excludes.contains(path)) { - missingStrings.append("\n").append(path).append(" -> ").append(requiredText); - } - } - } - - if (missingStrings.length() > 0) { - throw new AssertionError("The following text elements are missing from the view:" + missingStrings); - } - } - - private String getXPath(Content el) { - String path = ""; - if (el.getParentElement() != null) { - path = getXPath(el.getParentElement()); - } - if (el instanceof Element) { - return path + " > " + ((Element) el).getQualifiedName(); - } else { - return path + " > " + el.getClass().getSimpleName(); - } - } - - @Override - protected File getTestMetadataFile() throws URISyntaxException { - final URL mdFile = XmlViewFormatterTest.class.getResource("/dublincore/example.xml"); - return new File(mdFile.toURI()); - } -} diff --git a/schemas-test/src/test/java/iso19139/AbstractFullViewFormatterTest.java b/schemas-test/src/test/java/iso19139/AbstractFullViewFormatterTest.java deleted file mode 100644 index a15bede11d07..000000000000 --- a/schemas-test/src/test/java/iso19139/AbstractFullViewFormatterTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139; - -import com.google.common.collect.Lists; -import org.fao.geonet.api.records.formatters.AbstractFormatterTest; -import org.fao.geonet.api.records.formatters.FormatType; -import org.fao.geonet.api.records.formatters.FormatterParams; -import org.fao.geonet.api.records.formatters.groovy.Environment; -import org.fao.geonet.api.records.formatters.groovy.EnvironmentImpl; -import org.fao.geonet.api.records.formatters.groovy.Functions; -import org.fao.geonet.languages.IsoLanguagesMapper; -import org.fao.geonet.utils.Xml; -import org.jdom.Attribute; -import org.jdom.Content; -import org.jdom.Element; -import org.jdom.Text; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.context.request.ServletWebRequest; - -import java.io.File; -import java.net.URL; -import java.util.List; - -import static org.fao.geonet.api.records.formatters.FormatterWidth._100; - -/** - * @author Jesse on 10/17/2014. - */ -public abstract class AbstractFullViewFormatterTest extends AbstractFormatterTest { - - @Autowired - private IsoLanguagesMapper mapper; - - @SuppressWarnings("unchecked") - protected void testPrintFormat() throws Exception { - final FormatType formatType = FormatType.testpdf; - - Format format = new Format(formatType).invoke(); - Functions functions = format.getFunctions(); - String view = format.getView(); - - List excludes = excludes(); - - final Element xmlEl = Xml.loadString(xml, false); - final List text = Lists.newArrayList(Xml.selectNodes(xmlEl, "*//node()[not(@codeList)]/text()")); - text.addAll(Lists.newArrayList(Xml.selectNodes(xmlEl, "*//node()[@codeList]/@codeListValue"))); - - StringBuilder missingStrings = new StringBuilder(); - for (Object t : text) { - final String path; - final String requiredText; - if (t instanceof Text) { - requiredText = ((Text) t).getTextTrim(); - path = getXPath((Content) t).trim(); - } else if (t instanceof Attribute) { - Attribute attribute = (Attribute) t; - final String codelist = attribute.getParent().getAttributeValue("codeList"); - final String code = attribute.getValue(); - requiredText = functions.codelistValueLabel(codelist, code); - path = getXPath(attribute.getParent()).trim() + "> @codeListValue"; - } else { - throw new AssertionError(t.getClass() + " is not handled"); - } - if (!requiredText.isEmpty() && !view.contains(requiredText)) { - if (!excludes.contains(path.trim())) { - missingStrings.append("\n").append(path).append(" -> ").append(requiredText); - } - } - } - - if (missingStrings.length() > 0) { - throw new AssertionError("The following text elements are missing from the view:" + missingStrings); - } - } - - protected List excludes() { - return Lists.newArrayList(); - } - - private String getXPath(Content el) { - String path = ""; - if (el.getParentElement() != null) { - path = getXPath(el.getParentElement()); - } - if (el instanceof Element) { - return path + " > " + ((Element) el).getQualifiedName(); - } else { - return path + " > " + el.getClass().getSimpleName(); - } - } - - @Override - protected File getTestMetadataFile() throws Exception { - final URL mdFile = AbstractFullViewFormatterTest.class.getResource("/iso19139/example.xml"); - return new File(mdFile.toURI()); - } - - protected class Format { - private FormatType formatType; - private Functions functions; - private String view; - private String requestLanguage = "eng"; - ; - - public Format(FormatType formatType) throws Exception { - this.formatType = formatType; - } - - public Functions getFunctions() { - return functions; - } - - public String getView() { - return view; - } - - public Format invoke() throws Exception { - view = null; - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession(); - MockHttpServletResponse response = new MockHttpServletResponse(); -// measureFormatterPerformance(request, formatterId); - - final String formatterId = "full_view"; - FormatterParams fparams = getFormatterFormatterParamsPair(request, formatterId).two(); - Environment env = new EnvironmentImpl(fparams, mapper); - functions = new Functions(fparams, env); - -// formatService.exec("eng", FormatType.html.name(), "" + id, null, formatterId, "true", false, request, response); - formatService.exec(getRequestLanguage(), formatType.name(), "" + id, null, formatterId, "true", false, _100, - new ServletWebRequest(request, response)); - view = response.getContentAsString(); -// Files.write(view, new File("e:/tmp/view.html"), Constants.CHARSET); - - return this; - } - - public String getRequestLanguage() { - return requestLanguage; - } - - public void setRequestLanguage(String requestLanguage) { - this.requestLanguage = requestLanguage; - } - } -} diff --git a/schemas-test/src/test/java/iso19139/FullViewFormatterLocalizationTest.java b/schemas-test/src/test/java/iso19139/FullViewFormatterLocalizationTest.java deleted file mode 100644 index 6d9506fcb346..000000000000 --- a/schemas-test/src/test/java/iso19139/FullViewFormatterLocalizationTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139; - -import org.fao.geonet.languages.IsoLanguagesMapper; -import org.fao.geonet.api.records.formatters.FormatType; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; - -import static org.junit.Assert.assertEquals; - -/** - * @author Jesse on 10/17/2014. - */ -// TODOES -@Ignore -public class FullViewFormatterLocalizationTest extends AbstractFullViewFormatterTest { - - @Autowired - private IsoLanguagesMapper mapper; - - @Test - @SuppressWarnings("unchecked") - public void testPrintFormatLocales() throws Exception { - final FormatType formatType = FormatType.testpdf; - - Format format = new Format(formatType); - assertCorrectTranslation(format, "eng"); - assertCorrectTranslation(format, "fre"); - assertCorrectTranslation(format, "ger"); - - } - - public void assertCorrectTranslation(Format format, String lang) throws Exception { - format.setRequestLanguage(lang); - format.invoke(); - String view = format.getView(); - - assertEquals(view, lang.equalsIgnoreCase("eng"), view.contains("Identification EN Title")); - assertEquals(view, lang.equalsIgnoreCase("fre"), view.contains("Identification FR Title")); - assertEquals(view, lang.equalsIgnoreCase("ger"), view.contains("Identification DE Title")); - - } - -} diff --git a/schemas-test/src/test/java/iso19139/FullViewFormatterServiceTest.java b/schemas-test/src/test/java/iso19139/FullViewFormatterServiceTest.java deleted file mode 100644 index 6b96cc76081d..000000000000 --- a/schemas-test/src/test/java/iso19139/FullViewFormatterServiceTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139; - -import com.google.common.collect.Lists; - -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.test.annotation.DirtiesContext; - -import java.io.File; -import java.net.URL; -import java.util.List; - -/** - * @author Jesse on 10/17/2014. - */ -public class FullViewFormatterServiceTest extends AbstractFullViewFormatterTest { - - @Test - public void testDummy() { - } - - @Test - @Ignore - public void testServiceMdFormatting() throws Exception { - super.testPrintFormat(); - } - - protected List excludes() { - return Lists.newArrayList( - "> gmd:MD_Metadata > gmd:parentIdentifier > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > gmd:citation > gmd:CI_Citation > gmd:edition > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > gmd:graphicOverview > gmd:MD_BrowseGraphic > gmd:fileDescription > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > gmd:graphicOverview > gmd:MD_BrowseGraphic > gmd:fileType > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > gmd:descriptiveKeywords > gmd:MD_Keywords > gmd:thesaurusName > gmd:CI_Citation > gmd:date > gmd:CI_Date > gmd:date > gco:Date > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > gmd:descriptiveKeywords > gmd:MD_Keywords > gmd:thesaurusName > gmd:CI_Citation > gmd:identifier > gmd:MD_Identifier > gmd:code > gmx:Anchor > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > gmd:aggregationInfo > gmd:MD_AggregateInformation > gmd:aggregateDataSetIdentifier > gmd:RS_Identifier > gmd:code > gmx:FileName > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > srv:serviceType > gco:LocalName > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > srv:containsOperations > srv:SV_OperationMetadata > srv:connectPoint > gmd:CI_OnlineResource > gmd:protocol > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > srv:containsOperations > srv:SV_OperationMetadata > srv:connectPoint > gmd:CI_OnlineResource > gmd:function > gmd:CI_OnLineFunctionCode> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > srv:SV_ServiceIdentification > gmd:descriptiveKeywords > gmd:MD_Keywords > gmd:type > gmd:MD_KeywordTypeCode> @codeListValue" - ); - } - - @Override - protected File getTestMetadataFile() throws Exception { - final URL mdFile = FullViewFormatterServiceTest.class.getResource("/iso19139/example-service.xml"); - return new File(mdFile.toURI()); - } -} diff --git a/schemas-test/src/test/java/iso19139/FullViewFormatterTest.java b/schemas-test/src/test/java/iso19139/FullViewFormatterTest.java deleted file mode 100644 index 5087c537c155..000000000000 --- a/schemas-test/src/test/java/iso19139/FullViewFormatterTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139; - -import com.google.common.collect.Lists; - -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.test.annotation.DirtiesContext; - -import java.util.List; - -/** - * @author Jesse on 10/17/2014. - */ -public class FullViewFormatterTest extends AbstractFullViewFormatterTest { - - @Test - public void testDummy() { - } - - - @Test - @Ignore - public void testServiceMdFormatting() throws Exception { - super.testPrintFormat(); - } - - protected List excludes() { - return Lists.newArrayList( - "> gmd:MD_Metadata > gmd:contentInfo > gmd:MD_CoverageDescription > gmd:dimension > gmd:MD_Band > gmd:sequenceIdentifier > gco:MemberName > gco:attributeType > gco:TypeName > gco:aName > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:contentInfo > gmd:MD_CoverageDescription > gmd:dimension > gmd:MD_Band > gmd:descriptor > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:dataQualityInfo > gmd:DQ_DataQuality > gmd:report > gmd:DQ_TemporalValidity > gmd:evaluationMethodDescription > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:dataQualityInfo > gmd:DQ_DataQuality > gmd:report > gmd:DQ_TemporalValidity > gmd:evaluationProcedure > gmd:CI_Citation > gmd:title > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:dataQualityInfo > gmd:DQ_DataQuality > gmd:lineage > gmd:LI_Lineage > gmd:processStep > gmd:LI_ProcessStep > gmd:processor > gmd:CI_ResponsibleParty > gmd:organisationName > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:dataQualityInfo > gmd:DQ_DataQuality > gmd:report > gmd:DQ_NonQuantitativeAttributeAccuracy > gmd:nameOfMeasure > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:metadataConstraints > gmd:MD_LegalConstraints > gmd:otherConstraints > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:applicationSchemaInfo > gmd:MD_ApplicationSchemaInformation > gmd:name > gmd:CI_Citation > gmd:title > gco:PT_FreeText > gco:textGroup > gmd:LocalisedCharacterString > Text", - "> gmd:MD_Metadata > gmd:applicationSchemaInfo > gmd:MD_ApplicationSchemaInformation > gmd:constraintLanguage > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:applicationSchemaInfo > gmd:MD_ApplicationSchemaInformation > gmd:schemaAscii > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:applicationSchemaInfo > gmd:MD_ApplicationSchemaInformation > gmd:softwareDevelopmentFileFormat > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:metadataMaintenance > gmd:MD_MaintenanceInformation > gmd:maintenanceNote > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:title > gco:PT_FreeText > gco:textGroup > gmd:LocalisedCharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:date > gmd:CI_Date > gmd:date > gco:DateTime > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:title > gco:PT_FreeText > gco:textGroup > gmd:LocalisedCharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:date > gmd:CI_Date > gmd:date > gco:DateTime > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:series > gmd:CI_Series > gmd:name > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:series > gmd:CI_Series > gmd:issueIdentification > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:series > gmd:CI_Series > gmd:page > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:collectiveTitle > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:ISBN > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:ISSN > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:version > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:graphicOverview > gmd:MD_BrowseGraphic > gmd:fileType > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributionOrderProcess > gmd:MD_StandardOrderProcess > gmd:orderingInstructions > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributionOrderProcess > gmd:MD_StandardOrderProcess > gmd:turnaround > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributorTransferOptions > gmd:MD_DigitalTransferOptions > gmd:unitsOfDistribution > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributorTransferOptions > gmd:MD_DigitalTransferOptions > gmd:onLine > gmd:CI_OnlineResource > gmd:protocol > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributorTransferOptions > gmd:MD_DigitalTransferOptions > gmd:onLine > gmd:CI_OnlineResource > gmd:applicationProfile > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributorTransferOptions > gmd:MD_DigitalTransferOptions > gmd:onLine > gmd:CI_OnlineResource > gmd:description > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributorTransferOptions > gmd:MD_DigitalTransferOptions > gmd:offLine > gmd:MD_Medium > gmd:densityUnits > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributorTransferOptions > gmd:MD_DigitalTransferOptions > gmd:offLine > gmd:MD_Medium > gmd:mediumNote > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:descriptiveKeywords > gmd:MD_Keywords > gmd:thesaurusName > gmd:CI_Citation > gmd:alternateTitle > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:descriptiveKeywords > gmd:MD_Keywords > gmd:thesaurusName > gmd:CI_Citation > gmd:date > gmd:CI_Date > gmd:date > gco:DateTime > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:topicCategory > gmd:MD_TopicCategoryCode > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:extent > gmd:EX_Extent > gmd:temporalElement > gmd:EX_TemporalExtent > gmd:extent > gml:TimePeriod > gml:beginPosition > Text", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:extent > gmd:EX_Extent > gmd:temporalElement > gmd:EX_TemporalExtent > gmd:extent > gml:TimePeriod > gml:endPosition > Text", - "> gmd:MD_Metadata > gmd:distributionInfo > gmd:MD_Distribution > gmd:transferOptions > gmd:MD_DigitalTransferOptions > gmd:onLine > gmd:CI_OnlineResource > gmd:protocol > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:distributionInfo > gmd:MD_Distribution > gmd:transferOptions > gmd:MD_DigitalTransferOptions > gmd:onLine > gmd:CI_OnlineResource > gmd:applicationProfile > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:distributionInfo > gmd:MD_Distribution > gmd:transferOptions > gmd:MD_DigitalTransferOptions > gmd:onLine > gmd:CI_OnlineResource > gmd:linkage > gmd:URL > Text", - "> gmd:MD_Metadata > gmd:distributionInfo > gmd:MD_Distribution > gmd:transferOptions > gmd:MD_DigitalTransferOptions > gmd:onLine > gmd:CI_OnlineResource > gmd:protocol > gco:CharacterString > Text", - "> gmd:MD_Metadata > gmd:locale > gmd:PT_Locale > gmd:country > gmd:Country> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:date > gmd:CI_Date > gmd:dateType > gmd:CI_DateTypeCode> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:date > gmd:CI_Date > gmd:dateType > gmd:CI_DateTypeCode> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:presentationForm > gmd:CI_PresentationFormCode> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributorTransferOptions > gmd:MD_DigitalTransferOptions > gmd:onLine > gmd:CI_OnlineResource > gmd:function > gmd:CI_OnLineFunctionCode> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributorTransferOptions > gmd:MD_DigitalTransferOptions > gmd:offLine > gmd:MD_Medium > gmd:name > gmd:MD_MediumNameCode> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:resourceFormat > gmd:MD_Format > gmd:formatDistributor > gmd:MD_Distributor > gmd:distributorTransferOptions > gmd:MD_DigitalTransferOptions > gmd:offLine > gmd:MD_Medium > gmd:mediumFormat > gmd:MD_MediumFormatCode> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:descriptiveKeywords > gmd:MD_Keywords > gmd:type > gmd:MD_KeywordTypeCode> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:descriptiveKeywords > gmd:MD_Keywords > gmd:thesaurusName > gmd:CI_Citation > gmd:date > gmd:CI_Date > gmd:dateType > gmd:CI_DateTypeCode> @codeListValue", - "> gmd:MD_Metadata > gmd:portrayalCatalogueInfo > gmd:MD_PortrayalCatalogueReference > gmd:portrayalCatalogueCitation > gmd:CI_Citation > gmd:date > gmd:CI_Date > gmd:dateType > gmd:CI_DateTypeCode> @codeListValue", - "> gmd:MD_Metadata > gmd:applicationSchemaInfo > gmd:MD_ApplicationSchemaInformation > gmd:name > gmd:CI_Citation > gmd:date > gmd:CI_Date > gmd:dateType > gmd:CI_DateTypeCode> @codeListValue", - "> gmd:MD_Metadata > gmd:identificationInfo > gmd:MD_DataIdentification > gmd:citation > gmd:CI_Citation > gmd:identifier > gmd:RS_Identifier > gmd:authority > gmd:CI_Citation > gmd:alternateTitle > gco:CharacterString > Text" - ); - } -} diff --git a/schemas-test/src/test/java/iso19139/IsoMatchersTest.java b/schemas-test/src/test/java/iso19139/IsoMatchersTest.java deleted file mode 100644 index 4882ac2ff5e8..000000000000 --- a/schemas-test/src/test/java/iso19139/IsoMatchersTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139; - -import groovy.util.slurpersupport.GPathResult; - -import org.fao.geonet.schema.iso19139.ISO19139Namespaces; -import org.fao.geonet.api.records.formatters.AbstractFormatterTest; -import org.fao.geonet.api.records.formatters.groovy.Handler; -import org.fao.geonet.api.records.formatters.groovy.Handlers; -import org.junit.Test; -import org.springframework.mock.web.MockHttpServletRequest; - -import java.io.File; -import java.net.URL; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * @author Jesse on 10/23/2014. - */ -public class IsoMatchersTest extends AbstractFormatterTest { - - @Override - protected File getTestMetadataFile() throws Exception { - final URL mdFile = AbstractFullViewFormatterTest.class.getResource("/iso19139/example.xml"); - return new File(mdFile.toURI()); - } - - @Test - public void testTextMatcher() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession(); - request.addParameter("html", "true"); - - final String formatterId = "full_view"; - final Handlers handlers = getHandlers(request, formatterId); - GPathResult elem = parseXml( - "\n" - + " \n" - + " \n" - + " GER Citation Title\n" - + " \n" - + " \n" - + "", ISO19139Namespaces.GMD, ISO19139Namespaces.GCO); - final GPathResult titleEl = (GPathResult) elem.getProperty("gmd:title"); - Handler handler = handlers.findHandlerFor(titleEl); - - assertNotNull(handler); - assertTrue("Expected 'Text Elements' but got '" + handler.getName() + "'", handler.getName().equals("Text Elements")); - String handlerResult = executeHandler(request, formatterId, titleEl, handler); - assertTrue(handlerResult, handlerResult.contains("GER Citation Title")); - - elem = parseXml( - "" - + "\n" - + " eng\n" - + "", ISO19139Namespaces.GMD, ISO19139Namespaces.GCO); - final GPathResult langEl = (GPathResult) elem.getProperty("gmd:language"); - handler = handlers.findHandlerFor(langEl); - - assertNotNull(handler); - assertTrue("Expected 'Text Elements' but got '" + handler.getName() + "'", handler.getName().contains("gmd:language")); - handlerResult = executeHandler(request, formatterId, langEl, handler); - assertTrue(handlerResult, handlerResult.contains("English")); - assertTrue(handlerResult, handlerResult.contains("Metadata language")); - } - -} diff --git a/schemas-test/src/test/java/iso19139/XmlViewFormatterTest.java b/schemas-test/src/test/java/iso19139/XmlViewFormatterTest.java deleted file mode 100644 index fbf73b16eb96..000000000000 --- a/schemas-test/src/test/java/iso19139/XmlViewFormatterTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139; - -import com.google.common.collect.Lists; - -import org.fao.geonet.api.records.formatters.AbstractFormatterTest; -import org.fao.geonet.utils.Xml; -import org.jdom.Content; -import org.jdom.Element; -import org.jdom.Text; -import org.junit.Test; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.context.request.ServletWebRequest; - -import java.io.File; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.List; - -import static org.fao.geonet.api.records.formatters.FormatterWidth._100; - -/** - * @author Jesse on 10/17/2014. - */ -public class XmlViewFormatterTest extends AbstractFormatterTest { - - @Test - public void testBasicFormat() throws Exception { - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession(); - request.addParameter("html", "true"); - - final String formatterId = "xml_view"; - -// measureFormatterPerformance(request, formatterId); - - final MockHttpServletResponse response = new MockHttpServletResponse(); - formatService.exec("eng", "html", "" + id, null, formatterId, "true", false, _100, new ServletWebRequest(request, response)); - String view = response.getContentAsString(); -// Files.write(view, new File("e:/tmp/view.html"), Constants.CHARSET); - view = view.replaceAll("\\s+", " "); - - List excludes = Lists.newArrayList( - ); - - final Element xmlEl = Xml.loadString(xml, false); - final List text = Lists.newArrayList(Xml.selectNodes(xmlEl, "*//text()")); - - StringBuilder missingStrings = new StringBuilder(); - for (Object t : text) { - Text textEl = (Text) t; - final String requiredText = escapeXmlText(textEl.getTextTrim()); - if (!requiredText.isEmpty() && !view.contains(requiredText)) { - final String path = getXPath(textEl).trim(); - if (!excludes.contains(path)) { - missingStrings.append("\n").append(path).append(" -> ").append(requiredText); - } - } - } - - if (missingStrings.length() > 0) { - throw new AssertionError("The following text elements are missing from the view:" + missingStrings); - } - } - - private String getXPath(Content el) { - String path = ""; - if (el.getParentElement() != null) { - path = getXPath(el.getParentElement()); - } - if (el instanceof Element) { - return path + " > " + ((Element) el).getQualifiedName(); - } else { - return path + " > " + el.getClass().getSimpleName(); - } - } - - @Override - protected File getTestMetadataFile() throws URISyntaxException { - final URL mdFile = XmlViewFormatterTest.class.getResource("/iso19139/example.xml"); - return new File(mdFile.toURI()); - } -} diff --git a/schemas-test/src/test/resources/cswrecord/example.xml b/schemas-test/src/test/resources/cswrecord/example.xml deleted file mode 100644 index 82d6101e129c..000000000000 --- a/schemas-test/src/test/resources/cswrecord/example.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - 81de0ca8-2090-4386-9f9c-6648a7dc600f - Geothermische Potenzialabschätzung auf Grundlage der Temperaturen in 1500 m unter - Gelände - - dataset - Modellierung - Geologie - Temperatur - Geologie - Simulation - Energie - Geology - geoscientificInformation - ESRI Grid - Die Karte zeigt die Potenzialabschätzung für verschiedene geothermische - Nutzungsformen für das innere Projektgebiet auf - Grundlage der Temperaturen in 1500 m unter Gelände (Grad Celsius). Zusätzlich sind Störungen und - Störungszonen in gleicher - Tiefenlage dargestellt. Details siehe Abschlussbericht zum INTERREG IV-Projekt "GeORG" . - - copyright - 3D-Temperaturmodell und geologisches 3D-Modell des INTERREG IV A Projekts GeORG - - ESRI Grid - - 9.096 47.44 - 6.692 49.722 - - - http://www4.lgrb.uni-freiburg.de/ws/application/wms.phtml?REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS&SERVICE_NAME=lgrb_georg_temp_de - - http://www.lgrb.uni-freiburg.de/lgrb/Produkte - resources.get?id=350&fname=g_temp1500nk.jpg&access=public - - diff --git a/schemas-test/src/test/resources/dublincore/example.xml b/schemas-test/src/test/resources/dublincore/example.xml deleted file mode 100644 index babeee7f33f2..000000000000 --- a/schemas-test/src/test/resources/dublincore/example.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - Test File for Dublin Core - Camptocamp SA - Jesse - This is a test file - Description element for DC - http://... - today - also today - What ever you want :) - test type - text/plain - North 90, South -90, East 180, West -180. Global - eng - 80f1c261-1495-4e3b-bd22-f32a5f0ad643 - diff --git a/schemas/csw-record/src/main/plugin/csw-record/formatter/full_view/view.groovy b/schemas/csw-record/src/main/plugin/csw-record/formatter/full_view/view.groovy deleted file mode 100644 index 1679ee717339..000000000000 --- a/schemas/csw-record/src/main/plugin/csw-record/formatter/full_view/view.groovy +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -new cswrecord.Handlers(handlers, f, env).addDefaultHandlers() \ No newline at end of file diff --git a/schemas/csw-record/src/main/plugin/csw-record/formatter/groovy/cswrecord/Handlers.groovy b/schemas/csw-record/src/main/plugin/csw-record/formatter/groovy/cswrecord/Handlers.groovy deleted file mode 100644 index 578b8be77196..000000000000 --- a/schemas/csw-record/src/main/plugin/csw-record/formatter/groovy/cswrecord/Handlers.groovy +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package cswrecord - -import org.fao.geonet.api.records.formatters.FormatType -import org.geotools.geometry.jts.ReferencedEnvelope -import org.geotools.referencing.CRS - -import static java.lang.Double.parseDouble - -public class Handlers extends dublincore.Handlers { - - - public static final String BOUNDING_BOX = 'ows:BoundingBox' - - public Handlers(handlers, f, env) { - super(handlers, f, env, 'csw:Record') - excludedEls << BOUNDING_BOX - } - - public void addDefaultHandlers() { - super.addDefaultHandlers() - handlers.add name: 'BBoxes', select: BOUNDING_BOX, handleBoundingBox - } - - def handleBoundingBox = { el -> - def lowerCorner = el.'ows:LowerCorner'.text().trim().split(' ') - def upperCorner = el.'ows:UpperCorner'.text().trim().split(' ') - - def crsAtt = el['@crs'] - if (upperCorner.length > 1 && lowerCorner.length > 1) { - try { - String crsCode = crsAtt.text().trim() - if (!crsCode.isEmpty()) { - if (crsCode.contains(":::")) { - crsCode = crsCode.split(":::", 2)[1] - } - } else { - crsCode = "EPSG:4326" - } - - def crs = CRS.decode(crsCode.trim()) - ReferencedEnvelope bbox = new ReferencedEnvelope(parseDouble(lowerCorner[0]), parseDouble(upperCorner[0]), - parseDouble(lowerCorner[1]), parseDouble(upperCorner[1]), crs) - - def model = [ - label : f.nodeLabel(el), - s : bbox.getMinY(), - n : bbox.getMaxY(), - w : bbox.getMinX(), - e : bbox.getMaxX(), - geomproj : "EPSG:${CRS.lookupEpsgCode(crs, false)}", - minwidth: mapConfig.getWidth() / 4, - minheight: mapConfig.getWidth() / 4, - mapconfig : this.env.mapConfiguration - ] - - return handlers.fileResult("html/bbox.html", model) - } catch (Throwable t) { - // skip and use default - } - } - - def data = el.'ows:LowerCorner'.text().trim() + ", " + el.'ows:UpperCorner'.text().trim() - if (!crsAtt.text().isEmpty()) { - data += " (${crsAtt.text()})" - } - - return handlers.fileResult("html/2-level-entry.html", [label: f.nodeLabel(el), childData: data]) - } - - @Override - public String getAbstract(el) { - def abstractVal = firstNonEmpty(el.'dct:abstract') - if (abstractVal.isEmpty()) { - abstractVal = super.getAbstract(el); - } - return abstractVal - } - -} diff --git a/schemas/dublin-core/src/main/plugin/dublin-core/formatter/full_view/view.groovy b/schemas/dublin-core/src/main/plugin/dublin-core/formatter/full_view/view.groovy deleted file mode 100644 index e34be68405be..000000000000 --- a/schemas/dublin-core/src/main/plugin/dublin-core/formatter/full_view/view.groovy +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -new dublincore.Handlers(handlers, f, env).addDefaultHandlers() \ No newline at end of file diff --git a/schemas/dublin-core/src/main/plugin/dublin-core/formatter/groovy/dublincore/Handlers.groovy b/schemas/dublin-core/src/main/plugin/dublin-core/formatter/groovy/dublincore/Handlers.groovy deleted file mode 100644 index c6efe6d6d212..000000000000 --- a/schemas/dublin-core/src/main/plugin/dublin-core/formatter/groovy/dublincore/Handlers.groovy +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package dublincore - -import org.fao.geonet.api.records.formatters.groovy.Environment -import org.fao.geonet.api.records.formatters.groovy.util.* - -public class Handlers { - public static final String TITLE_EL_NAME = 'dc:title' - public static final String DESC_EL_NAME = 'dc:description' - protected org.fao.geonet.api.records.formatters.groovy.Handlers handlers; - protected org.fao.geonet.api.records.formatters.groovy.Functions f - protected Environment env - common.Handlers commonHandlers - public String rootEl - def excludedEls = [] - def urlElts = ['dc:relation'] - - public Handlers(handlers, f, env) { - this(handlers, f, env, "simpledc") - } - - public Handlers(handlers, f, env, rootEl) { - this.handlers = handlers - this.f = f - this.env = env - commonHandlers = new common.Handlers(handlers, f, env) - this.rootEl = rootEl - excludedEls << rootEl - } - - public void addDefaultHandlers() { - commonHandlers.addDefaultStartAndEndHandlers() - - handlers.add name: "Normal Elements", select: { - !excludedEls.contains(it.name()) && !it.text().isEmpty() - }, group:true, handleNormalEls - handlers.add name: 'Root Element', select: rootEl, priority: -1, handleRootEl - } - - def firstNonEmpty(el) { - if (el.text().isEmpty()) { - return null; - } else { - return el.find { !it.text().isEmpty() }.text() - } - } - - def handleRootEl = { el -> - Summary summary = new Summary(handlers, env, f); - - summary.title = firstNonEmpty(el[TITLE_EL_NAME]) - summary.abstr = getAbstract(el) - summary.content = handlers.processElements(el.children()) - summary.addNavBarItem(new NavBarItem(f.translate('complete'), null, '.container > .entry:not(.overview)')) - summary.addNavBarItem(commonHandlers.createXmlNavBarItem()) - summary.addCompleteNavItem = false - summary.addOverviewNavItem = true - - LinkBlock linkBlock = new LinkBlock(f.translate("links"), "fa fa-link"); - summary.links.add(linkBlock) - def toLink = { linkEl -> - Link link; - try { - def href = linkEl.text() - link = new Link(href, href); - - } catch (URISyntaxException e) { - link = new Link("alert('${f.translate('notValidUri')}')", linkEl.text()); - } - - return link - } - - def relatedLinkType = new LinkType("related", null, null, "fa fa-sitemap") - def referencesLinkType = new LinkType("references", null, null, "fa fa-arrows-h") - el.'dc:relation'.each{linkBlock.put(relatedLinkType, toLink(it))} - el.'dc:URI'.each{linkBlock.put(referencesLinkType, toLink(it))} - - summary.result - } - - def handleNormalEls = { els -> - def sections = new TreeMap( - [compare:{el1, el2 -> - if (el1 == TITLE_EL_NAME) return -1 - else if (el2 == TITLE_EL_NAME) return 1 - else return f.nodeLabel(el1, null).compareTo(f.nodeLabel(el2, null)) - }] as Comparator); - - - els.each{ - def list = sections[it.name()] - list = list == null ? [] : list - list << it - sections.put(it.name(), list) - } - - def singles = new StringBuilder() - def multiples = new StringBuilder() - sections.entrySet().each { entry -> - if (entry.value.size() > 1) { - multiples.append(handlers.fileResult("html/list-entry.html", [label: f.nodeLabel(entry.key, null), listItems: entry.value])) - } else { - def el = entry.value.iterator().next() - if(!urlElts.contains(el.name())) - singles.append(handlers.fileResult("html/text-el.html", [label: f.nodeLabel(el), text: el.text()])) - else - singles.append(handlers.fileResult("html/url-el.html", ["label": f.nodeLabel(el), "href" : el.text(), "text" : - el.text().length() > 50 ? (el.text().substring(0, 50) + "...") : el.text()])) - - } - } - - return handlers.fileResult("html/2-level-entry.html", [label: f.nodeLabel(rootEl, null), childData: singles.toString() + multiples]) - } - - public String getAbstract(el) { - return firstNonEmpty(el[DESC_EL_NAME]) - } -} diff --git a/schemas/iso19110/src/main/plugin/iso19110/formatter/full_view/view.groovy b/schemas/iso19110/src/main/plugin/iso19110/formatter/full_view/view.groovy deleted file mode 100644 index 61acdb35736a..000000000000 --- a/schemas/iso19110/src/main/plugin/iso19110/formatter/full_view/view.groovy +++ /dev/null @@ -1,28 +0,0 @@ -def isoHandlers = new iso19110.Handlers(handlers, f, env) - -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -//SummaryFactory.summaryHandler({it.parent() is it.parent()}, isoHandlers) - -isoHandlers.addDefaultHandlers() \ No newline at end of file diff --git a/schemas/iso19110/src/main/plugin/iso19110/formatter/groovy/iso19110/Handlers.groovy b/schemas/iso19110/src/main/plugin/iso19110/formatter/groovy/iso19110/Handlers.groovy deleted file mode 100644 index 9275beb299f9..000000000000 --- a/schemas/iso19110/src/main/plugin/iso19110/formatter/groovy/iso19110/Handlers.groovy +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19110 - -import org.fao.geonet.api.records.formatters.groovy.Environment -import org.fao.geonet.api.records.formatters.groovy.Functions -import org.fao.geonet.api.records.formatters.groovy.util.NavBarItem -import org.fao.geonet.api.records.formatters.groovy.util.Summary - -/** - * @author Jesse on 6/24/2015. - */ -class Handlers extends iso19139.Handlers { - def iso19139RootPackageEl; - - public Handlers(org.fao.geonet.api.records.formatters.groovy.Handlers handlers, Functions f, Environment env) { - super(handlers, f, env); - rootEl = 'gfc:FC_FeatureCatalogue' - packageViews = [rootEl] - iso19139RootPackageEl = super.rootPackageEl - rootPackageEl = iso19100RootPackageEl - } - - private def iso19100RootPackageEl = { el -> - Summary summary = new Summary(handlers, env, f); - - summary.title = isofunc.isoText(el['gmx:name']) - summary.abstr = '' - summary.content = iso19139RootPackageEl(el) - summary.addNavBarItem(new NavBarItem(f.translate('complete'), null, '.container > .entry:not(.overview)')) - summary.addNavBarItem(commonHandlers.createXmlNavBarItem()) - summary.addCompleteNavItem = false - summary.addOverviewNavItem = false - - summary.result - } - -} diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/full_view/view.groovy b/schemas/iso19139/src/main/plugin/iso19139/formatter/full_view/view.groovy deleted file mode 100644 index c5d141e3422f..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/full_view/view.groovy +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -import iso19139.SummaryFactory - -def isoHandlers = new iso19139.Handlers(handlers, f, env) - -SummaryFactory.summaryHandler({it.parent() is it.parent()}, isoHandlers) - -isoHandlers.addDefaultHandlers() diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Functions.groovy b/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Functions.groovy deleted file mode 100644 index 001291c24f4f..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Functions.groovy +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139 - -import org.fao.geonet.domain.ISODate - -import java.text.SimpleDateFormat - -public class Functions { - static final def CHAR_PATTERN = /\W/ - - def handlers; - def f - def env - common.Handlers commonHandlers - - def clean = { text -> - if (text == null) { - return '' - } - def trimmed = text.trim() - if ((trimmed =~ CHAR_PATTERN).matches()) { - trimmed = ''; - } - return trimmed; - } - - def isoUrlText = { el -> - el.'gmd:URL'.text() - } - - def isoAnchorUrlLink = { el -> - el.'gmx:Anchor'['@xlink:href'].text() - } - - def isoAnchorUrlText = { el -> - el.'gmx:Anchor'.text() - } - - def isoText = { el -> - def uiCode2 = '#'+env.lang2.toUpperCase() - def uiCode3 = '#'+env.lang3.toUpperCase() - - def locStrings = el.'**'.findAll{ it.name() == 'gmd:LocalisedCharacterString' && !it.text().isEmpty()} - def ptEl = locStrings.find{(it.'@locale' == uiCode2 || it.'@locale' == uiCode3)} - if (ptEl != null) return ptEl.text() - - def charString = el.'**'.findAll {it.name() == 'gco:CharacterString' && !it.text().isEmpty()} - if (!charString.isEmpty()) return charString[0].text() - if (!locStrings.isEmpty()) return locStrings[0].text() - "" - } - - def dateText = { el -> - - String date = el.'gco:Date'.text() - String dateTime = el.'gco:DateTime'.text() - if (!date.isEmpty()) { - return date; - } else if (!dateTime.isEmpty()){ - ISODate isoDate = new ISODate(dateTime) - return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(isoDate.toDate()) - } - } - /** - * A shortcut for: commonHandlers.func.textEl(node), text)) - * @return - */ - def isoTextEl(node, text) { - return commonHandlers.func.textEl(f.nodeLabel(node), text) - } - - /** - * A shortcut for: commonHandlers.func.wikiTextEl(node), text)) - * @return - */ - def isoWikiTextEl(node, text) { - return commonHandlers.func.wikiTextEl(f.nodeLabel(node), text) - } - - /** - * A shortcut for: commonHandlers.func.textEl(node), text)) - * @return - */ - def isoUrlEl(node, href, text) { - return commonHandlers.func.urlEl(f.nodeLabel(node), href, text) - } -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Handlers.groovy b/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Handlers.groovy deleted file mode 100644 index ebc71e31c9f6..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Handlers.groovy +++ /dev/null @@ -1,464 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139 - -import org.fao.geonet.api.records.formatters.groovy.Environment -import org.fao.geonet.api.records.formatters.groovy.MapConfig - -public class Handlers { - protected org.fao.geonet.api.records.formatters.groovy.Handlers handlers; - protected org.fao.geonet.api.records.formatters.groovy.Functions f - protected Environment env - Matchers matchers - iso19139.Functions isofunc - common.Handlers commonHandlers - List packageViews - String rootEl = 'gmd:MD_Metadata' - - public Handlers(handlers, f, env) { - this.handlers = handlers - this.f = f - this.env = env - commonHandlers = new common.Handlers(handlers, f, env) - isofunc = new iso19139.Functions(handlers: handlers, f:f, env:env, commonHandlers: commonHandlers) - matchers = new Matchers(handlers: handlers, f:f, env:env) - packageViews = [ - 'gmd:identificationInfo', 'gmd:metadataMaintenance', 'gmd:metadataConstraints', 'gmd:spatialRepresentationInfo', - 'gmd:distributionInfo', 'gmd:applicationSchemaInfo', 'gmd:dataQualityInfo', 'gmd:portrayalCatalogueInfo', - 'gmd:contentInfo', 'gmd:metadataExtensionInfo', 'gmd:referenceSystemInfo', rootEl] - } - - def addDefaultHandlers() { - handlers.add name: 'Text Elements', select: matchers.isTextEl, isoTextEl - handlers.add name: 'Simple Text Elements', select: matchers.isSimpleTextEl, isoSimpleTextEl - handlers.add name: 'URL Elements', select: matchers.isUrlEl, isoUrlEl - handlers.add name: 'Anchor URL Elements', select: matchers.isAnchorUrlEl, isoAnchorUrlEl - handlers.add name: 'Simple Elements', select: matchers.isBasicType, isoBasicType - handlers.add name: 'Boolean Elements', select: matchers.isBooleanEl, isoBooleanEl - handlers.add name: 'CodeList Elements', select: matchers.isCodeListEl, isoCodeListEl - handlers.add name: 'Date Elements', select: matchers.isDateEl, dateEl - handlers.add name: 'Format Elements', select: matchers.isFormatEl, group: true, formatEls - handlers.add name: 'Keyword Elements', select: 'gmd:descriptiveKeywords', group:true, keywordsEl - handlers.add name: 'ResponsibleParty Elements', select: matchers.isRespParty, pointOfContactEl - handlers.add name: 'Graphic Overview', select: 'gmd:graphicOverview', group: true, graphicOverviewEl - handlers.add name: 'Dataset URI', select: 'gmd:dataSetURI', isoDatasetUriEl - handlers.add select: 'gmd:language', group: false, isoLanguageEl - handlers.add select: matchers.isCiOnlineResourceParent, group: true, onlineResourceEls - handlers.add select: 'srv:coupledResource', group: true, coupledResourceEls - handlers.add select: 'srv:containsOperations', group: true, containsOperationsEls - handlers.add name: 'gmd:topicCategory', select: 'gmd:topicCategory', group: true, { elems -> - def listItems = elems.findAll{!it.text().isEmpty()}.collect {f.codelistValueLabel("MD_TopicCategoryCode", it.text())}; - handlers.fileResult("html/list-entry.html", [label:f.nodeLabel(elems[0]), listItems: listItems]) - } - - handlers.skip name: "skip date parent element", select: matchers.hasDateChild, {it.children()} - handlers.skip name: "skip codelist parent element", select: matchers.hasCodeListChild, {it.children()} - handlers.skip name: "skip containers: " + matchers.skipContainers, select: matchers.isSkippedContainer, {it.children()} - - handlers.add select: 'gmd:locale', group: true, localeEls - handlers.add 'gmd:CI_Date', ciDateEl - handlers.add 'gmd:CI_Citation', citationEl - handlers.add name: 'Root Element', select: matchers.isRoot, rootPackageEl - - handlers.add name: 'identificationInfo elements', select: {it.parent().name() == 'gmd:identificationInfo'}, commonHandlers.entryEl(f.&nodeLabel, {el -> 'gmd_identificationInfo'}) - handlers.add name: 'Container Elements', select: matchers.isContainerEl, priority: -1, commonHandlers.entryEl(f.&nodeLabel, addPackageViewClass) - - commonHandlers.addDefaultStartAndEndHandlers(); - addExtentHandlers() - - handlers.sort name: 'Text Elements', select: matchers.isContainerEl, priority: -1, sortContainerEl - } - - def sortContainerEl = {el1, el2 -> - def v1 = matchers.isContainerEl(el1) ? 1 : -1; - def v2 = matchers.isContainerEl(el2) ? 1 : -1; - return v1 - v2 - } - def addPackageViewClass = {el -> if (packageViews.contains(el.name())) return el.name().replace(':', '_')} - - def addExtentHandlers() { - handlers.add commonHandlers.matchers.hasChild('gmd:EX_Extent'), commonHandlers.flattenedEntryEl({it.'gmd:EX_Extent'}, f.&nodeLabel) - handlers.add name: 'BBox Element', select: matchers.isBBox, bboxEl(false) - handlers.add name: 'Polygon Element', select: matchers.isPolygon, polygonEl(false) - handlers.add 'gmd:geographicElement', commonHandlers.processChildren{it.children()} - handlers.add 'gmd:extentTypeCode', extentTypeCodeEl - } - - def isoTextEl = { isofunc.isoTextEl(it, isofunc.isoText(it))} - def isoUrlEl = { isofunc.isoUrlEl(it, isofunc.isoUrlText(it), isofunc.isoUrlText(it))} - def isoAnchorUrlEl = { isofunc.isoUrlEl(it, isofunc.isoAnchorUrlLink(it), isofunc.isoAnchorUrlText(it))} - def isoDatasetUriEl = { isofunc.isoUrlEl(it, isofunc.isoText(it), isofunc.isoText(it))} - def isoCodeListEl = {isofunc.isoTextEl(it, f.codelistValueLabel(it))} - def isoBasicType = {isofunc.isoTextEl(it, it.'*'.text())} - def isoSimpleTextEl = { isofunc.isoTextEl(it, it.text()) } - def isoSimpleTextElGrouped = { elems -> - def listItems = elems.findAll{!it.text().isEmpty()}.collect {it.text()}; - handlers.fileResult("html/list-entry.html", [label:f.nodeLabel(elems[0]), listItems: listItems]) - } - def parseBool(text) { - switch (text.trim().toLowerCase()){ - case "1": - case "true": - case "y": - return true; - default: - return false; - } - } - def isoBooleanEl = {isofunc.isoTextEl(it, parseBool(it.'*'.text()).toString())} - def dateEl = {isofunc.isoTextEl(it, isofunc.dateText(it));} - def extentTypeCodeEl = { - isofunc.isoTextEl(it, parseBool(it.text()) ? 'include' : 'excluded') - } - def ciDateEl = { - if(matchers.isDateEl(it.'gmd:date')) { - def dateType = f.codelistValueLabel(it.'gmd:dateType'.'gmd:CI_DateTypeCode') - commonHandlers.func.textEl(dateType, isofunc.dateText(it.'gmd:date')); - } - } - def localeEls = { els -> - def locales = [] - els.each { - it.'gmd:PT_Locale'.each { loc -> - locales << [ - language: f.codelistValueLabel(loc.'gmd:languageCode'.'gmd:LanguageCode'), - charset: f.codelistValueLabel(loc.'gmd:characterEncoding'.'gmd:MD_CharacterSetCode') - ] - } - } - handlers.fileResult("html/locale.html", [ - label: f.nodeLabel(els[0]), - locales: locales - ]) - } - def isoLanguageEl = { language -> - def lang; - if (!language.'gmd:LanguageCode'.isEmpty()) { - lang = f.codelistValueLabel(language.'gmd:LanguageCode') - } else { - lang = f.translateLanguageCode(language.text()); - } - - commonHandlers.func.textEl(f.nodeLabel(language), lang); - } - def containsOperationsEls = { els -> - StringBuilder builder = new StringBuilder(); - els.'*'.each{op -> - builder.append(handlers.processElements(op)); - } - - return handlers.fileResult('html/2-level-entry.html', [label: f.nodeLabel(els[0]), childData: builder.toString()]) - } - - def onlineResourceEls = { els -> - def links = [] - els.each {it.'gmd:CI_OnlineResource'.each { link -> - def model = [ - href : isofunc.isoUrlText(link.'gmd:linkage'), - name : isofunc.clean(isofunc.isoText(link.'gmd:name')), - desc : isofunc.clean(isofunc.isoText(link.'gmd:description')) - ] - if (model.href != '' || model.name != '' || model.desc != '') { - links << model; - } - }} - - if (links.isEmpty()) { - return '' - } else { - handlers.fileResult('html/online-resource.html', [ - label: f.nodeLabel(els[0]), - links: links - ]) - } - } - - def coupledResourceEls = { els -> - def resources = com.google.common.collect.ArrayListMultimap.create() - - def resolveResource = { el -> - def resource = el.'srv:SV_CoupledResource' - if (resource.isEmpty()) { - resource = el - } - resource - } - - els.each {el -> - def resource = resolveResource(el) - def opName = resource.'srv:operationName'.text() - def identifier = resource.'srv:identifier'.text() - def scopedName = resource.'gco:ScopedName'.text() - - def tip, href, cls; - if (identifier.trim().isEmpty()) { - href = "javascript:alert('" + this.f.translate("noUuidInLink") + "');" - tip = this.f.translate("noUuidInLink") - cls = 'text-muted' - } else { - href = env.localizedUrl + 'display#/' + identifier + '/formatters/full_view/' - tip = href - } - def category = opName.trim().isEmpty() ? 'uncategorized' : opName - resources.put(category, [ - href : href, - tip : tip, - name : scopedName.trim().isEmpty() ? identifier : scopedName, - class: cls - ]); - } - - def label = f.nodeLabel("srv:SV_CoupledResource", null) - if (!els.isEmpty()) { - label = f.nodeLabel(els[0]) - } - - def model = [label: label, resources: resources.asMap()] - handlers.fileResult("html/coupled-resources.html", model) - } - def formatEls = { els -> - def formats = [] as Set - - def resolveFormat = { el -> - def format = el.'gmd:MD_Format' - if (format.isEmpty()) { - format = el - } - format - } - - els.each {el -> - def format = resolveFormat(el) - def valueMap = [:] - format.children().list().each {child -> - if (child.name().equals("gmd:formatDistributor")) { - return; - } - String[] parts = child.name().split(":"); - String name; - if (parts.length == 2) { - name = parts[1] - } else { - name = parts[0] - } - - valueMap.put(name, isofunc.isoText(child)) - } - def distributor = resolveFormat(el).'gmd:formatDistributor'.'gmd:MD_Distributor'.'gmd:distributorContact'.'*' - if (!distributor.text().isEmpty()) { - valueMap.put('formatDistributor', handlers.processElements(distributor)) - } - - formats.add(valueMap) - } - - def label = "format" - if (!els.isEmpty()) { - label = f.nodeLabel(els[0]) - } - - def model = [label: label, formats: formats] - handlers.fileResult("html/format.html", model) - } - def keywordsEl = {keywords -> - def keywordProps = com.google.common.collect.ArrayListMultimap.create() - keywords.collectNested {it.'**'.findAll{it.name() == 'gmd:keyword'}}.flatten().each { k -> - def thesaurusName = isofunc.isoText(k.parent().'gmd:thesaurusName'.'gmd:CI_Citation'.'gmd:title') - - if (thesaurusName.isEmpty()) { - def keywordTypeCode = k.parent().'gmd:type'.'gmd:MD_KeywordTypeCode' - if (!keywordTypeCode.isEmpty()) { - thesaurusName = f.translate("uncategorizedKeywords") - } - } - - if (thesaurusName.isEmpty()) { - thesaurusName = f.translate("noThesaurusName") - } - keywordProps.put(thesaurusName, isofunc.isoText(k)) - } - - return handlers.fileResult('html/keyword.html', [ - label : f.nodeLabel("gmd:descriptiveKeywords", null), - keywords: keywordProps.asMap()]) - } - def isSmallImage(img) { - return img.matches(".+_s\\.\\w+"); - } - def graphicOverviewEl = {graphics -> - def links = [] - def hasLargeGraphic = graphics.find {graphic -> - def url = graphic.'gmd:fileName'.text() - !(url.startsWith("http://") || url.startsWith("https://")) && !isSmallImage(url) - } - graphics.each {it.'gmd:MD_BrowseGraphic'.each { graphic -> - def img = graphic.'gmd:fileName'.text() - String thumbnailUrl; - if (img.startsWith("http://") || img.startsWith("https://")) { - thumbnailUrl = img.replace("&fname", "&fname"); - } else if (!isSmallImage(img) || !hasLargeGraphic) { - thumbnailUrl = env.getLocalizedUrl() + "resources.get?fname=" + img + "&access=public&id=" + env.getMetadataId(); - } - - if (thumbnailUrl != null) { - links << [ - src : thumbnailUrl, - desc: isofunc.isoText(graphic.'gmd:fileDescription') - ] - } - - }} - handlers.fileResult("html/graphic-overview.html", [ - label: f.nodeLabel(graphics[0]), - graphics: links - ]) - } - def citationEl = { el -> - Set processedChildren = ['gmd:title', 'gmd:alternateTitle', 'gmd:identifier', 'gmd:ISBN', 'gmd:ISSN', - 'gmd:date', 'gmd:edition', 'gmd:editionDate', 'gmd:presentationForm'] - - def otherChildren = el.children().findAll { ch -> !processedChildren.contains(ch.name()) } - - def model = [ - title : handlers.processElements([el.'gmd:title']), - altTitle : handlers.processElements([el.'gmd:alternateTitle']), - date : handlers.processElements(el.'gmd:date'.'gmd:CI_Date'), - editionInfo: commonHandlers.func.textEl(el.'gmd:edition'.text(), el.'gmd:editionDate'.'gco:Date'.text()), - identifier : isofunc.isoWikiTextEl(el.'gmd:identifier', el.'gmd:identifier'.'*'.'gmd:code'.join('
')), - presentationForm : isofunc.isoTextEl(el.'gmd:presentationForm', f.codelistValueLabel(el.'gmd:presentationForm'.'gmd:CI_PresentationFormCode')), - ISBN : handlers.processElements(el.'gmd:ISBN'), - ISSN : handlers.processElements(el.'gmd:ISSN'), - otherData : handlers.processElements(otherChildren) - ] - return handlers.fileResult("html/citation.html", model) - } - - /** - * El must be a parent of gmd:CI_ResponsibleParty - */ - def pointOfContactEl = { el -> - - def party = el.children().find { ch -> - ch.name() == 'gmd:CI_ResponsibleParty' || ch['@gco:isoType'].text() == 'gmd:CI_ResponsibleParty' - } - - def general = pointOfContactGeneralData(party); - def groups = party.'gmd:contactInfo'.'*'.'*' - - def half = (int) Math.round((groups.size()) / 2) - - def output = commonHandlers.func.isPDFOutput() ? '' : '
' - if (commonHandlers.func.isPDFOutput()) { - output += '
' - output += '' - } else { - output = '
' - output += commonHandlers.func.textColEl(general.toString() + handlers.processElements(groups.take(half - 1)), 6) - output += commonHandlers.func.textColEl(handlers.processElements(groups.drop(half - 1)), 6) - } - - output += commonHandlers.func.isPDFOutput() ? '
' + general.toString() + handlers.processElements(groups.take(half - 1)) + '' + handlers.processElements(groups.drop(half - 1)) + '
' : '' - - return handlers.fileResult('html/2-level-entry.html', [label: f.nodeLabel(el), childData: output]) - } - - def pointOfContactGeneralData(party) { - def generalChildren = [ - party.'gmd:individualName', - party.'gmd:organisationName', - party.'gmd:positionName', - party.'gmd:role' - ] - handlers.fileResult('html/2-level-entry.html', [label: f.translate('general'), childData: handlers.processElements(generalChildren)]) - } - - def polygonEl(thumbnail) { - return { el -> - MapConfig mapConfig = env.mapConfiguration - def mapproj = mapConfig.mapproj - def background = mapConfig.background - def width = thumbnail? mapConfig.thumbnailWidth : mapConfig.width - def mdId = env.getMetadataId(); - def xpath = f.getXPathFrom(el); - - if (xpath != null) { - def image = "" - - def inclusion = el.'gmd:extentTypeCode'.text() == '0' ? 'exclusive' : 'inclusive'; - - def label = f.nodeLabel(el) + " (" + f.translate(inclusion) + ")" - handlers.fileResult('html/2-level-entry.html', [label: label, childData: image]) - } - } - } - - def bboxEl(thumbnail) { - return { el -> - if (el.parent().'gmd:EX_BoundingPolygon'.text().isEmpty() && - el.parent().parent().'gmd:geographicElement'.'gmd:EX_BoundingPolygon'.text().isEmpty()) { - - def inclusion = el.'gmd:extentTypeCode'.text() == '0' ? 'exclusive' : 'inclusive'; - - def label = f.nodeLabel(el) + " (" + f.translate(inclusion) + ")" - - def replacements = bbox(thumbnail, el) - replacements['label'] = label - replacements['pdfOutput'] = commonHandlers.func.isPDFOutput() - - handlers.fileResult("html/bbox.html", replacements) - } - } - } - - def bbox(thumbnail, el) { - def mapConfig = env.mapConfiguration - if (thumbnail) { - mapConfig.setWidth(mapConfig.thumbnailWidth) - } - - return [ w: el.'gmd:westBoundLongitude'.'gco:Decimal'.text(), - e: el.'gmd:eastBoundLongitude'.'gco:Decimal'.text(), - s: el.'gmd:southBoundLatitude'.'gco:Decimal'.text(), - n: el.'gmd:northBoundLatitude'.'gco:Decimal'.text(), - geomproj: "EPSG:4326", - minwidth: mapConfig.getWidth() / 4, - minheight: mapConfig.getWidth() / 4, - mapconfig: mapConfig - ] - } - def rootPackageEl = { - el -> - def rootPackage = el.children().findAll { ch -> !this.packageViews.contains(ch.name()) } - def otherPackage = el.children().findAll { ch -> this.packageViews.contains(ch.name()) } - - def rootPackageData = handlers.processElements(rootPackage, el); - def otherPackageData = handlers.processElements(otherPackage, el); - - def rootPackageOutput = handlers.fileResult('html/2-level-entry.html', - [label: f.nodeLabel(el), childData: rootPackageData, name: rootEl.replace(":", "_")]) - - return rootPackageOutput.toString() + otherPackageData - } -} diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Matchers.groovy b/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Matchers.groovy deleted file mode 100644 index c83eda108fd3..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/Matchers.groovy +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139 - -public class Matchers { - def handlers; - def f - def env - - def isUrlEl = {!it.'gmd:URL'.text().isEmpty()} - def isAnchorUrlEl = {!it.'gmx:Anchor'['@xlink:href'].text().isEmpty()} - def simpleElements = ['gco:Decimal', 'gco:Integer', 'gco:Scale', 'gco:Angle', 'gco:Measure', 'gco:Distance', - 'gmd:MD_PixelOrientationCode', 'gts:TM_PeriodDuration'] - - def skipContainers = [ - 'gmd:CI_Series', 'gmd:MD_ReferenceSystem', 'gmd:identificationInfo', 'gmd:transferOptions', - 'gmd:contactInfo', 'gmd:address', 'gmd:phone', 'gmd:onlineResource', 'gmd:referenceSystemIdentifier', - 'gmd:distributorTransferOptions', 'gmd:resourceMaintenance', 'gmd:resourceConstraints', 'gmd:aggregationInfo', 'gmd:scope', - 'gmd:DQ_DataQuality', 'gmd:lineage', 'gmd:processStep', 'gmd:MD_Distribution', 'gmd:MD_Distributor' - ] - - def isBasicType = {el -> - el.children().size() == 1 && simpleElements.any{!el[it].text().isEmpty()} - } - def isDateEl = {!it.'gco:DateTime'.text().isEmpty() || !it.'gco:Date'.text().isEmpty()} - def isFormatEl = {!it.'gmd:MD_Format'.text().isEmpty() || (it.name() == 'gmd:MD_Format' && !it.text().isEmpty())} - def isBooleanEl = {!it.'gco:Boolean'.text().isEmpty()} - def hasDateChild = {it.children().size() == 1 && it.children().any(isDateEl)} - def isCodeListEl = {!it['@codeListValue'].text().isEmpty()} - def hasCodeListChild = {it.children().size() == 1 && it.children().any(isCodeListEl)} - - def isTextEl = {el -> - !el.'gco:CharacterString'.text().isEmpty() || - !el.'gmd:PT_FreeText'.'gmd:textGroup'.'gmd:LocalisedCharacterString'.text().isEmpty() - } - - def isSimpleTextEl = {el -> - el.children().isEmpty() && !el.text().isEmpty() - } - - def isContainerEl = {el -> - !isBasicType(el) && !isSimpleTextEl(el) && - !isTextEl(el) && !isUrlEl(el) && !isAnchorUrlEl(el) && - !isCodeListEl(el) && !hasCodeListChild(el) && - !isDateEl(el) && !hasDateChild(el) && - !el.children().isEmpty() - //!excludeContainer.any{it == el.name()} - } - - def isRespParty = { el -> - !el.'gmd:CI_ResponsibleParty'.isEmpty() || el.'*'['@gco:isoType'].text() == 'gmd:CI_ResponsibleParty' - } - - def isCiOnlineResourceParent = { el -> - !el.'gmd:CI_OnlineResource'.text().isEmpty() - } - - def isBBox = { el -> - el.name() == 'gmd:EX_GeographicBoundingBox' - } - def isPolygon = { el -> - el.name() == 'gmd:EX_BoundingPolygon' - } - def isRoot = { el -> - el.parent() is el - } - - def isSkippedContainer = { el -> - skipContainers.contains(el.name()) - } - -} diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/SummaryFactory.groovy b/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/SummaryFactory.groovy deleted file mode 100644 index 5c72c822cbb4..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/groovy/iso19139/SummaryFactory.groovy +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package iso19139 -import org.fao.geonet.api.records.formatters.FormatType -import org.fao.geonet.api.records.formatters.groovy.Environment -import org.fao.geonet.api.records.formatters.groovy.util.* - -import java.util.regex.Pattern - -/** - * Creates the {@link org.fao.geonet.api.records.formatters.groovy.util.Summary} instance for the iso19139 class. - * - * @author Jesse on 11/18/2014. - */ -class SummaryFactory { - def isoHandlers; - org.fao.geonet.api.records.formatters.groovy.Handlers handlers - org.fao.geonet.api.records.formatters.groovy.Functions f - Environment env - - def navBarItems - - /* - * This field can be set by the creator and provided a closure that will be passed the summary object. The closure can - * perform customization for its needs. - */ - Closure summaryCustomizer = null - - SummaryFactory(isoHandlers, summaryCustomizer) { - this.isoHandlers = isoHandlers - this.handlers = isoHandlers.handlers; - this.f = isoHandlers.f; - this.env = isoHandlers.env; - this.navBarItems = ['gmd:identificationInfo', 'gmd:distributionInfo', isoHandlers.rootEl] - this.summaryCustomizer = summaryCustomizer; - } - SummaryFactory(isoHandlers) { - this(isoHandlers, null) - } - - static void summaryHandler(select, isoHandler) { - def factory = new SummaryFactory(isoHandler) - factory.handlers.add name: "Summary Handler", select: select, {factory.create(it).getResult()} - } - - Summary create(metadata) { - - Summary summary = new Summary(this.handlers, this.env, this.f) - - summary.title = this.isoHandlers.isofunc.isoText(metadata.'gmd:identificationInfo'.'*'.'gmd:citation'.'gmd:CI_Citation'.'gmd:title') - summary.abstr = this.isoHandlers.isofunc.isoText(metadata.'gmd:identificationInfo'.'*'.'gmd:abstract').replaceAll("\n", "
") - - configureKeywords(metadata, summary) - configureFormats(metadata, summary) - configureExtent(metadata, summary) - configureThumbnails(metadata, summary) - - - LinkBlock linkBlock = new LinkBlock('links', "fa fa-link"); - configureLinks(linkBlock, 'link', false, { - def linkParts = it.split("\\|") - [ - title : isoHandlers.isofunc.clean(linkParts[0]), - desc : isoHandlers.isofunc.clean(linkParts[1]), - href : isoHandlers.isofunc.clean(linkParts[2]), - protocol: isoHandlers.isofunc.clean(linkParts[3]) - ] - }) - - if (!linkBlock.links.isEmpty()) { - summary.links.add(linkBlock) - } - - /* - * TODO fix the xslt transform required by loadHierarchyLinkBlocks when running tests. - */ - if (env.formatType == FormatType.pdf/* || env.formatType == FormatType.testpdf */) { - summary.associated.add(isoHandlers.commonHandlers.loadHierarchyLinkBlocks()) - } else { - summary.associated.add(createDynamicAssociatedHtml(summary)) - } - - def toNavBarItem = {s -> - def name = f.nodeLabel(s, null) - def abbrName = f.nodeTranslation(s, null, "abbrLabel") - new NavBarItem(name, abbrName, '.' + s.replace(':', "_")) - } - summary.navBar = this.isoHandlers.packageViews.findAll{navBarItems.contains(it)}.collect (toNavBarItem) - summary.navBarOverflow = this.isoHandlers.packageViews.findAll{!navBarItems.contains(it)}.collect (toNavBarItem) - summary.navBarOverflow.add(isoHandlers.commonHandlers.createXmlNavBarItem()) - summary.content = this.isoHandlers.rootPackageEl(metadata) - - if (summaryCustomizer != null) { - summaryCustomizer(summary); - } - - return summary - } - - def configureKeywords(metadata, summary) { - def keywords = metadata."**".findAll{it.name() == 'gmd:descriptiveKeywords'} - if (!keywords.isEmpty()) { - summary.keywords = this.isoHandlers.keywordsEl(keywords).toString() - } - } - def configureFormats(metadata, summary) { - def formats = metadata."**".findAll this.isoHandlers.matchers.isFormatEl - if (!formats.isEmpty()) { - summary.formats = this.isoHandlers.formatEls(formats).toString() - } - } - def configureExtent(metadata, summary) { - def extents = metadata."**".findAll { this.isoHandlers.matchers.isPolygon(it) || this.isoHandlers.matchers.isBBox(it) } - def split = extents.split this.isoHandlers.matchers.isPolygon - - def polygons = split[0] - def bboxes = split[1] - - def extent = "" - if (!polygons.isEmpty()) { - extent = this.isoHandlers.polygonEl(true)(polygons[0]).toString() - } else if (!bboxes.isEmpty()) { - extent = this.isoHandlers.bboxEl(true)(bboxes[0]).toString() - } - summary.extent = extent - } - - def configureLinks(linkBlock, indexKey, urlAndTextEquals, objParser) { - Collection links = this.env.indexInfo[indexKey]; - if (links != null && !links.isEmpty()) { - - links.each { link -> - def linkParts = objParser(link) - def title = linkParts.title - def desc = linkParts.desc - def href = linkParts.href - if (title.isEmpty()) { - title = desc; - } - if (title.isEmpty()) { - title = href; - } - - if (href != '') { - def protocol = linkParts.protocol != null ? linkParts.protocol.toLowerCase() : ''; - def linkClass = href.isEmpty() ? 'text-muted' : ''; - - def imagesDir = "../../images/formatter/" - def type; - def icon = ""; - def iconClasses = ""; - if (protocol.contains("kml")) { - type = "kml"; - icon = imagesDir + "kml.png"; - } else if (protocol.contains("wms")) { - type = "wms"; - icon = imagesDir + "wms.png"; - } else if (protocol.contains("download")) { - type = "download"; - iconClasses = "fa fa-download" - } else if (protocol.contains("wfs")) { - type = "wfs"; - icon = imagesDir + "wfs.png"; - } else if (protocol.contains("ogc:")) { - type = "ogc"; - } else { - if (indexKey == 'wms_uri' ) { - type = "wms"; - icon = imagesDir + "wms.png"; - } else { - type = "link"; - iconClasses = "fa fa-link" - } - } - - def linkType = new LinkType(type, null, icon, iconClasses) - - def linkObj = new Link(href, title, linkClass) - if (urlAndTextEquals) { - linkBlock.linkMap.put(linkType, linkObj); - } else { - linkBlock.put(linkType, linkObj) - } - } - } - } - } - - LinkBlock createDynamicAssociatedHtml(Summary summary) { - def associated = "associated-link" - def html = """ - -
Loading...
-""" - - LinkBlock linkBlock = new LinkBlock(associated, "fa fa-sitemap") - linkBlock.html = html - return linkBlock; - } - - private static void configureThumbnails(metadata, header) { - def logos = metadata.'gmd:identificationInfo'.'*'.'gmd:graphicOverview'.'gmd:MD_BrowseGraphic'.'gmd:fileName'.'gco:CharacterString' - - logos.each { logo -> - header.addThumbnail(logo.text()) - } - } -} diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/citation.html b/schemas/iso19139/src/main/plugin/iso19139/formatter/html/citation.html deleted file mode 100644 index c947ab7a559d..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/citation.html +++ /dev/null @@ -1,40 +0,0 @@ - - -
-
- {{title}} - {{altTitle}} - {{date}} - {{editionInfo}} -
-
- {{identifier}} - {{presentationForm}} - {{ISBN}} - {{ISSN}} -
-
- {{otherData}} -
-
diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/coupled-resources.html b/schemas/iso19139/src/main/plugin/iso19139/formatter/html/coupled-resources.html deleted file mode 100644 index d798f9f4d5b7..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/coupled-resources.html +++ /dev/null @@ -1,35 +0,0 @@ - - -
-
    -
  • - {{opName}} -
      -
    • - -
    • -
    -
  • -
-
diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/format.html b/schemas/iso19139/src/main/plugin/iso19139/formatter/html/format.html deleted file mode 100644 index 8d1ca368b1f4..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/format.html +++ /dev/null @@ -1,47 +0,0 @@ - - -
-
    -
  • - {{f.name}} ({{f.version}}) -
      -
    • -
      gmd:amendmentNumber
      -
      {{f.amendmentNumber}}
      -
    • -
    • -
      gmd:specification
      -
      {{f.specification}}
      -
    • -
    • -
      gmd:fileDecompressionTechnique
      -
      {{f.fileDecompressionTechnique}}
      -
    • -
    • - {{f.formatDistributor}} -
    • -
    -
  • -
-
diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/graphic-overview.html b/schemas/iso19139/src/main/plugin/iso19139/formatter/html/graphic-overview.html deleted file mode 100644 index b93e74681542..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/graphic-overview.html +++ /dev/null @@ -1,35 +0,0 @@ - - -
-
-
- -
-
-
diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/keyword.html b/schemas/iso19139/src/main/plugin/iso19139/formatter/html/keyword.html deleted file mode 100644 index 4fdd59de7efb..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/keyword.html +++ /dev/null @@ -1,33 +0,0 @@ - - -
-
    -
  • - {{type}} -
      -
    • {{word}}
    • -
    -
  • -
-
diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/locale.html b/schemas/iso19139/src/main/plugin/iso19139/formatter/html/locale.html deleted file mode 100644 index 531361f3c678..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/locale.html +++ /dev/null @@ -1,30 +0,0 @@ - - -
-
    -
  • - {{loc.language}} ({{loc.charset}}) -
  • -
-
diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/online-resource.html b/schemas/iso19139/src/main/plugin/iso19139/formatter/html/online-resource.html deleted file mode 100644 index fc94f4b59f5a..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/online-resource.html +++ /dev/null @@ -1,30 +0,0 @@ - - -
-
    -
  • - -
  • -
-
diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/single-resource.html b/schemas/iso19139/src/main/plugin/iso19139/formatter/html/single-resource.html deleted file mode 100644 index 1dc9d60866ff..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/html/single-resource.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - {{link.name | escapeXmlContent}} - {{link.href | escapeXmlContent}} - - {{link.name | escapeXmlContent}} - - {{link.desc | escapeXmlContent}} - diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ca-strings.json b/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ca-strings.json deleted file mode 100644 index 504e3f8ccda9..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ca-strings.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "general": "General", - "kml-link": "Arxiu KML per descarregar", - "link-link": "Enllaç", - "download-link": "Descarregar", - "ogc-link": "Enllaços WxS", - "noFormatName": "No s'ha proporcionat cap nom de format", - "noThesaurusName": "Sense nom de tesaure", - "wms-link": "Servidor Web de Mapes", - "associated-link": "Associat", - "children-link": "Fill", - "datasets-link": "Conjunt de dades", - "hasfeaturecat-link": "Catàleg de Features", - "fcats-link": "Catàleg de Features", - "parent-link": "Pare", - "related-link": "Relacionats", - "services-link": "Servei", - "siblings-link": "Germà", - "sources-link": "Origen", - "hassource-link": "Origen", - "source-link": "Origen", - "largerWorkCitation-link": "Citació de treball ampliat", - "isTemporalStatOf-link": "Estat temporal", - "stereoMate-link": "Par estereogràfic", - "crossReference-link": "Referència creuada", - "partOfSeamlessDatabase-link": "Part d'una base de dades", - "isDescriptionOf-link": "Descripció", - "inclusive": "Inclusiu", - "exclusive": "Exclusiu" -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/en-strings.json b/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/en-strings.json deleted file mode 100644 index 14bd962846e9..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/en-strings.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "general": "General", - "kml-link": "KML File for download", - "link-link": "Link", - "download-link": "Download", - "ogc-link": "WxS Links", - "noFormatName": "No format name provided", - "noThesaurusName": "No Thesaurus Name", - "wms-link": "Web Map Server", - "associated-link": "Associated", - "children-link": "Child", - "datasets-link": "Dataset", - "hasfeaturecat-link": "Feature Catalog", - "fcats-link": "Feature Catalog", - "parent-link": "Parent", - "related-link": "Related", - "services-link": "Service", - "siblings-link": "Sibling", - "sources-link": "Source", - "hassource-link": "Source", - "source-link": "Source", - "largerWorkCitation-link": "Larger Work Citation", - "isTemporalStatOf-link": "Temporal state", - "stereoMate-link": "Stereo mate", - "crossReference-link": "Cross Reference", - "partOfSeamlessDatabase-link": "Part of Seamless Database", - "isDescriptionOf-link": "Description", - "inclusive" : "Inclusive", - "exclusive" : "Exclusive" -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/es-strings.json b/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/es-strings.json deleted file mode 100644 index d3f31ce721d2..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/es-strings.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "general": "General", - "kml-link": "Fichero KML para descargar", - "link-link": "Enlace", - "download-link": "Descargar", - "ogc-link": "Enlaces WxS", - "noFormatName": "No se ha añadido un nombre de formato", - "noThesaurusName": "Sin Nombre de Tesauro", - "wms-link": "Servidor Web Map", - "associated-link": "Asociado", - "children-link": "Hijo", - "datasets-link": "Conjunto de datos", - "hasfeaturecat-link": "Catálogo de Features", - "fcats-link": "Catálogo de Features", - "parent-link": "Padre", - "related-link": "Relacionados", - "services-link": "Servicio", - "siblings-link": "Hermano", - "sources-link": "Origen", - "hassource-link": "Origen", - "source-link": "Origen", - "largerWorkCitation-link": "Cita de trabajo ampliada", - "isTemporalStatOf-link": "Estado temporal", - "stereoMate-link": "Compañero estéreo", - "crossReference-link": "Referencia cruzada", - "partOfSeamlessDatabase-link": "Parte de la base de datos original", - "isDescriptionOf-link": "Descripción", - "inclusive": "Inclusivo", - "exclusive": "Exclusivo" -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/fr-strings.json b/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/fr-strings.json deleted file mode 100644 index a4f411d161d1..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/fr-strings.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "general": "Général", - "kml-link": "Fichier KML pour téléchargement", - "link-link": "Lien", - "noFormatName": "Aucun nom de format", - "noThesaurusName": "Pas de nom de thésaurus", - "wms-link": "Serveur Web Map", - "associated-link": "Ressources associées", - "children-link": "Enfant", - "datasets-link": "Données", - "hasfeaturecat-link": "Catalogue d'attributs", - "fcats-link": "Catalogue d'attributs", - "parent-link": "Parent", - "related-link": "Associé", - "services-link": "Service", - "siblings-link": "Frères et soeurs", - "sources-link": "Source", - "hassource-link": "Source", - "source-link": "Source", - "largerWorkCitation-link": "Référence mère", - "isTemporalStatOf-link": "Temporal state", - "stereoMate-link": "Stéréo restitution", - "crossReference-link": "Référence croisée", - "partOfSeamlessDatabase-link": "Partie d'une même base de données", - "isDescriptionOf-link": "Description" -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ge-strings.json b/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ge-strings.json deleted file mode 100644 index 0aa9a9f48bc0..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ge-strings.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "general": "Allgemein", - "kml-link": "KML Datei zum herunterladen", - "link-link": "Verknüpfung", - "noFormatName": "Kein Formatname bereitgestellt", - "noThesaurusName": "Kein Thesaurus Name", - "wms-link": "Web Map Server", - "associated-link": "Verbunden", - "children-link": "Kinder", - "datasets-link": "Datenbestand", - "hasfeaturecat-link": "Feature-Katalog", - "fcats-link": "Feature-Katalog", - "parent-link": "Eltern", - "related-link": "Verwandt", - "services-link": "Dienst", - "siblings-link": "Geschwister", - "sources-link": "Quellen", - "hassource-link": "Quellen", - "source-link": "Quellen", - "largerWorkCitation-link": "Übergeordneter Datenbestand", - "isTemporalStatOf-link": "Temporal state", - "stereoMate-link": "Stereobild", - "crossReference-link": "Querverweis", - "partOfSeamlessDatabase-link": "Komponente", - "isDescriptionOf-link": "Description" -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/it-strings.json b/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/it-strings.json deleted file mode 100644 index afa5027352f7..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/it-strings.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "general": "Generale", - "kml-link": "File KML per il download", - "link-link": "Collegamento", - "noFormatName": "Nome formato non fornito", - "noThesaurusName": "Nome Thesaurus non fornito", - "wms-link": "Web Map Server", - "associated-link": "Associated", - "children-link": "Child", - "datasets-link": "Dataset", - "hasfeaturecat-link": "Feature Catalog", - "fcats-link": "Feature Catalog", - "parent-link": "Parent", - "related-link": "Related", - "services-link": "Servizio", - "siblings-link": "Sibling", - "sources-link": "Source", - "hassource-link": "Source", - "source-link": "Source", - "largerWorkCitation-link": "Riferimento a dataset principale", - "isTemporalStatOf-link": "Temporal state", - "stereoMate-link": "Accoppiamento stereo", - "crossReference-link": "Riferimento incrociato", - "partOfSeamlessDatabase-link": "Parte del database senza soluzione di continuità", - "isDescriptionOf-link": "Description" -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ko-strings.json b/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ko-strings.json deleted file mode 100644 index 22ac1d9e1668..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/ko-strings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "general": "일반", - "kml-link": "다운로드할 KML 파일", - "link-link": "링크", - "noFormatName": "제공된 포맷 이름이 없음", - "noThesaurusName": "분류어사전 이름 없음", - "wms-link": "Web Map Service URL" -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/nl-strings.json b/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/nl-strings.json deleted file mode 100644 index 92b5d9bf8350..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/nl-strings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "general": "Algemeen", - "kml-link": "KML bestand voor download", - "link-link": "Link", - "noFormatName": "Formaatnaam niet gegeven", - "noThesaurusName": "Geen Thesaurus Naam", - "wms-link": "Web Map Server URL's" -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/sk-strings.json b/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/sk-strings.json deleted file mode 100644 index 3076b5eb73ec..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/loc/sk-strings.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "general": "Veobecn", - "kml-link": "KML Sbor na stiahnutie", - "link-link": "Odkaz", - "download-link": "Odkaz na stiahnutie", - "ogc-link": "WxS Odkazy", - "noFormatName": "iadny formt poskytujci meno", - "noThesaurusName": "iadny Thesaurus meno", - "wms-link": "Webov Mapov Sluba", - "associated-link": "Spojen", - "children-link": "Dedin link", - "datasets-link": "dajov link", - "hasfeaturecat-link": "Atribtov katalg", - "fcats-link": "Atribtov katalg", - "parent-link": "Rodiovsk odkaz", - "related-link": "Prbuzn odkaz", - "services-link": "Odkaz na slubu", - "siblings-link": "Nasledujci odkaz", - "sources-link": "Zdrojov odkaz", - "hassource-link": "Zdroj", - "source-link": "Zdrojov odkaz", - "largerWorkCitation-link": "Odkaz na citciu", - "isTemporalStatOf-link": "Odkaz na doasn stav", - "stereoMate-link": "Odkaz na partnera", - "crossReference-link": "Krov odvolvka", - "partOfSeamlessDatabase-link": "as databzy", - "isDescriptionOf-link": "Popis", - "inclusive" : "Vrtane", - "exclusive" : "Vhradne" -} \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/partial_view/config.properties b/schemas/iso19139/src/main/plugin/iso19139/formatter/partial_view/config.properties deleted file mode 100644 index bdd6f5e15881..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/partial_view/config.properties +++ /dev/null @@ -1,24 +0,0 @@ -# -# Copyright (C) 2001-2016 Food and Agriculture Organization of the -# United Nations (FAO-UN), United Nations World Food Programme (WFP) -# and United Nations Environment Programme (UNEP) -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 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 -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA -# -# Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, -# Rome - Italy. email: geonetwork@osgeo.org -# - -published=false \ No newline at end of file diff --git a/schemas/iso19139/src/main/plugin/iso19139/formatter/partial_view/view.groovy b/schemas/iso19139/src/main/plugin/iso19139/formatter/partial_view/view.groovy deleted file mode 100644 index 1f10de4d5485..000000000000 --- a/schemas/iso19139/src/main/plugin/iso19139/formatter/partial_view/view.groovy +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -def isoHandlers = new iso19139.Handlers(handlers, f, env) - -isoHandlers.addDefaultHandlers() -handlers.start {} -handlers.end {} diff --git a/schemas/pom.xml b/schemas/pom.xml index 80364cf89554..9a3d6c6338ea 100644 --- a/schemas/pom.xml +++ b/schemas/pom.xml @@ -37,13 +37,6 @@ GeoNetwork schema plugins pom - - - org.codehaus.groovy - groovy-all - - - schema-core csw-record @@ -53,11 +46,7 @@ iso19115-3.2018 - - - ../.. - diff --git a/services/pom.xml b/services/pom.xml index 63a6a9d227a3..38fcadd6dfc4 100644 --- a/services/pom.xml +++ b/services/pom.xml @@ -86,11 +86,6 @@ ${project.version} - - org.codehaus.groovy - groovy-all - - org.mockito mockito-all diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/AbstractFormatService.java b/services/src/main/java/org/fao/geonet/api/records/formatters/AbstractFormatService.java index 1fdce57f005a..aee5599dae13 100644 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/AbstractFormatService.java +++ b/services/src/main/java/org/fao/geonet/api/records/formatters/AbstractFormatService.java @@ -55,7 +55,7 @@ public boolean accept(Path file) throws IOException { } private boolean isViewFileExists(Path file) { - return Files.exists(file.resolve(VIEW_GROOVY_FILENAME)) || Files.exists(file.resolve(VIEW_XSL_FILENAME)); + return Files.exists(file.resolve(VIEW_XSL_FILENAME)); } }; @@ -120,11 +120,10 @@ protected Path getAndVerifyFormatDir(GeonetworkDataDirectory dataDirectory, Stri throw new BadParameterEx(paramName, "Format bundle " + xslid + " is not a directory"); } - if (!Files.exists(formatDir.resolve(VIEW_XSL_FILENAME)) && - !Files.exists(formatDir.resolve(VIEW_GROOVY_FILENAME))) { + if (!Files.exists(formatDir.resolve(VIEW_XSL_FILENAME))) { throw new BadParameterEx(paramName, "Format bundle " + xslid + " is not a valid format bundle because it does not have a '" + - VIEW_XSL_FILENAME + "' file or a '" + VIEW_GROOVY_FILENAME + "' file."); + VIEW_XSL_FILENAME + "' file file."); } if (!containsFile(userXslDir, formatDir)) { diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/CurrentLanguageHolder.java b/services/src/main/java/org/fao/geonet/api/records/formatters/CurrentLanguageHolder.java similarity index 95% rename from services/src/main/java/org/fao/geonet/api/records/formatters/groovy/CurrentLanguageHolder.java rename to services/src/main/java/org/fao/geonet/api/records/formatters/CurrentLanguageHolder.java index 758c748ad679..e0dc6be59c0b 100644 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/CurrentLanguageHolder.java +++ b/services/src/main/java/org/fao/geonet/api/records/formatters/CurrentLanguageHolder.java @@ -20,8 +20,7 @@ * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, * Rome - Italy. email: geonetwork@osgeo.org */ - -package org.fao.geonet.api.records.formatters.groovy; +package org.fao.geonet.api.records.formatters; /** * @author Jesse on 11/28/2014. diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterAdminApi.java b/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterAdminApi.java index 38d8a059d087..2541576729a2 100644 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterAdminApi.java +++ b/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterAdminApi.java @@ -528,11 +528,6 @@ private Path findViewFile(FileSystem zipFs) throws IOException { if (Files.exists(rootView)) { return rootView; } - final String groovyView = "view.groovy"; - rootView = zipFs.getPath(groovyView); - if (Files.exists(rootView)) { - return rootView; - } final Path rootDir = zipFs.getRootDirectories().iterator().next(); try (DirectoryStream dirs = Files.newDirectoryStream(rootDir, IO.DIRECTORIES_FILTER)) { Iterator dirIter = dirs.iterator(); @@ -545,10 +540,6 @@ private Path findViewFile(FileSystem zipFs) throws IOException { if (Files.exists(rootView)) { return rootView; } - rootView = next.resolve(groovyView); - if (Files.exists(rootView)) { - return rootView; - } } } return null; diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterApi.java b/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterApi.java index 9145f38336a4..f7822452e2fe 100644 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterApi.java +++ b/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterApi.java @@ -38,11 +38,9 @@ import org.fao.geonet.ApplicationContextHolder; import org.fao.geonet.Constants; import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.API; import org.fao.geonet.api.ApiUtils; import org.fao.geonet.api.records.extent.MapRenderer; import org.fao.geonet.api.records.formatters.cache.*; -import org.fao.geonet.api.records.formatters.groovy.ParamValue; import org.fao.geonet.api.tools.i18n.LanguageUtils; import org.fao.geonet.constants.Geonet; import org.fao.geonet.domain.*; @@ -446,7 +444,7 @@ public void exec( final boolean hideWithheld = Boolean.TRUE.equals(hide_withheld) || !context.getBean(AccessManager.class).canEdit(context, resolvedId); Key key = new Key(Integer.parseInt(resolvedId), lang, formatType, xslid, hideWithheld, width); - final boolean skipPopularityBool = new ParamValue(skipPopularity).toBool(); + final boolean skipPopularityBool = skipPopularity.equals("y"); ISODate changeDate = context.getBean(EsSearchManager.class).getDocChangeDate(resolvedId); @@ -607,14 +605,10 @@ private Pair createFormatterAndParams(String lan fparams.formatterInSchemaPlugin = isFormatterInSchemaPlugin(formatDir, schemaDir); Path viewXslFile = formatDir.resolve(FormatterConstants.VIEW_XSL_FILENAME); - Path viewGroovyFile = formatDir.resolve(FormatterConstants.VIEW_GROOVY_FILENAME); FormatterImpl formatter; if (Files.exists(viewXslFile)) { fparams.viewFile = viewXslFile.toRealPath(); formatter = context.getBean(XsltFormatter.class); - } else if (Files.exists(viewGroovyFile)) { - fparams.viewFile = viewGroovyFile.toRealPath(); - formatter = context.getBean(GroovyFormatter.class); } else { throw new IllegalArgumentException("The 'xsl' parameter must be a valid id of a formatter"); } diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterConstants.java b/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterConstants.java index 766f71778cbd..46cf470ba79c 100644 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterConstants.java +++ b/services/src/main/java/org/fao/geonet/api/records/formatters/FormatterConstants.java @@ -35,6 +35,4 @@ public class FormatterConstants { public static final String USER_XSL_DIR = "user_xsl_dir"; public static final Pattern ID_XSL_REGEX = Pattern.compile("[\\w\\-.]+"); public static final String VIEW_XSL_FILENAME = "view.xsl"; - public static final String VIEW_GROOVY_FILENAME = "view.groovy"; - public static final String GROOVY_SCRIPT_ROOT = "groovy"; } diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/GroovyFormatter.java b/services/src/main/java/org/fao/geonet/api/records/formatters/GroovyFormatter.java deleted file mode 100644 index 4e997e004459..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/GroovyFormatter.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.collect.Maps; -import groovy.lang.Binding; -import groovy.lang.GroovyClassLoader; -import groovy.util.GroovyScriptEngine; -import groovy.util.ResourceException; -import groovy.util.ScriptException; -import org.codehaus.groovy.control.CompilationFailedException; -import org.fao.geonet.api.records.formatters.groovy.*; -import org.fao.geonet.api.records.formatters.groovy.template.TemplateCache; -import org.fao.geonet.kernel.GeonetworkDataDirectory; -import org.fao.geonet.kernel.SchemaManager; -import org.fao.geonet.utils.IO; -import org.jdom.Namespace; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.io.IOException; -import java.net.URL; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; - -import static org.fao.geonet.api.records.formatters.FormatterConstants.GROOVY_SCRIPT_ROOT; -import static org.fao.geonet.api.records.formatters.FormatterConstants.SCHEMA_PLUGIN_FORMATTER_DIR; - -/** - * Formatter for groovy dialect of formatters. - * - * @author Jesse on 10/15/2014. - */ -@Component -public class GroovyFormatter implements FormatterImpl { - - private final Cache transformers = CacheBuilder.newBuilder(). - concurrencyLevel(1). - maximumSize(40). - initialCapacity(40).build(); - @Autowired - private TemplateCache templateCache; - private GroovyClassLoader baseClassLoader; - private final Map schemaClassLoaders = Maps.newHashMap(); - - @VisibleForTesting - Transformer findTransformer(final FormatterParams fparams) throws ExecutionException { - return transformers.get(fparams.formatDir, new Callable() { - @Override - public Transformer call() throws Exception { - return createTransformer(fparams); - } - }); - } - - public String format(FormatterParams fparams) throws Exception { - EnvironmentProxy.clearContext(); - final Transformer transformer = createTransformer(fparams); - - EnvironmentProxy.setCurrentEnvironment(fparams); - try { - final List namespaces = fparams.context.getBean(SchemaManager.class).getSchema(fparams.schema).getNamespaces(); - return transformer.apply(fparams.metadata, namespaces); - } finally { - EnvironmentProxy.clearContext(); - } - } - - private synchronized Transformer createTransformer(FormatterParams fparams) throws Exception { - Transformer transformer = this.transformers.getIfPresent(fparams.formatDir); - - if (fparams.isDevMode() || transformer == null) { - final Path baseShared = fparams.context.getBean(GeonetworkDataDirectory.class).getFormatterDir().resolve(GROOVY_SCRIPT_ROOT); - final Path schemaFormatterDir = getSchemaPluginFormatterDir(fparams, fparams.schema); - final Path schemaShared = schemaFormatterDir.resolve(GROOVY_SCRIPT_ROOT); - GroovyClassLoader cl = getParentClassLoader(fparams, fparams.schema, baseShared, schemaShared); - - URL[] roots = new URL[]{ - IO.toURL(fparams.formatDir) - }; - GroovyScriptEngine groovyScriptEngine = new GroovyScriptEngine(roots, cl); - - loadScripts(fparams.formatDir, groovyScriptEngine); - - Handlers handlers = new Handlers(fparams, schemaShared.getParent(), baseShared.getParent(), this.templateCache); - Environment env = new EnvironmentProxy(); - Functions functions = new Functions(fparams, env); - Binding binding = new Binding(); - binding.setVariable("handlers", handlers); - binding.setVariable("env", env); - binding.setVariable("f", functions); - - final String scriptName = fparams.viewFile.toAbsolutePath().toUri().toString(); - groovyScriptEngine.run(scriptName, binding); - - transformer = new Transformer(handlers, functions, env, fparams.formatDir.toAbsolutePath()); - this.transformers.put(fparams.formatDir, transformer); - } - - return transformer; - } - - private Path getSchemaPluginFormatterDir(FormatterParams fparams, String schema) { - return fparams.context.getBean(SchemaManager.class).getSchemaDir(schema).resolve(SCHEMA_PLUGIN_FORMATTER_DIR); - } - - private GroovyClassLoader getParentClassLoader(FormatterParams fparams, String schema, Path baseShared, Path schemaShared) throws IOException, - ResourceException, ScriptException { - GroovyClassLoader cl = this.schemaClassLoaders.get(schema); - if (fparams.isDevMode() || cl == null) { - final GroovyClassLoader parent; - ConfigFile newConfig = new ConfigFile(getSchemaPluginFormatterDir(fparams, schema), false, null); - final String dependOnSchema = newConfig.dependOn(); - if (dependOnSchema != null) { - Path dependent = getSchemaPluginFormatterDir(fparams, dependOnSchema).resolve(GROOVY_SCRIPT_ROOT); - parent = getParentClassLoader(fparams, dependOnSchema, baseShared, dependent); - } else { - if (fparams.isDevMode() || this.baseClassLoader == null) { - URL[] roots = new URL[]{IO.toURL(baseShared)}; - GroovyScriptEngine groovyScriptEngine = new GroovyScriptEngine(roots); - loadScripts(baseShared, groovyScriptEngine); - this.baseClassLoader = groovyScriptEngine.getGroovyClassLoader(); - } - parent = this.baseClassLoader; - } - - URL[] roots = new URL[]{IO.toURL(schemaShared)}; - GroovyScriptEngine groovyScriptEngine = new GroovyScriptEngine(roots, parent); - - loadScripts(schemaShared, groovyScriptEngine); - cl = groovyScriptEngine.getGroovyClassLoader(); - this.schemaClassLoaders.put(schema, cl); - } - - return cl; - } - - private void loadScripts(Path baseShared, final GroovyScriptEngine gse) throws ResourceException, ScriptException, IOException { - if (!Files.exists(baseShared)) { - return; - } - final Map compileErrors = Maps.newHashMap(); - Files.walkFileTree(baseShared, new SimpleFileVisitor() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - try (DirectoryStream paths = Files.newDirectoryStream(dir, "*.groovy")) { - for (Path path : paths) { - if (!Files.isDirectory(path)) { - try { - gse.loadScriptByName(path.toUri().toString()); - } catch (CompilationFailedException e) { - compileErrors.put(path, null); - } catch (ScriptException | ResourceException e) { - throw new RuntimeException(e); - } - - } - } - } - return FileVisitResult.CONTINUE; - } - }); - - int numErrors = 0; - - while (numErrors != compileErrors.size() && compileErrors.size() > 0) { - numErrors = compileErrors.size(); - Iterator iter = compileErrors.keySet().iterator(); - while (iter.hasNext()) { - Path file = iter.next(); - try { - gse.loadScriptByName(file.toUri().toString()); - iter.remove(); - } catch (CompilationFailedException e) { - compileErrors.put(file, e); - // skip - } - } - - if (!compileErrors.isEmpty()) { - StringBuilder errorMsg = new StringBuilder("Errors occurred while compiling files:"); - - for (Map.Entry entry : compileErrors.entrySet()) { - errorMsg.append("\n\n").append(entry.getKey()).append(":\n").append(entry.getValue().getMessage()); - } - - throw new AssertionError(errorMsg.toString()); - } - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/SchemaLocalizations.java b/services/src/main/java/org/fao/geonet/api/records/formatters/SchemaLocalizations.java index de03b3bf6a83..fa626d2ba310 100644 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/SchemaLocalizations.java +++ b/services/src/main/java/org/fao/geonet/api/records/formatters/SchemaLocalizations.java @@ -26,11 +26,9 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.*; -import groovy.util.slurpersupport.GPathResult; import jeeves.server.context.ServiceContext; import jeeves.server.dispatchers.guiservices.XmlFile; import org.fao.geonet.ApplicationContextHolder; -import org.fao.geonet.api.records.formatters.groovy.CurrentLanguageHolder; import org.fao.geonet.api.tools.i18n.LanguageUtils; import org.fao.geonet.constants.Geonet; import org.fao.geonet.domain.IsoLanguage; @@ -156,17 +154,6 @@ protected Map getSchemaLocalizations(ApplicationCont return loadSchemaLocalizations(context, schemaManager); } - /** - * Obtain a translation for the given node by looking up the elements name in the the schema's - * labels.xml file - * - * @param node the node to get a translation for. - */ - public String nodeLabel(GPathResult node) throws Exception { - String parentNodeName = parentNodeName(node); - return nodeLabel(node.name(), parentNodeName); - } - /** * Look up a translation in the schema's labels.xml file * @@ -178,26 +165,6 @@ public String nodeLabel(String qualifiedNodeName, String qualifiedParentNodeName return nodeTranslation(qualifiedNodeName, qualifiedParentNodeName, "label"); } - /** - * Obtain the description for the given node by looking up the elements name in the the schema's - * labels.xml file - * - * @param node the node to get a description for. - */ - public String nodeDesc(GPathResult node) throws Exception { - String parentNodeName = parentNodeName(node); - return nodeDesc(node.name(), parentNodeName); - } - - protected String parentNodeName(GPathResult node) { - GPathResult parentNode = node.parent(); - String parentNodeName = null; - if (parentNode != node) { - parentNodeName = parentNode.name(); - } - return parentNodeName; - } - /** * Look up a description in the schema's labels.xml file * @@ -236,15 +203,6 @@ public String nodeTranslation(String qualifiedNodeName, String qualifiedParentNo return qualifiedNodeName; } - /** - * Obtain a translation for the given codelist by looking up the codelist and codelist value in - * the the schema's codelists.xml file * @param node a node containing a codeListValue attribute - * and a codeList attribute - */ - public String codelistValueLabel(GPathResult node) throws Exception { - return codelistValueLabel(node.getProperty("@codeList").toString(), node.getProperty("@codeListValue").toString()); - } - /** * Obtain a translation for the given codelist by looking up the codelist and codelist value in * the the schema's codelists.xml file. @@ -256,16 +214,6 @@ public String codelistValueLabel(String codelist, String value) throws Exception return codelistTranslation(codelist, value, "label"); } - /** - * Obtain the description for the given codelist by looking up the codelist and codelist value - * in the the schema's codelists.xml file. - * - * @param node a node containing a codeListValue attribute and a codeList attribute - */ - public String codelistValueDesc(GPathResult node) throws Exception { - return codelistValueDesc(node.getProperty("@codeList").toString(), node.getProperty("@codeListValue").toString()); - } - /** * Obtain the description for the given codelist by looking up the codelist and codelist value * in the the schema's codelists.xml file. @@ -360,8 +308,8 @@ public String schemaString(String... key) throws Exception { for (SchemaLocalization schemaLocalization : this.schemaLocalizations) { Element strings = schemaLocalization.getStrings(this.languageHolder.getLang3()); - for (int i = 0; i < key.length; i++) { - strings = strings.getChild(key[i]); + for (String s : key) { + strings = strings.getChild(s); if (strings == null) { break; } @@ -373,5 +321,4 @@ public String schemaString(String... key) throws Exception { return "[" + Joiner.on(',').join(key) + "]"; } - } diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Environment.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Environment.java deleted file mode 100644 index 4cb133b3ff59..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Environment.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import com.google.common.base.Optional; -import com.google.common.collect.Multimap; -import jeeves.server.context.ServiceContext; -import org.fao.geonet.api.records.formatters.FormatType; -import org.fao.geonet.api.records.formatters.FormatterWidth; -import org.jdom.Element; -import org.springframework.security.core.Authentication; - -import java.util.Collection; -import java.util.Map; - -/** - * Contains methods for accessing data regarding the current user and request, such as the current - * UI language, username, the parameters passed to the format request, etc... - * - * IMPORTANT: This class cannot be used while registering handlers, sorters, etc... - * Only when the XML processing is under way can it be used. If used during setup of the handlers - * then an exception will be thrown. The reason this object is bound to the script is so that it - * can be used within any handler and object created can be passed the object for use without having - * to do any crazy gymnastics. - * - * @author Jesse on 10/20/2014. - */ -public interface Environment extends CurrentLanguageHolder { - /** - * Return the id of the metadata - */ - int getMetadataId(); - - /** - * Return the UUID of the metadata - */ - String getMetadataUUID(); - - /** - * The URL to use in the html when accessing resources in the formatter resource package. Simply - * append the relative path of the resource from the formatter bundle directory. - */ - String getResourceUrl(); - - /** - * The url to use when making a service call. This string will contain the full url up to but - * not including the servive for example: http://localhost:8080/geonetwork/srv/eng/ - */ - String getLocalizedUrl(); - - /** - * Get the current user's authentication information. - */ - Authentication getAuth(); - - /** - * Get the Format output type of this request. (html, xml, pdf, etc...) - */ - FormatType getFormatType(); - - /** - * Get the approximate size of the element that the formatter output will be embedded in - * compared to the full device width. Allowed options are the enum values: {@link - * org.fao.geonet.api.records.formatters.FormatterWidth} - */ - FormatterWidth getEmbeddingWidth(); - - /** - * Return the map of all parameters passed to the Format service. - */ - Multimap params(); - - /** - * Return the value of the first parameter with the provided name. Null is returned if there is - * no parameter with the given name. - */ - ParamValue param(String paramName); - - /** - * Return ALL values of parameter with the provided name. - */ - Collection paramValues(String paramName); - - /** - * Get the request headers for the given name. - * - * @param name the name of the header to get - * @return the request headers for the given name. - */ - Collection getHeaders(String name); - - /** - * Get the request header for the given name. - * - * @param name the name of the header to get - * @return the request header for the given name. - */ - Optional getHeader(String name); - - /** - * Return the metadata document as a jdom Element. json is the XML API used typically in - * geonetwork. This is useful when one needs to call back into the Geonetwork classes. - */ - Element getMetadataElement(); - - /** - * Returns the data in the index for the current metadata. - */ - Map> getIndexInfo() throws Exception; - - /** - * Get the service context - * - * @return the context - */ - ServiceContext getContext(); - - /** - * Get a Spring Bean from Spring Application Context. - * - * @param clazz the type of bean to look up. - */ - T getBean(Class clazz); - - /** - * Get a Spring Bean from Spring Application Context. - * - * @param name the name. - * @param clazz the type of bean to look up. - */ - T getBean(String name, Class clazz); - - /** - * Retrieves the background, width and mapproj parameters from settings and puts them into the - * map config. - */ - MapConfig getMapConfiguration(); - - /** - * Return true is the current user has edit permissions for the current metadata - */ - boolean canEdit() throws Exception; -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/EnvironmentImpl.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/EnvironmentImpl.java deleted file mode 100644 index 923336221a88..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/EnvironmentImpl.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import com.google.common.base.Optional; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimap; -import jeeves.server.context.ServiceContext; -import org.apache.commons.lang.NotImplementedException; -import org.fao.geonet.api.records.formatters.FormatType; -import org.fao.geonet.api.records.formatters.FormatterParams; -import org.fao.geonet.api.records.formatters.FormatterWidth; -import org.fao.geonet.domain.AbstractMetadata; -import org.fao.geonet.kernel.AccessManager; -import org.fao.geonet.kernel.search.EsSearchManager; -import org.fao.geonet.kernel.setting.SettingManager; -import org.fao.geonet.kernel.setting.Settings; -import org.fao.geonet.languages.IsoLanguagesMapper; -import org.jdom.Element; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.web.context.request.WebRequest; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -/** - * The actual Environment implementation. - * - * @author Jesse on 10/20/2014. - */ -public class EnvironmentImpl implements Environment { - private final String lang3; - private final String lang2; - private final String resourceUrl; - private final Multimap params = ArrayListMultimap.create(); - private final FormatType formatType; - private final AbstractMetadata metadataInfo; - private final String locUrl; - private final Element jdomMetadata; - private final ServiceContext serviceContext; - private final WebRequest webRequest; - private final FormatterWidth width; - private final Multimap indexInfo = null; - - public EnvironmentImpl(FormatterParams fparams, IsoLanguagesMapper mapper) { - jdomMetadata = fparams.metadata; - this.width = fparams.width; - this.lang3 = fparams.context.getLanguage(); - this.lang2 = mapper.iso639_2_to_iso639_1(lang3, "en"); - - this.formatType = fparams.formatType; - this.resourceUrl = fparams.getResourceUrl(); - this.locUrl = fparams.getLocUrl(); - this.metadataInfo = fparams.metadataInfo; - for (Map.Entry entry : fparams.webRequest.getParameterMap().entrySet()) { - for (String value : entry.getValue()) { - this.params.put(entry.getKey(), new ParamValue(value)); - } - } - - this.webRequest = fparams.webRequest; - this.serviceContext = fparams.context; - } - - /** - * Return the map of all parameters passed to the Format service. - */ - public Multimap params() { - return this.params; - } - - /** - * Return the value of the first parameter with the provided name. Null is returned if there is - * no parameter with the given name. - */ - public ParamValue param(String paramName) { - final Collection paramValues = this.params.get(paramName); - if (paramValues.isEmpty()) { - return new ParamValue("") { - @Override - public String toString() { - return "Null Value"; - } - - @Override - public boolean toBool() { - return false; - } - - @Override - public int toInt() { - return -1; - } - - @Override - public Double toDouble() { - return -1.0; - } - }; - } - return paramValues.iterator().next(); - } - - /** - * Return ALL values of parameter with the provided name. - */ - public Collection paramValues(String paramName) { - return this.params.get(paramName); - } - - public String getLang3() { - return this.lang3; - } - - public String getLang2() { - return this.lang2; - } - - @Override - public int getMetadataId() { - return this.metadataInfo.getId(); - } - - @Override - public String getMetadataUUID() { - return this.metadataInfo.getUuid(); - - } - - @Override - public String getResourceUrl() { - return this.resourceUrl; - } - - @Override - public String getLocalizedUrl() { - return this.locUrl; - } - - @Override - public Authentication getAuth() { - SecurityContext context = SecurityContextHolder.getContext(); - if (context != null) { - return context.getAuthentication(); - } - return null; - } - - @Override - public FormatType getFormatType() { - return this.formatType; - } - - @Override - public FormatterWidth getEmbeddingWidth() { - return this.width; - } - - @Override - public Element getMetadataElement() { - return this.jdomMetadata; - } - - @Override - public synchronized Map> getIndexInfo() throws Exception { - if (this.indexInfo == null) { - final EsSearchManager searchManager = getBean(EsSearchManager.class); - - throw new NotImplementedException("Not implemented in ES"); - -// try (IndexAndTaxonomy newIndexReader = searchManager.getNewIndexReader(getLang3())) { -// TopFieldCollector collector = TopFieldCollector.create(Sort.RELEVANCE, 1, true, false, false, false); -// IndexSearcher searcher = new IndexSearcher(newIndexReader.indexReader); -// Query query = new TermQuery(new Term("_id", String.valueOf(getMetadataId()))); -// searcher.search(query, collector); -// ScoreDoc[] topDocs = collector.topDocs().scoreDocs; -// -// Multimap fields = HashMultimap.create(); -// for (ScoreDoc scoreDoc : topDocs) { -// Document doc = searcher.doc(scoreDoc.doc); -// for (IndexableField field : doc) { -// fields.put(field.name(), field.stringValue()); -// } -// } -// this.indexInfo = fields; -// } - - } - return Collections.unmodifiableMap(this.indexInfo.asMap()); - } - - @Override - public ServiceContext getContext() { - return this.serviceContext; - } - - @Override - public T getBean(Class clazz) { - return this.serviceContext.getBean(clazz); - } - - @Override - public T getBean(String name, Class clazz) { - return this.serviceContext.getBean(name, clazz); - } - - @Override - public MapConfig getMapConfiguration() { - final SettingManager settingManager = this.serviceContext.getBean(SettingManager.class); - final String background = settingManager.getValue(Settings.REGION_GETMAP_BACKGROUND); - final String mapproj = settingManager.getValue(Settings.REGION_GETMAP_MAPPROJ); - final Integer width = settingManager.getValueAsInt(Settings.REGION_GETMAP_WIDTH); - final Integer thumbnailWidth = settingManager.getValueAsInt(Settings.REGION_GETMAP_SUMMARY_WIDTH); - return new MapConfig(background, mapproj, width, thumbnailWidth); - } - - @Override - public boolean canEdit() throws Exception { - final AccessManager bean = serviceContext.getBean(AccessManager.class); - return bean.isOwner(serviceContext, this.metadataInfo.getSourceInfo()) - || bean.hasEditPermission(serviceContext, String.valueOf(this.metadataInfo.getId())); - } - - @Override - public Optional getHeader(String name) { - return Optional.fromNullable(webRequest.getHeader(name)); - } - - public Collection getHeaders(final String name) { - return Arrays.asList(webRequest.getHeaderValues(name)); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/EnvironmentProxy.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/EnvironmentProxy.java deleted file mode 100644 index 0cf37d0d91d2..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/EnvironmentProxy.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import com.google.common.base.Optional; -import com.google.common.collect.Multimap; -import jeeves.server.context.ServiceContext; -import org.fao.geonet.api.records.formatters.FormatType; -import org.fao.geonet.api.records.formatters.FormatterParams; -import org.fao.geonet.api.records.formatters.FormatterWidth; -import org.fao.geonet.languages.IsoLanguagesMapper; -import org.jdom.Element; -import org.springframework.security.core.Authentication; - -import java.util.Collection; -import java.util.Map; - -/** - * This class is the actual object passed to the Groovy script. It looks up in the current - * ThreadLocal the environment object for the current request. - * - * @author Jesse on 10/20/2014. - */ -public class EnvironmentProxy implements Environment { - private static final ThreadLocal currentEnvironment = new InheritableThreadLocal(); - - public static void setCurrentEnvironment(FormatterParams fparams) { - currentEnvironment.set(new EnvironmentImpl(fparams, fparams.context.getBean(IsoLanguagesMapper.class))); - } - - public static void clearContext() { - currentEnvironment.set(null); - } - - private static Environment get() { - final Environment env = currentEnvironment.get(); - if (env == null) { - throw new AssertionError( - "The Environment object cannot be used at the moment, it can only be used during XML processing," + - " not during the configuration stage. It is accessible here only so that it is in scope in all" + - " handlers without having to pass it in as a parameter to all handlers and sorters and similar" + - " object used for XML processing"); - } - - return env; - } - - @Override - public String getLang3() { - return get().getLang3(); - } - - @Override - public String getLang2() { - return get().getLang2(); - } - - @Override - public int getMetadataId() { - return get().getMetadataId(); - } - - @Override - public String getMetadataUUID() { - return get().getMetadataUUID(); - } - - @Override - public String getResourceUrl() { - return get().getResourceUrl(); - } - - @Override - public String getLocalizedUrl() { - return get().getLocalizedUrl(); - } - - @Override - public Authentication getAuth() { - return get().getAuth(); - } - - @Override - public FormatType getFormatType() { - return get().getFormatType(); - } - - @Override - public FormatterWidth getEmbeddingWidth() { - return get().getEmbeddingWidth(); - } - - @Override - public Multimap params() { - return get().params(); - } - - @Override - public ParamValue param(String paramName) { - return get().param(paramName); - } - - @Override - public Collection paramValues(String paramName) { - return get().paramValues(paramName); - } - - @Override - public Collection getHeaders(String name) { - return get().getHeaders(name); - } - - @Override - public Optional getHeader(String name) { - return get().getHeader(name); - } - - @Override - public Element getMetadataElement() { - return get().getMetadataElement(); - } - - @Override - public Map> getIndexInfo() throws Exception { - return get().getIndexInfo(); - } - - @Override - public ServiceContext getContext() { - return get().getContext(); - } - - @Override - public T getBean(Class clazz) { - return get().getBean(clazz); - } - - @Override - public T getBean(final String name, final Class clazz) { - return get().getBean(name, clazz); - } - - @Override - public MapConfig getMapConfiguration() { - return get().getMapConfiguration(); - } - - @Override - public boolean canEdit() throws Exception { - return get().canEdit(); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Functions.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Functions.java deleted file mode 100644 index 5e9cff2b9bd6..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Functions.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import com.google.common.io.Closer; -import groovy.lang.Closure; -import groovy.util.IndentPrinter; -import groovy.util.slurpersupport.GPathResult; -import groovy.xml.MarkupBuilder; -import org.fao.geonet.api.records.formatters.ConfigFile; -import org.fao.geonet.api.records.formatters.FormatterConstants; -import org.fao.geonet.api.records.formatters.FormatterParams; -import org.fao.geonet.api.records.formatters.SchemaLocalizations; -import org.fao.geonet.constants.Geonet; -import org.fao.geonet.kernel.SchemaManager; -import org.fao.geonet.kernel.schema.SchemaPlugin; -import org.fao.geonet.util.LangUtils; -import org.jdom.Element; -import org.jdom.JDOMException; - -import java.io.IOException; -import java.io.StringWriter; -import java.nio.file.Path; -import java.util.List; -import java.util.Map; - -/** - * Contains several functions and properties which can be used when implementing view.groovy - * formatter files (or the helper classes). - * - * @author Jesse on 10/16/2014. - */ -public class Functions extends SchemaLocalizations { - - private final Environment env; - private final FormatterParams fparams; - private final SchemaPlugin schemaPlugin; - - public Functions(FormatterParams fparams, Environment env) throws Exception { - super(fparams.context.getApplicationContext(), env, fparams.schema, fparams.config.dependOn()); - - this.env = env; - this.schemaPlugin = SchemaManager.getSchemaPlugin(fparams.schema); - this.fparams = fparams; - } - - /** - * Creates a groovy.xml.MarkupBuilder object and executes the closure with the MarkupBuilder as - * its parameter. - *

- * The xml created with the MarkupBuilder is returned as a string. - * - * @param htmlFunction function that uses the MarkupBuilder to create xml or html - */ - public String html(Closure htmlFunction) { - Closer closer = Closer.create(); - try { - final StringWriter writer = closer.register(new StringWriter()); - final IndentPrinter indentPrinter = new IndentPrinter(writer, " ", true, false); - MarkupBuilder html = new MarkupBuilder(indentPrinter); - htmlFunction.call(html); - return writer.toString(); - } finally { - try { - closer.close(); - } catch (IOException e) { - throw new Error(e); - } - } - } - - /** - * Obtain strings from the formatter, the formatter's schema shared translations or - * web/src/main/webapp/loc/???/formatter.xml . - * - * @param key the key to use for looking up the translation - */ - public String translate(String key) throws Exception { - return translate(key, null); - } - - /** - * Obtain strings from the formatter, the formatter's schema shared translations or - * web/src/main/webapp/loc/???/formatter.xml. - * - * @param key the key to use for looking up the translation - * @param file the name of the xml file to get the strings from (without the .xml). This may be - * null in which case all files will be searched. if null then for the shared - * translations the formatter.xml file will be used (web/src/main/webapp/loc/???/formatter.xml) - * and all the formatter translation files will be searched. If this is non-null - * then the formatter translation file will be used if found in the file and the - * method will fallback to searching web/src/main/webapp/loc/???/&file>.xml - */ - public String translate(String key, String file) throws Exception { - String value = translateFromFormatterResources(key, file); - if (value == null || value.isEmpty()) { - value = translateFromSchema(fparams.schemaDir, key, file); - } - if (value == null || value.isEmpty()) { - value = translateFromShared(key, file == null ? "formatter" : file); - } - if (value == null || value.isEmpty()) { - return key; - } - return value; - } - - private String translateFromSchema(Path schemaDir, String key, String file) throws Exception { - final Path formatterDir = schemaDir.resolve(FormatterConstants.SCHEMA_PLUGIN_FORMATTER_DIR); - final Element translations = getFormatterTranslations(formatterDir); - Element currLanTranslations = translations.getChild(env.getLang3()); - String translation = translateFrom(key, file, currLanTranslations); - if (translation == null) { - final ConfigFile configFile = new ConfigFile(formatterDir, false, schemaDir); - if (configFile.dependOn() != null) { - final SchemaManager schemaManager = fparams.context.getBean(SchemaManager.class); - final Path parentSchemaDir = schemaManager.getSchemaDir(configFile.dependOn()); - translation = translateFromSchema(parentSchemaDir, key, file); - } - } - return translation; - } - - private String translateFromFormatterResources(String key, String file) throws Exception { - final Element translations = getFormatterTranslations(fparams.formatDir); - Element currLanTranslations = translations.getChild(env.getLang3()); - return translateFrom(key, file, currLanTranslations); - } - - private String translateFrom(String key, String file, Element currLanTranslations) { - if (currLanTranslations == null) { - return null; - } - String translation = null; - if (file == null) { - @SuppressWarnings("unchecked") - List files = currLanTranslations.getChildren(); - for (Element element : files) { - translation = element.getChildText(key); - if (translation != null) { - break; - } - } - } else { - final Element fileTranslations = currLanTranslations.getChild(file); - if (fileTranslations != null) { - translation = fileTranslations.getChildText(key); - } - } - return translation; - } - - protected String translateFromShared(String key, String file) throws JDOMException, IOException { - final Map translations = LangUtils.translate(fparams.context.getApplicationContext(), file, key); - String value = translations.get(env.getLang3()); - if (value == null) { - value = translations.get(Geonet.DEFAULT_LANGUAGE); - } - if (value == null && !translations.isEmpty()) { - value = translations.values().iterator().next(); - } - return value; - } - - public SchemaPlugin getSchemaPlugin() { - return this.schemaPlugin; - } - - private Element getFormatterTranslations(Path dir) throws Exception { - return fparams.format.getPluginLocResources(fparams.context, dir); - } - - public String getXPathFrom(GPathResult path) { - if (path == null) { - return ""; - } - - final GPathResult parent = path.parent(); - if (parent == path) { - return ""; - } - - StringBuilder currPath = new StringBuilder(getXPathFrom(parent)); - if (currPath.length() > 0) { - currPath.append("/"); - } - currPath.append(path.name()); - - final GPathResult singlingsAndSelf = (GPathResult) parent.getProperty(path.name()); - if (singlingsAndSelf.size() > 1) { - final int i = singlingsAndSelf.list().indexOf(path); - currPath.append('[').append(i + 1).append(']'); - } - - return currPath.toString(); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Handler.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Handler.java deleted file mode 100644 index b09ec1d1ee31..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Handler.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.lang.Closure; -import groovy.util.slurpersupport.GPathResult; - -import java.io.IOException; -import java.util.List; - -/** - * Represents a Handler for handling Xml elements and returning the resulting data. - * - * @author Jesse on 10/15/2014. - */ -public abstract class Handler extends Selectable implements Comparable { - private final Closure handlerFunction; - private boolean group = false; - - public Handler(int priority, Closure handlerFunction) { - super(priority); - this.handlerFunction = handlerFunction; - } - - /** - * Process the result of the handler function. - */ - public static void processResult(Object result, StringBuilder resultantXml) throws IOException { - if (result == null) { - return; - } - - resultantXml.append(result); - } - - protected static void createPath(GPathResult element, StringBuilder path) { - createPath(element, path, 0); - } - - protected static void createPath(GPathResult element, StringBuilder path, int depth) { - if (element != null) { - if (depth > 10) { - path.append("... >"); - } else { - if (element.parent() != element) { - createPath(element.parent(), path, depth + 1); - path.append(">"); - } - } - path.append(element.name()); - } - } - - @Override - public int compareTo(Handler o) { - return Integer.compare(o.priority, this.priority); - } - - public HandlerResult handle(TransformationContext context, List elem, StringBuilder resultantXml) - throws IOException { - Logging.debug("Executing handler '%2$s' on element %1$s.", elem, this); - Object elParam = null; - if (group) { - elParam = elem; - } else if (!elem.isEmpty()) { - elParam = elem.get(0); - } - - final int maximumNumberOfParameters = this.handlerFunction.getMaximumNumberOfParameters(); - Object result; - switch (maximumNumberOfParameters) { - case 0: - result = this.handlerFunction.call(); - break; - case 1: - result = this.handlerFunction.call(elParam); - break; - case 2: - result = this.handlerFunction.call(elParam, context); - break; - default: - throw new IllegalStateException("Too many arguments in handler '" + this + "' there are: " + - maximumNumberOfParameters); - } - - processResult(result, resultantXml); - return new HandlerResult(); - } - - public boolean isGroup() { - return group; - } - - public void setGroup(boolean group) { - this.group = group; - } - - @Override - public final String extraToString() { - return handlerExtraToString(); - } - - protected abstract String handlerExtraToString(); -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerFunctionSelect.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerFunctionSelect.java deleted file mode 100644 index 98cf68d0793d..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerFunctionSelect.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.lang.Closure; -import groovy.util.slurpersupport.GPathResult; - -/** - * @author Jesse on 10/16/2014. - */ -public class HandlerFunctionSelect extends Handler { - private final Closure selectFunction; - - public HandlerFunctionSelect(Closure select, int priority, Closure handlerFunction) { - super(priority, handlerFunction); - this.selectFunction = select; - } - - @Override - public boolean select(TransformationContext rootPath, GPathResult elem) { - final int maximumNumberOfParameters = this.selectFunction.getMaximumNumberOfParameters(); - boolean matches; - switch (maximumNumberOfParameters) { - case 0: - matches = (boolean) this.selectFunction.call(); - break; - case 1: - matches = (boolean) this.selectFunction.call(elem); - break; - case 2: - StringBuilder path = new StringBuilder(); - createPath(elem, path); - matches = (boolean) this.selectFunction.call(elem, path.toString()); - break; - default: - throw new IllegalStateException("Too many arguments in handler '" + this + "' there are: " + maximumNumberOfParameters); - } - - return matches; - } - - @Override - protected String handlerExtraToString() { - return ""; - } - -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerNameSelect.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerNameSelect.java deleted file mode 100644 index 3d56105dc670..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerNameSelect.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.lang.Closure; -import groovy.util.slurpersupport.GPathResult; - -import java.util.regex.Pattern; - -/** - * A Handler where the function will be executed if the element's qualified name matches the - * pattern. - * - * @author Jesse on 10/15/2014. - */ -public class HandlerNameSelect extends Handler { - private final Pattern namePattern; - - public HandlerNameSelect(Pattern namePattern, int priority, Closure handler) { - super(priority, handler); - this.namePattern = namePattern; - setName(namePattern.toString()); - } - - @Override - public boolean select(TransformationContext rootPath, GPathResult element) { - final String qualifiedName = element.name(); - return namePattern.matcher(qualifiedName).matches(); - } - - @Override - protected String handlerExtraToString() { - return ", namePattern ~= /" + namePattern + "/"; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerPathSelect.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerPathSelect.java deleted file mode 100644 index 7f436195c284..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerPathSelect.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.lang.Closure; -import groovy.util.slurpersupport.GPathResult; - -import java.util.regex.Pattern; - -/** - * A Handler that is applied when the path of the element matches the path pattern of this handler. - *

- * The path is separated by > characters - * - * @author Jesse on 10/15/2014. - */ -public class HandlerPathSelect extends Handler { - private final Pattern pathPattern; - - public HandlerPathSelect(Pattern pathPattern, int priority, Closure handler) { - super(priority, handler); - this.pathPattern = pathPattern; - } - - @Override - public boolean select(TransformationContext context, GPathResult element) { - StringBuilder path = new StringBuilder(context.getRootPath()); - if (path.length() > 0) { - path.append(">"); - } - createPath(element, path); - return this.pathPattern.matcher(path.toString()).matches(); - } - - @Override - protected String handlerExtraToString() { - return ", pathPattern ~= /" + pathPattern + "/"; - } - -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerResult.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerResult.java deleted file mode 100644 index ecc5bfe11f70..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/HandlerResult.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -/** - * Contains the results of handling an element. - * - * @author Jesse on 10/15/2014. - */ -public class HandlerResult { -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Handlers.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Handlers.java deleted file mode 100644 index bc8868b31856..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Handlers.java +++ /dev/null @@ -1,614 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import com.google.common.collect.*; -import groovy.lang.Closure; -import groovy.lang.GString; -import groovy.util.ClosureComparator; -import groovy.util.slurpersupport.GPathResult; -import org.fao.geonet.api.records.formatters.FormatterParams; -import org.fao.geonet.api.records.formatters.groovy.template.FileResult; -import org.fao.geonet.api.records.formatters.groovy.template.TemplateCache; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.regex.Pattern; - -/** - * Used for registering Element handlers and in many ways configuring the view. - * - * @author Jesse on 10/15/2014. - */ -public class Handlers { - static final String HANDLER_SELECT = "select"; - - private final Path formatterDir; - private final Path schemaDir; - private final Path rootFormatterDir; - private final TemplateCache templateCache; - TransformEngine transformationEngine = new TransformEngine(this); - StartEndHandler startHandler = new StartEndHandler(null); - StartEndHandler endHandler = new StartEndHandler(null); - private Set roots = Sets.newHashSet(); - private final List skipElements = Lists.newArrayList(); - private Callable> functionRoots = null; - /** - * ModeId -> Mode mapping - */ - private Map modes = Maps.newHashMap(); - /** - * ModeId -> Sorter mapping - */ - private ListMultimap sorters = ArrayListMultimap.create(); - /** - * ModeId -> Handler mapping - */ - private ListMultimap handlers = ArrayListMultimap.create(); - - public Handlers(FormatterParams fparams, Path schemaDir, Path rootFormatterDir, - TemplateCache templateCache) { - this.formatterDir = fparams.formatDir; - this.schemaDir = schemaDir; - this.rootFormatterDir = rootFormatterDir; - this.templateCache = templateCache; - } - - /** - * Executed once when transformer is created. This locks down the handler configuration so that - * it is not modifiable any more. - */ - public void prepareForTransformer() { - for (String id : this.handlers.keySet()) { - Collections.sort(this.handlers.get(id)); - } - this.handlers = Multimaps.unmodifiableListMultimap(this.handlers); - for (String id : this.sorters.keySet()) { - Collections.sort(this.sorters.get(id)); - } - this.sorters = Multimaps.unmodifiableListMultimap(this.sorters); - this.modes = Collections.unmodifiableMap(this.modes); - this.roots = Collections.unmodifiableSet(this.roots); - } - - /** - * Set the xpaths for selecting the roots for processing the metadata. - *

- * Each xpath should be the type of xpath used when calling {@link - * org.fao.geonet.utils.Xml#selectNodes(org.jdom.Element, String, java.util.List)} - */ - public void roots(Object... xpaths) { - this.roots.clear(); - this.functionRoots = null; - for (Object xpath : xpaths) { - this.roots.add(xpath.toString()); - } - } - - - /** - * Set the xpaths for selecting the roots for processing the metadata. - *

- * Each xpath should be the type of xpath used when calling {@link - * org.fao.geonet.utils.Xml#selectNodes(org.jdom.Element, String, java.util.List)} - */ - @SuppressWarnings("unchecked") - public void roots(Closure rootFunction) { - this.roots.clear(); - this.functionRoots = rootFunction; - } - - public Set getRoots() throws Exception { - final HashSet allRoots = Sets.newHashSet(this.roots); - if (this.functionRoots != null) { - Iterable fromFunc = this.functionRoots.call(); - for (Object root : fromFunc) { - allRoots.add(root.toString()); - } - } - return allRoots; - } - - /** - * Add a root xpath selector to the set of roots. - *

- * The xpath should be the type of xpath used when calling {@link org.fao.geonet.utils.Xml#selectNodes(org.jdom.Element, - * String, java.util.List)} - */ - public void root(Object xpath) { - this.roots.add(xpath.toString()); - } - - /** - * Add an "skip element". A skip element is an element that shouldn't be processed but some of - * its children should be. For example a formatter for iso19139 may not want to show the - * informationInfo elements but does want to display its children. The match can be - * gmd:informationInfo and the childSelector can be the closure {it.children()} - * - * @param select a string which is the element name of the element to skip or a closure - * that takes an element and returns boolean - * @param childSelector a closure that returns the children to process. The element selected by - * 'select' will be passed to the closure - */ - public SkipElement skip(Object select, Closure childSelector) { - return skip(select, childSelector, 0); - } - - /** - * Add an "skip element". A skip element is an element that shouldn't be processed but some of - * its children should be. For example a formatter for iso19139 may not want to show the - * informationInfo elements but does want to display its children. The match can be - * gmd:informationInfo and the childSelector can be the closure {it.children()} - * - * @param select a string which is the element name of the element to skip or a closure - * that takes an element and returns boolean - * @param childSelector a closure that returns the children to process. The element selected by - * 'select' will be passed to the closure - * @param priority priority of the skipElement - */ - public SkipElement skip(Object select, Closure childSelector, int priority) { - final SkipElement skipElement; - if (select instanceof String) { - final Pattern pattern = Pattern.compile(Pattern.quote((String) select)); - skipElement = new SkipElementPattern(pattern, priority, childSelector); - } else if (select instanceof GString) { - final GString gString = (GString) select; - final Pattern pattern = Pattern.compile(Pattern.quote(gString.toString())); - skipElement = new SkipElementPattern(pattern, priority, childSelector); - } else if (select instanceof Closure) { - Closure closure = (Closure) select; - skipElement = new SkipElementClosure(closure, priority, childSelector); - } else { - throw new IllegalArgumentException("select must either be a string or a closure but was a: " + select.getClass()); - } - - this.skipElements.add(skipElement); - return skipElement; - } - - /** - * Create a handler from a map of properties to values. There must be a 'select' attribute - * which can be:

  • a function for determining if this handler should be applied
  • - *
  • a string for matching against the name
  • a regular expression for matching against - * the path
- *

- * In addition any JavaBean properties on the handler maybe set using the correct JavaBean - * semantics. For example: priority, processChildren - */ - public SkipElement skip(Map properties, Closure handlerFunction) { - Object select = properties.get(HANDLER_SELECT); - - if (select == null) { - throw new IllegalArgumentException("A property " + HANDLER_SELECT + " must be present in the properties map"); - } - - final SkipElement handler; - if (select instanceof Closure) { - handler = skip(select, handlerFunction); - } else if (select instanceof String || select instanceof GString) { - handler = skip(select.toString(), handlerFunction); - } else if (select instanceof Pattern) { - handler = skip(select, handlerFunction); - } else { - throw new IllegalArgumentException( - "The property " + HANDLER_SELECT + " is not a legal type. Legal types are: Closure/function or String or " + - "Regular Expression(Pattern) but was " + select.getClass()); - } - handler.configure(properties); - - return handler; - } - - /** - * Add a handler with the priority 1 which will exactly match element name and prefix. - * - * @param elementName the qualified element name to match - * @param function the handler closure/function - */ - public Handler add(String elementName, Closure function) { - final HandlerNameSelect handler = new HandlerNameSelect(Pattern.compile(Pattern.quote(elementName)), 1, function); - addHandler(handler); - return handler; - } - - /** - * Add a handler with priority 0 which will do a regular expression match against the qualified - * element name to see if it applies to the element. - * - * @param namePattern the regular expression to match. - * @param function the handler closure/function - */ - public Handler add(Pattern namePattern, Closure function) { - final HandlerNameSelect handler = new HandlerNameSelect(namePattern, 0, function); - addHandler(handler); - return handler; - } - - /** - * Add a handler with priority 0 which will do a regular expression match against full path from - * root to see if it applies to the element. Each segment of path will be separated by > - * - * @param pathPattern the regular expression to match. - * @param function the handler closure/function - */ - public Handler withPath(Pattern pathPattern, Closure function) { - final HandlerPathSelect handler = new HandlerPathSelect(pathPattern, 0, function); - addHandler(handler); - return handler; - } - - /** - * Add a handler with priority 0 which will do a execute the matcher function with the current - * element to see if it the handler should be applied to the element. - * - * @param select the regular expression to match. - * @param function the handler closure/function - */ - public Handler add(Closure select, Closure function) { - final Handler handler = new HandlerFunctionSelect(select, 0, function); - addHandler(handler); - return handler; - } - - /** - * Create a handler from a map of properties to values. There must be a 'select' attribute - * which can be:

  • a function for determining if this handler should be applied
  • - *
  • a string for matching against the name
  • a regular expression for matching against - * the path
- *

- * In addition any JavaBean properties on the handler maybe set using the correct JavaBean - * semantics. For example: priority, processChildren - */ - public Handler add(Map properties, Closure handlerFunction) { - Object select = properties.get(HANDLER_SELECT); - - if (select == null) { - throw new IllegalArgumentException("A property " + HANDLER_SELECT + " must be present in the properties map"); - } - - final Handler handler; - if (select instanceof Closure) { - handler = add((Closure) select, handlerFunction); - } else if (select instanceof String || select instanceof GString) { - handler = add(select.toString(), handlerFunction); - } else if (select instanceof Pattern) { - handler = withPath((Pattern) select, handlerFunction); - } else { - throw new IllegalArgumentException( - "The property " + HANDLER_SELECT + " is not a legal type. Legal types are: Closure/function or String or " + - "Regular Expression(Pattern) but was " + select.getClass()); - } - handler.configure(properties); - if (!handler.mode.equals(Mode.DEFAULT)) { - this.handlers.get(Mode.DEFAULT).remove(handler); - addHandler(handler); - } - - return handler; - } - - private void addHandler(Handler handler) { - handlers.put(handler.mode, handler); - addMode(handler); - } - - private void addMode(Selectable selectable) { - if (!this.modes.containsKey(selectable.mode)) { - this.modes.put(selectable.mode, new Mode(selectable.mode)); - } - } - - /** - * See if the default mode has a handler for the given element. - */ - public boolean hasHandlerFor(GPathResult elem) { - return hasHandlerFor(Mode.DEFAULT, elem); - } - - /** - * See if the mode has a handler for the given element. - */ - public boolean hasHandlerFor(String mode, GPathResult elem) { - return findHandlerFor(mode, elem) != null; - } - - public Handler findHandlerFor(GPathResult elem) { - return findHandlerFor(Mode.DEFAULT, elem); - } - - public Handler findHandlerFor(String mode, GPathResult elem) { - for (Handler handler : this.handlers.get(mode)) { - if (handler.select(TransformationContext.getContext(), elem)) { - Logging.debug("Handler %2$s found for element %1$s", elem, handler); - return handler; - } - } - Logging.debug("No handler found for element %s", elem); - - return null; - } - - /** - * Create a FileResult object as a result from a handler function. See {@link - * org.fao.geonet.api.records.formatters.groovy.template.FileResult} - *

- * File resolution is done by searching:

  • formatterDir/path
  • - *
  • schemaFormatterDir/path
  • rootFormatterDir/path
- * - * @param path The relative path to the file to load. - * @param model A map representing the data model to use when rendering the fileResult file. - */ - public FileResult fileResult(String path, Map model) throws IOException { - return this.templateCache.createFileResult(this.formatterDir, this.schemaDir, this.rootFormatterDir, path, model); - } - - /** - * Set the start handler. - * - * @param function the function executed at the start of the transformation. - */ - public StartEndHandler start(Closure function) { - this.startHandler = new StartEndHandler(function); - return this.startHandler; - } - - /** - * Set the end handler. - * - * @param function the function executed at the end of the transformation. - */ - public StartEndHandler end(Closure function) { - this.endHandler = new StartEndHandler(function); - return this.endHandler; - } - - /** - * Add a strategy for sorting the children of a node. - * - * @param select a closure for selecting if the sorter should be applied to a given node. - * If there is a match then the sorter will sort the children of the node - * and add the data resulting in processing the children in the sorted - * order. - * @param sortFunction a function that compares two elements and the data produced by - * processing/transforming them. The function must return a negative, 0 or - * positive number in the same way as a Comparator class. - */ - public Sorter sort(Closure select, Closure sortFunction) { - final SorterFunctionSelect sorter = new SorterFunctionSelect(0, select, new ClosureComparator(sortFunction)); - addSorter(sorter); - return sorter; - } - - /** - * Add a strategy for sorting the children of a node. - * - * @param elemName The name of the element this applies to - * @param sortFunction a function that compares two elements and the data produced by - * processing/transforming them. The function must return a negative, 0 or - * positive number in the same way as a Comparator class. - */ - public Sorter sort(String elemName, Closure sortFunction) { - final Sorter sorter = new SorterNameSelect(1, Pattern.compile(Pattern.quote(elemName)), - new ClosureComparator(sortFunction)); - addSorter(sorter); - return sorter; - } - - /** - * Add a strategy for sorting the children of a node. - * - * @param namePattern A pattern to use for matching the name of the element to apply the sorter - * to. - * @param sortFunction a function that compares two elements and the data produced by - * processing/transforming them. The function must return a negative, 0 or - * positive number in the same way as a Comparator class. - */ - public Sorter sort(Pattern namePattern, Closure sortFunction) { - final Sorter sorter = new SorterNameSelect(0, namePattern, - new ClosureComparator(sortFunction)); - addSorter(sorter); - return sorter; - } - - /** - * Add a strategy for sorting the children of a node. - * - * @param pathSelect A pattern to use for matching the path of the element to apply the sorter - * to. - * @param sortFunction a function that compares two elements and the data produced by - * processing/transforming them. The function must return a negative, 0 or - * positive number in the same way as a Comparator class. - */ - public Sorter sortPathMatcher(Pattern pathSelect, Closure sortFunction) { - final Sorter sorter = new SorterPathSelect(0, pathSelect, - new ClosureComparator(sortFunction)); - addSorter(sorter); - return sorter; - } - - public Sorter sort(Map properties, Closure handlerFunction) { - Object select = properties.get(HANDLER_SELECT); - - if (select == null) { - throw new IllegalArgumentException("A property " + HANDLER_SELECT + " must be present in the properties map"); - } - - final Sorter sorter; - if (select instanceof Closure) { - sorter = sort((Closure) select, handlerFunction); - } else if (select instanceof String || select instanceof GString) { - sorter = sort(select.toString(), handlerFunction); - } else if (select instanceof Pattern) { - sorter = sortPathMatcher((Pattern) select, handlerFunction); - } else { - throw new IllegalArgumentException( - "The property " + HANDLER_SELECT + " is not a legal type. Legal types are: Closure/function or String or " + - "Regular Expression(Pattern) but was " + select.getClass()); - } - sorter.configure(properties); - - if (!sorter.mode.equals(Mode.DEFAULT)) { - this.sorters.get(Mode.DEFAULT).remove(sorter); - addSorter(sorter); - } - return sorter; - } - - private void addSorter(Sorter sorter) { - this.sorters.put(sorter.mode, sorter); - addMode(sorter); - } - - Sorter findSorter(TransformationContext context, GPathResult md) { - for (Sorter sorter : this.sorters.get(context.getCurrentMode())) { - if (sorter.select(context, md)) { - Logging.debug("Sorter %2$s found for element %1$s.", md, sorter); - return sorter; - } - } - Logging.debug("No handler found for element %s", md); - return null; - } - - /** - * Add a new mode with the given id. If the mode already exists and has no fallback this is a - * no-op. if the mode exists and has a fallback then an exception is thrown. To change the - * fallback to null the 2 argument mode method must be called. - *

- * Note: This methods is not normally required because you can simply configure the mode on a - * handler or a sorter and a mode will automatically be created. - * - * @param id the id of the mode to create - */ - public Mode mode(String id) { - Mode mode = this.modes.get(id); - if (mode == null) { - mode = new Mode(id); - this.modes.put(id, mode); - } else { - if (mode.getFallback() != null) { - throw new IllegalArgumentException("The mode with id: " + id + " already exists and has a non-null fallback id. " + - "If you want to replace the fallback to null then explicitly call the 2 parameter " + - "mode method"); - } - } - return mode; - } - - /** - * Add a new mode with the given id and fallback. If the mode exists then the fallback of the - * mode will be updated with the new fallback id. - * - * @param id the id of the mode to create - */ - public Mode mode(String id, String fallback) { - Mode mode = this.modes.get(id); - if (mode == null) { - mode = new Mode(id, fallback); - this.modes.put(id, mode); - } else { - mode.setFallback(fallback); - } - - return mode; - } - - /** - * Find the mode with the given id or return null. - */ - public Mode findMode(String id) { - return this.modes.get(id); - } - - /** - * Process/Transform all GPathResult objects in the selection. Since a GPathResult can contain - * multiple elements, the selection will be iterated over and each element in each GPathResult - * will be iterated over. - *

- * This version will not sort the element and will use the current transformation mode. - * - * @param selection a iterable of GPathResult objects - */ - public String processElements(Iterable selection) throws IOException { - final TransformationContext context = TransformationContext.getContext(); - return processElementsInMode(context.getCurrentMode(), selection, null); - } - - /** - * Process/Transform all GPathResult objects in the selection. Since a GPathResult can contain - * multiple elements, the selection will be iterated over and each element in each GPathResult - * will be iterated over. - *

- * This version will not sort the element and will use the current transformation mode. - * - * @param selection a iterable of GPathResult objects - * @param sortByElement a GPathResult representing a single element which is used to look up a - * sorter. If null no sorting will be done - */ - public String processElements(Iterable selection, GPathResult sortByElement) throws IOException { - final TransformationContext context = TransformationContext.getContext(); - return processElementsInMode(context.getCurrentMode(), selection, sortByElement); - } - - /** - * Process/Transform all GPathResult objects in the selection. Since a GPathResult can contain - * multiple elements, the selection will be iterated over and each element in each GPathResult - * will be iterated over. - *

- * This version will not sort the element and will use the declared mode transformation mode. - * - * @param mode the transformation mode to use - * @param selection a iterable of GPathResult objects - */ - public String processElementsInMode(String mode, Iterable selection) throws IOException { - return processElementsInMode(mode, selection, null); - } - - /** - * Process/Transform all GPathResult objects in the selection. Since a GPathResult can contain - * multiple elements, the selection will be iterated over and each element in each GPathResult - * will be iterated over. - *

- * This version will sort the element using the sorter that applies to the sortByElement. will - * use the declared mode transformation mode. - * - * @param mode the transformation mode to use - * @param selection a iterable of GPathResult objects - * @param sortByElement a GPathResult representing a single element which is used to look up a - * sorter. If null no sorting will be done - */ - public String processElementsInMode(String mode, Iterable selection, GPathResult sortByElement) throws IOException { - return transformationEngine.processElementsInMode(mode, selection, sortByElement); - } - - ListMultimap getHandlers() { - return handlers; - } - - public List getSkipElements() { - return skipElements; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Logging.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Logging.java deleted file mode 100644 index 1007aae8d470..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Logging.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.util.slurpersupport.GPathResult; -import org.fao.geonet.constants.Geonet; -import org.fao.geonet.utils.Log; - -import java.util.Collection; -import java.util.Iterator; - -/** - * Methods for logging the handling of elements in this formatter. - * - * @author Jesse on 10/24/2014. - */ -public class Logging { - - static void debug(String message, GPathResult elem, Object... objects) { - if (isDebugMode()) { - Object[] objs = new Object[objects.length + 1]; - System.arraycopy(objects, 0, objs, 1, objects.length); - objs[0] = "'" + createPath(elem) + "'"; - debug(String.format(message, objs)); - } - } - - static void debug(String message, Collection elem, Object... objects) { - if (isDebugMode()) { - Object[] objs = new Object[objects.length + 1]; - System.arraycopy(objects, 0, objs, 1, objects.length); - StringBuilder builder = new StringBuilder(); - if (elem.isEmpty()) { - builder.append("No Paths"); - } else { - final Iterator iterator = elem.iterator(); - GPathResult first = iterator.next(); - builder.append(createPath(first)); - while (iterator.hasNext()) { - GPathResult next = iterator.next(); - builder.append(",").append(next.name()); - } - } - objs[0] = "'" + builder + "'"; - debug(String.format(message, objs)); - } - } - - public static boolean isDebugMode() { - return Log.isDebugEnabled(Geonet.FORMATTER); - } - - public static String createPath(GPathResult element) { - if (element == null) { - return "null"; - } - StringBuilder pathBuilder = new StringBuilder(); - Handler.createPath(element, pathBuilder); - String rootPath = ""; - TransformationContext context = TransformationContext.getContext(); - if (context != null) { - rootPath = context.getRootPath() + ">"; - } - return rootPath + pathBuilder.toString(); - } - - static void debug(String message) { - if (isDebugMode()) { - Log.debug(Geonet.FORMATTER, message); - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/MapConfig.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/MapConfig.java deleted file mode 100644 index d7845bebf8ca..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/MapConfig.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import org.fao.geonet.api.records.extent.MetadataExtentApi; - -/** - * Encapsulates the map parameters used when making {@link org.fao.geonet.services.region.MetadataExtentApi} - * requests. - *

- * The parameters are read from the setting (background, width and mapproj) and are to be used when - * displaying geometries and extents. - * - * @author Jesse on 12/19/2014. - */ -public class MapConfig { - private String background, mapproj; - private int width, thumbnailWidth; - - public MapConfig(String background, String mapproj, int width, int thumbnailWidth) { - this.background = background; - this.mapproj = mapproj; - this.width = width; - this.thumbnailWidth = thumbnailWidth; - } - - /** - * The value to pass as the background parameter when making a request to {@link - * org.fao.geonet.services.region.MetadataExtentApi} when rendering extents and geometries. - */ - public String getBackground() { - return background.toLowerCase().startsWith("http://") ? MetadataExtentApi.SETTING_BACKGROUND : background; - } - - public void setBackground(String background) { - this.background = background; - } - - /** - * The projection of the map. - */ - public String getMapproj() { - return mapproj; - } - - public void setMapproj(String mapproj) { - this.mapproj = mapproj; - } - - /** - * The width in pixels of the map image. - */ - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - /** - * The width in pixels of the map if the map is to be a small thumbnail. - */ - public int getThumbnailWidth() { - return thumbnailWidth; - } - - public void setThumbnailWidth(int thumbnailWidth) { - this.thumbnailWidth = thumbnailWidth; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Mode.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Mode.java deleted file mode 100644 index 7935dd2c05f3..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Mode.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -/** - * A mode is a way of grouping {@link org.fao.geonet.api.records.formatters.groovy.Handler} and - * {@link org.fao.geonet.api.records.formatters.groovy.Sorter} so that groups of handlers and - * sorters can be partitioned. - * - * @author Jesse on 10/22/2014. - */ -public class Mode { - public static final String DEFAULT = ""; - private String id; - private String fallback; - - public Mode(String modeId, String fallback) { - this.id = modeId; - this.fallback = fallback; - } - - public Mode(String modeId) { - this(modeId, null); - } - - /** - * The id of this mode - */ - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - /** - * The id of another mode which will be used if the object (Handler or Sorter) was not found in - * this mode. This can be null if not fallback is desired. - */ - public String getFallback() { - return fallback; - } - - public void setFallback(String fallback) { - this.fallback = fallback; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/ParamValue.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/ParamValue.java deleted file mode 100644 index 89ef820f35fe..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/ParamValue.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -/** - * Represents the value of one of the parameters passed to the Format Service. - * - * @author Jesse on 10/17/2014. - */ -public class ParamValue { - final String value; - - public ParamValue(String value) { - this.value = value; - } - - @Override - public String toString() { - return this.value; - } - - public boolean toBool() { - String processedValue = this.value == null ? "false" : this.value; - if (processedValue.equalsIgnoreCase("yes") || processedValue.equalsIgnoreCase("y") || processedValue.equals("1")) { - return true; - } - return Boolean.parseBoolean(processedValue); - } - - public int toInt() { - return Integer.parseInt(this.value); - } - - public Double toDouble() { - return Double.parseDouble(this.value); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Selectable.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Selectable.java deleted file mode 100644 index 0d4b98327f55..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Selectable.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.util.slurpersupport.GPathResult; -import org.springframework.beans.BeanUtils; - -import java.beans.PropertyDescriptor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Map; - -/** - * A common super class for objects that are configured from the groovy scripts and that are applied - * on a by element basis like {@link org.fao.geonet.api.records.formatters.groovy.Sorter} and {@link - * org.fao.geonet.api.records.formatters.groovy.Handler}. - * - * @author Jesse on 10/22/2014. - */ -public abstract class Selectable { - protected int priority = 0; - protected String name; - protected String mode = Mode.DEFAULT; - - public Selectable(int priority) { - this.priority = priority; - } - - /** - * Return true if the sorter should sort the children of the element. - */ - public abstract boolean select(TransformationContext context, GPathResult result); - - /** - * The priority of the handler. If two (or more) handlers can be applied to a metadata element, - * the handler with the higher priority will be selected. - */ - public void setPriority(int priority) { - this.priority = priority; - } - - @Override - public final String toString() { - return getClass().getSimpleName() + "{" + - (name != null ? "name='" + name + "'," : "") + - " priority=" + priority + - extraToString() + - '}'; - } - - protected abstract String extraToString(); - - public void configure(Map properties) { - final PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(getClass()); - - for (Map.Entry entry : properties.entrySet()) { - final String propertyName = entry.getKey(); - if (propertyName.equalsIgnoreCase(Handlers.HANDLER_SELECT)) { - // skip - continue; - } - - final Object value = entry.getValue(); - PropertyDescriptor propertyDescriptor = findPropertyDescriptor(propertyDescriptors, propertyName, value); - final Method writeMethod = propertyDescriptor.getWriteMethod(); - - try { - writeMethod.invoke(this, value); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (InvocationTargetException e) { - throw new RuntimeException(e); - } - } - } - - private PropertyDescriptor findPropertyDescriptor(PropertyDescriptor[] propertyDescriptors, String key, Object value) { - for (PropertyDescriptor descriptor : propertyDescriptors) { - if (descriptor.getWriteMethod() != null && descriptor.getName().equalsIgnoreCase(key)) { - return descriptor; - } - } - throw new IllegalArgumentException("Handler's do not have a configurable property: " + key + " value = " + value); - } - - public String getName() { - return name; - } - - /** - * A name for this handler. This is strictly for debugging purposes. - */ - public void setName(String name) { - this.name = name; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElement.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElement.java deleted file mode 100644 index a2c58593f24f..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElement.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.lang.Closure; -import groovy.util.slurpersupport.GPathResult; - -/** - * A skip element is an element that shouldn't be processed but some of its children should be. For - * example a formatter for iso19139 may not want to show the informationInfo elements but does want - * to display its children. - *

- * The match can be gmd:informationInfo and the childSelector can be the closure {it.children()} - * - * @author Jesse on 11/26/2014. - */ -public abstract class SkipElement extends Selectable { - public Closure childSelector; - - public SkipElement(int priority, Closure childSelector) { - super(priority); - this.childSelector = childSelector; - } - - @Override - protected String extraToString() { - return null; - } - - public Closure getChildSelector() { - return childSelector; - } - - public GPathResult selectChildren(GPathResult elem) { - final int maximumNumberOfParameters = this.childSelector.getMaximumNumberOfParameters(); - switch (maximumNumberOfParameters) { - case 0: - return (GPathResult) this.childSelector.call(); - case 1: - return (GPathResult) this.childSelector.call(elem); - default: - throw new IllegalArgumentException("Closure has too many parameters"); - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElementClosure.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElementClosure.java deleted file mode 100644 index cd25e2a4f152..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElementClosure.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.lang.Closure; -import groovy.util.slurpersupport.GPathResult; - -/** - * @author Jesse on 11/26/2014. - */ -public class SkipElementClosure extends SkipElement { - private final Closure closure; - - public SkipElementClosure(Closure closure, int priority, Closure childSelector) { - super(priority, childSelector); - this.closure = closure; - } - - @Override - public boolean select(TransformationContext context, GPathResult elem) { - final int maximumNumberOfParameters = this.closure.getMaximumNumberOfParameters(); - switch (maximumNumberOfParameters) { - case 0: - return (boolean) this.closure.call(); - case 1: - return (boolean) this.closure.call(elem); - default: - throw new IllegalArgumentException("Closure has too many parameters"); - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElementPattern.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElementPattern.java deleted file mode 100644 index aae618ca09ed..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SkipElementPattern.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.lang.Closure; -import groovy.util.slurpersupport.GPathResult; - -import java.util.regex.Pattern; - -/** - * @author Jesse on 11/26/2014. - */ -public class SkipElementPattern extends SkipElement { - private final Pattern pattern; - - public SkipElementPattern(Pattern name, int priority, Closure childSelector) { - super(priority, childSelector); - this.pattern = name; - this.name = pattern.toString(); - } - - @Override - public boolean select(TransformationContext context, GPathResult result) { - return pattern.matcher(result.name()).matches(); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Sorter.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Sorter.java deleted file mode 100644 index a9578f2c3a04..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Sorter.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.util.slurpersupport.GPathResult; - -import java.util.Comparator; - -/** - * A strategy for controlling the order that the transformed data of an element is added to the - * resulting document. A Sorter applies to a parent element and sorts all the child (and associated - * data) elements of that element. - * - * @author Jesse on 10/20/2014. - */ -public abstract class Sorter extends Selectable implements Comparator, Comparable { - private final Comparator comparator; - - protected Sorter(int priority, Comparator comparator) { - super(priority); - this.comparator = comparator; - } - - /** - * This is essentially the same as a Comparator's compare method. - */ - public int compare(GPathResult el1, GPathResult el2) { - return this.comparator.compare(el1, el2); - } - - @Override - public int compareTo(Sorter o) { - return Integer.compare(o.priority, this.priority); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterFunctionSelect.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterFunctionSelect.java deleted file mode 100644 index 03dbad75773b..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterFunctionSelect.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.lang.Closure; -import groovy.util.slurpersupport.GPathResult; - -import java.util.Comparator; - -/** - * A sorter where the matcher is a function. - * - * @author Jesse on 10/20/2014. - */ -public class SorterFunctionSelect extends Sorter { - private final Closure select; - - @SuppressWarnings("unchecked") - public SorterFunctionSelect(int priority, Closure select, Comparator comparator) { - super(priority, comparator); - this.select = select; - } - - @Override - public boolean select(TransformationContext context, GPathResult parentElement) { - return (Boolean) this.select.call(parentElement); - } - - @Override - protected String extraToString() { - return ""; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterNameSelect.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterNameSelect.java deleted file mode 100644 index 251117c01d1b..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterNameSelect.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.util.ClosureComparator; -import groovy.util.slurpersupport.GPathResult; - -import java.util.regex.Pattern; - -/** - * @author Jesse on 10/20/2014. - */ -public class SorterNameSelect extends Sorter { - private final Pattern namePattern; - - public SorterNameSelect(int priority, Pattern namePattern, ClosureComparator comparator) { - super(priority, comparator); - this.namePattern = namePattern; - } - - @Override - public boolean select(TransformationContext context, GPathResult result) { - return namePattern.matcher(result.name()).matches(); - } - - @Override - protected String extraToString() { - return ", namePattern ~= /" + namePattern + "/"; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterPathSelect.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterPathSelect.java deleted file mode 100644 index 793ff1be674e..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/SorterPathSelect.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.util.ClosureComparator; -import groovy.util.slurpersupport.GPathResult; - -import java.util.regex.Pattern; - -/** - * @author Jesse on 10/20/2014. - */ -public class SorterPathSelect extends Sorter { - private final Pattern pathPattern; - - public SorterPathSelect(int priority, Pattern pathPattern, ClosureComparator comparator) { - super(priority, comparator); - this.pathPattern = pathPattern; - } - - @Override - public boolean select(TransformationContext context, GPathResult parentElement) { - StringBuilder path = new StringBuilder(context.getRootPath()); - if (path.length() > 0) { - path.append(">"); - } - Handler.createPath(parentElement, path); - - return this.pathPattern.matcher(path.toString()).matches(); - } - - @Override - protected String extraToString() { - return ", pathPattern ~= /" + pathPattern + "/"; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/StartEndHandler.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/StartEndHandler.java deleted file mode 100644 index 85fc7241d377..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/StartEndHandler.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import groovy.lang.Closure; - -import java.io.IOException; - -/** - * A handler for start and end processing events. - * - * @author Jesse on 10/16/2014. - */ -public class StartEndHandler { - private final Closure function; - - public StartEndHandler(Closure function) { - this.function = function; - } - - public void handle(StringBuilder resultantXml) throws IOException { - if (this.function != null) { - final Object result = this.function.call(); - Handler.processResult(result, resultantXml); - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/TransformEngine.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/TransformEngine.java deleted file mode 100644 index 5b47b24193ba..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/TransformEngine.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import groovy.util.slurpersupport.GPathResult; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -/** - * The class that does the actual transforming of the Metadata XML. - * - * @author Jesse on 10/24/2014. - */ -class TransformEngine { - private final Handlers handlers; - - TransformEngine(Handlers handlers) { - this.handlers = handlers; - } - - String processElementsInMode(String mode, Iterable selection, GPathResult sortByElement) throws IOException { - StringBuilder resultantXml = new StringBuilder(); - final TransformationContext context = TransformationContext.getContext(); - String oldMode = context.getCurrentMode(); - try { - context.setCurrentMode(mode); - - List flattenedSelection = flattenGPathResults(selection); - processChildren(context, sortByElement, flattenedSelection, resultantXml); - - return resultantXml.toString(); - } finally { - context.setCurrentMode(oldMode); - } - } - - private List flattenGPathResults(Iterable selection) { - List result = Lists.newArrayList(); - for (Object path : selection) { - final GPathResult gpath = (GPathResult) path; - if (!gpath.isEmpty()) { - for (Object el : gpath) { - result.add((GPathResult) el); - } - } - } - return result; - } - - Collection processElement(TransformationContext context, GPathResult elem, List siblings, StringBuilder resultantXml) throws IOException { - @SuppressWarnings("unchecked") - List handledSiblings = Lists.newArrayList(elem); - Logging.debug("Starting to process element: %s", elem); - boolean processChildren = true; - for (SkipElement skipElement : this.handlers.getSkipElements()) { - if (skipElement.select(context, elem)) { - processChildren(context, elem, processSkipElements(elem, skipElement), resultantXml); - processChildren = false; - } - } - - if (processChildren) { - for (Handler handler : this.handlers.getHandlers().get(context.getCurrentMode())) { - if (handler.select(context, elem)) { - if (handler.isGroup()) { - for (GPathResult sibling : siblings) { - if (handler.select(context, sibling)) { - handledSiblings.add(sibling); - } - } - } - handler.handle(context, handledSiblings, resultantXml); - processChildren = false; - break; - } - } - } - - if (processChildren) { - Logging.debug("No Handler found for element: %s", elem); - processChildren(context, elem, processSkipElements(elem, null), resultantXml); - } - - return handledSiblings; - } - - private void processChildren(TransformationContext context, GPathResult md, List sortedChildren, - StringBuilder resultantXml) throws IOException { - if (sortedChildren.isEmpty()) { - return; - } - - if (md != null) { - Sorter sorter = this.handlers.findSorter(context, md); - if (sorter != null) { - Collections.sort(sortedChildren, sorter); - } - } - - final Set visitedByGroup = Sets.newIdentityHashSet(); - int size = sortedChildren.size(); - for (int i = 0; i < size; i++) { - GPathResult child = sortedChildren.get(i); - - if (!visitedByGroup.contains(child)) { - visitedByGroup.addAll(processElement(context, child, sortedChildren.subList(i + 1, size), resultantXml)); - } - } - } - - @SuppressWarnings("unchecked") - private List processSkipElements(GPathResult md, SkipElement skipElement) { - GPathResult childrenPath; - if (skipElement == null) { - childrenPath = md.children(); - } else { - childrenPath = skipElement.selectChildren(md); - } - if (Logging.isDebugMode()) { - Logging.debug("Starting to process %2$d children of: %1$s.", md, childrenPath.size()); - } - return childrenPath.list(); - } - -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/TransformationContext.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/TransformationContext.java deleted file mode 100644 index 14a74af6fcfa..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/TransformationContext.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -/** - * Contains properties like the current rootPath that can be used in handlers. - * - * @author Jesse on 10/16/2014. - */ -public class TransformationContext { - private static final ThreadLocal context = new InheritableThreadLocal(); - public final Handlers handlers; - public final Functions functions; - public final Environment env; - private String rootPath; - private String currentMode = Mode.DEFAULT; - - public TransformationContext(Handlers handlers, Functions functions, Environment env) { - this.handlers = handlers; - this.functions = functions; - this.env = env; - } - - public static TransformationContext getContext() { - return context.get(); - } - - public void setThreadLocal() { - context.set(this); - } - - /** - * The path from the root of the metadata document to the "root" element as selected by the - * roots selectors in {@link org.fao.geonet.api.records.formatters.groovy.Handlers#roots} - */ - public String getRootPath() { - return rootPath; - } - - public void setRootPath(String rootPath) { - this.rootPath = rootPath; - } - - /** - * Get the id of the mode currently configured for processing. - */ - public String getCurrentMode() { - return currentMode; - } - - public void setCurrentMode(String currentMode) { - this.currentMode = currentMode; - } - - public Handlers getHandlers() { - return handlers; - } - - public Functions getFunctions() { - return functions; - } - - public Environment getEnv() { - return env; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Transformer.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Transformer.java deleted file mode 100644 index b2d85c25a50d..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/Transformer.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Maps; -import groovy.util.XmlSlurper; -import groovy.util.slurpersupport.GPathResult; -import org.fao.geonet.constants.Geonet; -import org.fao.geonet.utils.Log; -import org.fao.geonet.utils.Xml; -import org.jdom.Content; -import org.jdom.Element; -import org.jdom.Namespace; -import org.xml.sax.SAXException; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Transforms the metadata using the Groovy formatter. - * - * @author Jesse on 10/15/2014. - */ -public class Transformer { - - private final Handlers handlers; - private final Path formatterPath; - private final Functions functions; - private final Environment env; - - public Transformer(Handlers handlers, Functions functions, Environment env, Path formatterPath) { - this.handlers = handlers; - this.functions = functions; - this.env = env; - handlers.prepareForTransformer(); - this.formatterPath = formatterPath; - } - - public String apply(Element metadata, List namespaces) throws Exception { - TransformationContext context = new TransformationContext(handlers, functions, env); - context.setThreadLocal(); - Map namespaceUriToPrefix = Maps.newHashMap(); - for (Namespace namespace : namespaces) { - namespaceUriToPrefix.put(namespace.getPrefix(), namespace.getURI()); - } - final XmlSlurper xmlSlurper = new XmlSlurper(false, false); - StringBuilder resultantXml = new StringBuilder(); - handlers.startHandler.handle(resultantXml); - - Set rootXpaths = this.handlers.getRoots(); - if (rootXpaths.isEmpty()) { - processRoot(context, namespaceUriToPrefix, xmlSlurper, resultantXml, metadata); - } - for (String rootXpath : rootXpaths) { - @SuppressWarnings("unchecked") final List roots = (List) Xml.selectNodes(metadata, rootXpath, namespaces); - for (Content root : roots) { - processRoot(context, namespaceUriToPrefix, xmlSlurper, resultantXml, root); - } - } - handlers.endHandler.handle(resultantXml); - try { - return resultantXml.toString(); - } catch (Exception e) { - Log.error(Geonet.FORMATTER, "Error parsing the resulting XML from '" + formatterPath + "' formatter. Resulting XML is: " + - resultantXml, e); - throw e; - } - } - - @SuppressWarnings("unchecked") - private void processRoot(TransformationContext context, Map namespaceUriToPrefix, XmlSlurper xmlSlurper, - StringBuilder resultantXml, Content root) throws IOException, SAXException { - // later for performance we could start a thread to write to a PipedInputStream and parse the PipedOutputStream - // however until we if there is a performance issue here we will not do that. - GPathResult md = xmlSlurper.parseText(Xml.getString((Element) root)).declareNamespace(namespaceUriToPrefix); - if (md.size() == 0) { - throw new IllegalArgumentException("There are no elements parsed from the xml"); - } - StringBuilder path = new StringBuilder(); - createPath(root.getParentElement(), path); - - context.setRootPath(path.toString()); - handlers.transformationEngine.processElement(context, md, md.children().list(), resultantXml); - } - - private void createPath(Element node, StringBuilder path) { - if (node == null) { - return; - } - if (node.getParentElement() != null) { - createPath(node.getParentElement(), path); - path.append(">"); - } - path.append(node.getQualifiedName()); - } - - @VisibleForTesting - public Handlers getHandlers() { - return this.handlers; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/AttributesFiltered.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/AttributesFiltered.java deleted file mode 100644 index 1adcc1f65ce1..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/AttributesFiltered.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Sets; -import org.apache.xalan.xsltc.runtime.AttributeList; -import org.xml.sax.Attributes; - -import java.util.Set; - -/** - * Represents a subset of an element's attributes - * - * @author Jesse on 11/29/2014. - */ -public class AttributesFiltered implements Attributes { - private final AttributeList filtered = new AttributeList(); - - public AttributesFiltered(Attributes unfiltered, String... excludeNames) { - Set allExcludes = Sets.newHashSet(); - for (String excludeName : excludeNames) { - for (String prefix : TNodeFactory.ATTRIBUTE_NAME_PREFIXES) { - allExcludes.add(prefix + excludeName); - } - } - for (int i = 0; i < unfiltered.getLength(); i++) { - String attName = unfiltered.getQName(i); - if (!allExcludes.contains(attName)) { - filtered.add(unfiltered.getQName(i), unfiltered.getValue(i)); - } - } - } - - @Override - public String getValue(String uri, String localName) { - return filtered.getValue(uri, localName); - } - - @Override - public int getLength() { - return filtered.getLength(); - } - - @Override - public String getURI(int index) { - return filtered.getURI(index); - } - - @Override - public String getLocalName(int index) { - return filtered.getLocalName(index); - } - - @Override - public String getQName(int pos) { - return filtered.getQName(pos); - } - - @Override - public String getType(int index) { - return filtered.getType(index); - } - - @Override - public int getIndex(String namespaceURI, String localPart) { - return filtered.getIndex(namespaceURI, localPart); - } - - @Override - public int getIndex(String qname) { - return filtered.getIndex(qname); - } - - @Override - public String getType(String uri, String localName) { - return filtered.getType(uri, localName); - } - - @Override - public String getType(String qname) { - return filtered.getType(qname); - } - - @Override - public String getValue(int pos) { - return filtered.getValue(pos); - } - - @Override - public String getValue(String qname) { - return filtered.getValue(qname); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FileResult.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FileResult.java deleted file mode 100644 index 6ca508e208c4..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FileResult.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.fao.geonet.Constants; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; - -/** - * One of the results the closure of a file handler can return. It will load a file and replace all - * ${key} values (where key is in the substitutions map) with the value from the substitutions map. - * Keys may not contain { or }. - * - * @author Jesse on 10/16/2014. - */ -public class FileResult { - private final TNode template; - private final Map substitutions; - - public FileResult(TNode template, Map substitutions) { - this.template = template; - this.substitutions = substitutions; - } - - @Override - public String toString() { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - TRenderContext context = new TRenderContext(out, substitutions); - try { - template.render(context); - return out.toString(Constants.ENCODING); - } catch (IOException e) { - throw new TemplateException(e); - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterCapitalize.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterCapitalize.java deleted file mode 100644 index 800c3e040978..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterCapitalize.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.apache.commons.lang.StringUtils; -import org.springframework.stereotype.Component; - -/** - * Uppercase the string. - * - * @author Jesse on 12/19/2014. - */ -@Component("capitalize") -public class FilterCapitalize implements TextContentFilter { - - public static String toTitleCase(String givenString) { - String[] arr = givenString.split(" "); - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < arr.length; i++) { - if (StringUtils.isNotEmpty(arr[i])) { - sb.append(Character.toUpperCase(arr[i].charAt(0))).append(arr[i].substring(1)).append(" "); - } - } - - return sb.toString().trim(); - } - - @Override - public String process(TRenderContext context, String rawValue) { - return toTitleCase(rawValue); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlAttrs.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlAttrs.java deleted file mode 100644 index 92185c670bd6..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlAttrs.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.escape.Escaper; -import com.google.common.xml.XmlEscapers; -import org.springframework.stereotype.Component; - -/** - * Escape the string for xml attributes. - * - * @author Jesse on 12/19/2014. - */ -@Component("escapeXmlAttrs") -public class FilterEscapeXmlAttrs implements TextContentFilter { - private static final Escaper escaper = XmlEscapers.xmlAttributeEscaper(); - - @Override - public String process(TRenderContext context, String rawValue) { - return escaper.escape(rawValue); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlContent.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlContent.java deleted file mode 100644 index 8498f510d51c..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlContent.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.escape.Escaper; -import com.google.common.xml.XmlEscapers; -import org.springframework.stereotype.Component; - -/** - * Escape the string for xml text content. - * - * @author Jesse on 12/19/2014. - */ -@Component("escapeXmlContent") -public class FilterEscapeXmlContent implements TextContentFilter { - private static final Escaper escaper = XmlEscapers.xmlContentEscaper(); - - @Override - public String process(TRenderContext context, String rawValue) { - return escaper.escape(rawValue); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterGenerateUUID.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterGenerateUUID.java deleted file mode 100644 index 5f942a7a3c6d..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterGenerateUUID.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.springframework.stereotype.Component; - -import java.util.UUID; - -/** - * Uppercase the string. - * - * @author Jesse on 12/19/2014. - */ -@Component("generateUUID") -public class FilterGenerateUUID implements TextContentFilter { - - static ThreadLocal LAST_UUID = new InheritableThreadLocal<>(); - - @Override - public String process(TRenderContext context, String rawValue) { - LAST_UUID.set(UUID.randomUUID().toString()); - - return LAST_UUID.get(); - } - -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLastUUID.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLastUUID.java deleted file mode 100644 index 8770a46321cd..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLastUUID.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.springframework.stereotype.Component; - -import java.util.UUID; - -/** - * Uppercase the string. - * - * @author Jesse on 12/19/2014. - */ -@Component("lastUUID") -public class FilterLastUUID implements TextContentFilter { - - @Override - public String process(TRenderContext context, String rawValue) { - String uuid = FilterGenerateUUID.LAST_UUID.get(); - if (uuid == null) { - uuid = UUID.randomUUID().toString(); - FilterGenerateUUID.LAST_UUID.set(uuid); - } - return uuid; - } - -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLowerCase.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLowerCase.java deleted file mode 100644 index 5f9089ea77f9..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLowerCase.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.springframework.stereotype.Component; - -/** - * Uppercase the string. - * - * @author Jesse on 12/19/2014. - */ -@Component("lowercase") -public class FilterLowerCase implements TextContentFilter { - - @Override - public String process(TRenderContext context, String rawValue) { - return rawValue.toLowerCase(); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUpperCase.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUpperCase.java deleted file mode 100644 index fea215a33fb0..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUpperCase.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.springframework.stereotype.Component; - -/** - * Uppercase the string. - * - * @author Jesse on 12/19/2014. - */ -@Component("uppercase") -public class FilterUpperCase implements TextContentFilter { - - @Override - public String process(TRenderContext context, String rawValue) { - return rawValue.toUpperCase(); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/SimpleTNode.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/SimpleTNode.java deleted file mode 100644 index 2433c622cdf2..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/SimpleTNode.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.base.Optional; -import org.fao.geonet.SystemInfo; -import org.xml.sax.Attributes; - -import java.io.IOException; - -/** - * @author Jesse on 11/29/2014. - */ -public class SimpleTNode extends TNode { - public SimpleTNode(SystemInfo info, TextContentParser parser, String qName, Attributes attributes) throws IOException { - super(info, parser, qName, attributes); - } - - @Override - protected Optional canRender(TRenderContext context) { - return Optional.absent(); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNode.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNode.java deleted file mode 100644 index 3434d4ff7552..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNode.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.base.Optional; -import com.google.common.collect.Lists; -import org.apache.xalan.xsltc.runtime.AttributeList; -import org.fao.geonet.SystemInfo; -import org.xml.sax.Attributes; - -import java.io.IOException; -import java.util.List; - -/** - * A "Template Node". A node in the template render tree. A TNode defines how a section of a - * template is rendered. For example a node might be an nonEmpty node where the node will only be - * rendered if the attribute is nonEmpty (non-empty/non-null string or collection). - * - * @author Jesse on 11/29/2014. - */ -public abstract class TNode { - protected static final Attributes EMPTY_ATTRIBUTES = new AttributeList(); - protected final TextBlock attributes, end; - protected final String qName; - protected final SystemInfo info; - protected final TextContentParser textContentParser; - private final List children = Lists.newArrayList(); - private long unparsedSize; - - public TNode(SystemInfo info, TextContentParser textContentParser, String qName, Attributes attributes) throws IOException { - this.info = info; - this.qName = qName; - StringBuilder start = new StringBuilder(); - StringBuilder end = new StringBuilder(); - renderAttributes(attributes, start); - - end.append(""); - - this.textContentParser = textContentParser; - this.attributes = textContentParser.parse(start.toString()); - this.end = textContentParser.parse(end.toString()); - } - - public List getChildren() { - return children; - } - - public void renderAttributes(Attributes attributes, Appendable appendable) throws IOException { - for (int i = 0; i < attributes.getLength(); i++) { - appendable.append(" ").append(attributes.getQName(i)).append("=\"").append(attributes.getValue(i)).append("\""); - } - } - - /** - * Render the currentNode. - */ - public void render(TRenderContext context) throws IOException { - final Optional reasonToNotRender = canRender(context); - if (reasonToNotRender.isPresent()) { - addCannontRenderComment(context, reasonToNotRender); - } else { - context.append("<").append(qName); - - if (writeAttributes(context)) { - attributes.render(context); - } - final Attributes customAttributes = customAttributes(context); - if (customAttributes != null) { - renderAttributes(customAttributes, context); - } - context.append(">"); - - if (writeChildren(context)) { - for (TNode child : children) { - appendCustomChildData(context, child); - child.render(context); - } - } - - end.render(context); - } - } - - public void addCannontRenderComment(TRenderContext context, Optional reasonToNotRender) throws IOException { - if (SystemInfo.getInfo(this.info).isDevMode()) { - context.append(""); - } - } - - /** - * If true and canRender then write all the children. - */ - protected boolean writeChildren(TRenderContext context) { - return true; - } - - /** - * If true and canRender then the attributes defined on the element will be on the element - * definition. Otherwise no attributes will be written. - */ - protected boolean writeAttributes(TRenderContext context) { - return true; - } - - /** - * Write the extra child data for this node. - *

- * The child nodes will be processed by the render method. - */ - protected void appendCustomChildData(TRenderContext context, TNode nextChild) throws IOException { - // no op - } - - /** - * Get attributes from implementation class. - */ - protected Attributes customAttributes(TRenderContext context) { - return null; - } - - /** - * Check if this node (and subtree) should be rendered. - */ - protected abstract Optional canRender(TRenderContext context); - - /** - * Add a child to this node. - */ - public void addChild(TNode node) { - this.children.add(node); - } - - public void setTextContent(String text) throws IOException { - if (text.isEmpty()) { - return; - } - addChild(new TNodeTextContent(info, textContentParser, textContentParser.parse(text))); - } - - public long getUnparsedSize() { - return unparsedSize; - } - - public void setUnparsedSize(long unparsedSize) { - this.unparsedSize = unparsedSize; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactory.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactory.java deleted file mode 100644 index 8fadfcf7c395..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactory.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Lists; -import org.springframework.beans.factory.annotation.Autowired; -import org.xml.sax.Attributes; - -import java.io.IOException; -import java.util.List; - -/** - * Parses xml attributes and elements and create TNode if applicable. - * - * @author Jesse on 11/29/2014. - */ -public abstract class TNodeFactory { - public static final String FMT_PREFIX = "fmt-"; - public static final List ATTRIBUTE_NAME_PREFIXES = Lists.newArrayList(FMT_PREFIX, "x-" + FMT_PREFIX, "data-" + FMT_PREFIX); - - @Autowired - protected TextContentParser textContentParser; - - /** - * Test if this node factory can process the current node. - */ - public abstract boolean applicable(String localName, String qName, Attributes attributes); - - /** - * Create a node from the current XML element. - */ - public abstract TNode create(String localName, String qName, Attributes attributes) throws IOException; - - protected String getValue(Attributes attributes, String name) { - for (String attributeNamePrefix : ATTRIBUTE_NAME_PREFIXES) { - final int index = attributes.getIndex(attributeNamePrefix + name); - if (index > -1) { - return attributes.getValue(index); - } - } - - return null; - } - - protected boolean hasAttribute(Attributes attributes, String... attNames) { - for (String att : attNames) { - if (getValue(attributes, att) != null) { - return true; - } - } - return false; - } - - protected boolean getBooleanAttribute(Attributes attributes, String attName, boolean defaultVal) { - String replaceAtt = getValue(attributes, attName); - boolean value = defaultVal; - - if (replaceAtt != null) { - value = replaceAtt.isEmpty() || replaceAtt.equalsIgnoreCase("y") || replaceAtt.equalsIgnoreCase("true") - || replaceAtt.equalsIgnoreCase("yes"); - } - - return value; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryByAttName.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryByAttName.java deleted file mode 100644 index 4b9b9fb0d2b0..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryByAttName.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.fao.geonet.SystemInfo; -import org.xml.sax.Attributes; - -/** - * Implementation where the applicable method is based on analyzing the element's attributes and - * checking if the attribute is one of the "applicable" names. - * - * @author Jesse on 11/29/2014. - */ -public abstract class TNodeFactoryByAttName extends TNodeFactory { - protected final SystemInfo testingInfo; - private final String applicableAtt; - - protected TNodeFactoryByAttName(String applicableAtt, SystemInfo testingInfo) { - this.applicableAtt = applicableAtt; - this.testingInfo = testingInfo; - } - - @Override - public final boolean applicable(String localName, String qName, Attributes attributes) { - return hasAttribute(attributes, applicableAtt); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryIf.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryIf.java deleted file mode 100644 index e31defcb8f97..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryIf.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.fao.geonet.SystemInfo; -import org.springframework.stereotype.Component; -import org.xml.sax.Attributes; - -import java.io.IOException; - -/** - * Creates fmt-if nodes. - * - * @author Jesse on 11/29/2014. - */ -@Component -public class TNodeFactoryIf extends TNodeFactoryByAttName { - - public static final String IF = "if"; - public static final String ONLY_CHILDREN = "only-children"; - - public TNodeFactoryIf(SystemInfo info, TextContentParser contentParser) { - super(IF, info); - this.textContentParser = contentParser; - } - - public TNodeFactoryIf() { - super(IF, null); - } - - @Override - public TNode create(String localName, String qName, Attributes attributes) throws IOException { - final String value = getValue(attributes, IF); - final boolean onlyChildren = getBooleanAttribute(attributes, ONLY_CHILDREN, false); - - final AttributesFiltered attributesFiltered = new AttributesFiltered(attributes, IF, ONLY_CHILDREN); - return new TNodeIf(SystemInfo.getInfo(this.testingInfo), textContentParser, qName, attributesFiltered, value, onlyChildren); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryInclude.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryInclude.java deleted file mode 100644 index 85f65c578b14..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryInclude.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.base.Optional; -import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.groovy.Handlers; -import org.fao.geonet.api.records.formatters.groovy.TransformationContext; -import org.springframework.stereotype.Component; -import org.xml.sax.Attributes; - -import java.io.IOException; - -/** - * Creates nodes that import other templates into the current template. - * - * @author Jesse on 12/3/2014. - */ -@Component -public class TNodeFactoryInclude extends TNodeFactoryByAttName { - private static final String INCLUDE = "include"; - private static final String REPLACE = "include-replace"; - - - protected TNodeFactoryInclude() { - super(INCLUDE, null); - } - - public TNodeFactoryInclude(SystemInfo info, TextContentParser contentParser) { - super(INCLUDE, info); - super.textContentParser = contentParser; - } - - @Override - public TNode create(String localName, String qName, Attributes attributes) throws IOException { - Attributes filteredAtts = new AttributesFiltered(attributes, INCLUDE, REPLACE); - String templatePath = getValue(attributes, INCLUDE); - - boolean replace = getBooleanAttribute(attributes, REPLACE, false); - return new TNodeInclude(SystemInfo.getInfo(this.testingInfo), textContentParser, qName, filteredAtts, templatePath, replace); - } - - private class TNodeInclude extends TNode { - - private final String templatePath; - private final boolean replace; - - public TNodeInclude(SystemInfo info, TextContentParser parser, String qName, Attributes attributes, String templatePath, boolean replace) - throws IOException { - super(info, parser, qName, attributes); - this.replace = replace; - this.templatePath = templatePath; - if (!replace) { - this.addChild(new TNodeInclude(info, parser, qName, attributes, templatePath, true)); - } - } - - @Override - protected Optional canRender(TRenderContext context) { - return Optional.absent(); - } - - @Override - public void render(TRenderContext context) throws IOException { - if (replace) { - final Handlers handlers = TransformationContext.getContext().getHandlers(); - final FileResult fileResult = handlers.fileResult(this.templatePath, context.getModel(true)); - context.append(fileResult.toString()); - } else { - super.render(context); - } - } - - - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryRepeat.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryRepeat.java deleted file mode 100644 index 4356020b160c..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryRepeat.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.fao.geonet.SystemInfo; -import org.springframework.stereotype.Component; -import org.xml.sax.Attributes; - -import java.io.IOException; -import java.util.Objects; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Creates if/non-empty/etc... nodes. - * - * @author Jesse on 11/29/2014. - */ -@Component -public class TNodeFactoryRepeat extends TNodeFactoryByAttName { - public static final String REPEAT = "repeat"; - public static final String ONLY_CHILDREN = REPEAT + "-only-children"; - private static final Pattern MAP_PATTERN = Pattern.compile("\\s*\\(\\s*(\\S+)\\s*,\\s*(\\S+)\\s*\\)"); - - protected TNodeFactoryRepeat() { - super(REPEAT, null); - } - - public TNodeFactoryRepeat(SystemInfo info, TextContentParser contentParser) { - super(REPEAT, info); - this.textContentParser = contentParser; - } - - @Override - public TNode create(String localName, String qName, Attributes attributes) throws IOException { - String value = getValue(attributes, REPEAT); - final boolean onlyChildren = getBooleanAttribute(attributes, ONLY_CHILDREN, false); - final String[] parts = value.split("\\s+in\\s+"); - final AttributesFiltered attributesFiltered = new AttributesFiltered(attributes, REPEAT, ONLY_CHILDREN); - - String key = parts[1]; - Objects.requireNonNull(key); - String contextName = parts[0]; - Objects.requireNonNull(contextName); - - Matcher mapMatcher = MAP_PATTERN.matcher(contextName); - - SystemInfo info = SystemInfo.getInfo(this.testingInfo); - if (mapMatcher.matches()) { - return new TNodeRepeatMap(info, textContentParser, onlyChildren, qName, attributesFiltered, key, mapMatcher.group(1), mapMatcher.group(2)); - } else { - return new TNodeRepeatIter(info, textContentParser, onlyChildren, qName, attributesFiltered, key, contextName); - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryTransclude.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryTransclude.java deleted file mode 100644 index 05fdac423567..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryTransclude.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.base.Optional; -import com.google.common.collect.Maps; -import org.fao.geonet.Constants; -import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.groovy.Handlers; -import org.fao.geonet.api.records.formatters.groovy.TransformationContext; -import org.springframework.stereotype.Component; -import org.xml.sax.Attributes; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; - -/** - * Creates nodes that import other templates into the current template. - * - * @author Jesse on 12/3/2014. - */ -@Component -public class TNodeFactoryTransclude extends TNodeFactoryByAttName { - private static final String TRANSCLUDE = "transclude"; - private static final String MODEL_KEY = TRANSCLUDE + "-model"; - private static final String EXTRA_MODEL = TRANSCLUDE + "-extra-model"; - private static final String REPLACE = TRANSCLUDE + "-replace"; - - protected TNodeFactoryTransclude() { - super(TRANSCLUDE, null); - } - - public TNodeFactoryTransclude(SystemInfo info, TextContentParser contentParser) { - super(TRANSCLUDE, info); - super.textContentParser = contentParser; - } - - @Override - public TNode create(String localName, String qName, Attributes attributes) throws IOException { - Attributes filteredAtts = new AttributesFiltered(attributes, TRANSCLUDE, REPLACE, MODEL_KEY, EXTRA_MODEL); - String templatePath = getValue(attributes, TRANSCLUDE); - String model = getValue(attributes, MODEL_KEY); - String extraModelAtts = getValue(attributes, EXTRA_MODEL); - - Map extraModel = Maps.newHashMap(); - if (extraModelAtts != null) { - - for (String att : extraModelAtts.split("\\|")) { - final String[] parts = att.split("="); - String key = parts[0]; - String value = parts.length > 1 ? parts[1] : null; - - extraModel.put(key, value); - } - } - - boolean replace = getBooleanAttribute(attributes, REPLACE, false); - - return new TNodeTransclude(SystemInfo.getInfo(this.testingInfo), textContentParser, qName, filteredAtts, templatePath, replace, model, extraModel); - } - - private static class TNodeTransclude extends TNode { - - private final String templatePath; - private final boolean replace; - private final String model; - private final Map extraModel; - - public TNodeTransclude(SystemInfo info, TextContentParser parser, String qName, Attributes attributes, String templatePath, boolean replace, - String model, Map extraModel) throws IOException { - super(info, parser, qName, attributes); - this.replace = replace; - this.templatePath = templatePath; - this.model = model; - this.extraModel = extraModel; - } - - @Override - protected Optional canRender(TRenderContext context) { - return Optional.absent(); - } - - @Override - public void render(TRenderContext context) throws IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - final TRenderContext sepContext = new TRenderContext(outputStream, context.getModel(true)); - if (replace) { - for (TNode childNode : getChildren()) { - childNode.render(sepContext); - } - } else { - super.render(sepContext); - } - - Map fullModel = Maps.newHashMap(); - fullModel.putAll(context.getModel(true)); - for (Map.Entry entry : this.extraModel.entrySet()) { - ByteArrayOutputStream o = new ByteArrayOutputStream(); - textContentParser.parse(entry.getValue().toString()).render(new TRenderContext(o, context.getModel(true))); - fullModel.put(entry.getKey(), new String(o.toByteArray(), Constants.CHARSET)); - } - - fullModel.put(this.model, new String(outputStream.toByteArray(), Constants.CHARSET)); - final Handlers handlers = TransformationContext.getContext().getHandlers(); - final FileResult fileResult = handlers.fileResult(this.templatePath, fullModel); - context.append(fileResult.toString()); - } - } - -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryTranslate.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryTranslate.java deleted file mode 100644 index c0637a648805..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeFactoryTranslate.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.fao.geonet.SystemInfo; -import org.springframework.stereotype.Component; -import org.xml.sax.Attributes; - -import java.io.IOException; - -/** - * Creates fmt-translate nodes. - *

- * A translate node take the text content element and find a translation. depending on the value of - * the fmt-translate attribute the translation is resolved using the {@link - * org.fao.geonet.api.records.formatters.groovy.Functions} translate methods. - *

- * Examples: - *


- * <div fmt-translate="">testString</div>
- * <div fmt-translate="default">testString</div>
- * <div fmt-translate=">file">testString</div>
- * <div fmt-translate="default>file">testString</div>
- * <div fmt-translate="codelist>name">testString</div>
- * <div fmt-translate="codelist>desc>context1">testString</div>
- * <div fmt-translate="codelist>desc>context2">testString</div>
- * <div fmt-translate="node>name>context">testString</div>
- * <div fmt-translate="node>desc">testString</div>
- * 
- * - * @author Jesse on 11/29/2014. - */ -@Component -public class TNodeFactoryTranslate extends TNodeFactoryByAttName { - public static final String TRANSLATE = "translate"; - - public TNodeFactoryTranslate() { - super(TRANSLATE, null); - } - - public TNodeFactoryTranslate(SystemInfo info, TextContentParser textContentParser) { - super(TRANSLATE, info); - this.textContentParser = textContentParser; - } - - @Override - public TNode create(String localName, String qName, Attributes attributes) throws IOException { - final String value = getValue(attributes, TRANSLATE); - final AttributesFiltered attributesFiltered = new AttributesFiltered(attributes, TRANSLATE); - return new TNodeTranslate(SystemInfo.getInfo(this.testingInfo), textContentParser, qName, attributesFiltered, value); - } - -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIf.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIf.java deleted file mode 100644 index e9f7bc84cd20..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIf.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Optional; -import com.google.common.collect.Sets; -import groovy.lang.Binding; -import groovy.lang.GroovyShell; -import org.fao.geonet.SystemInfo; -import org.xml.sax.Attributes; - -import java.io.IOException; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; - -/** - * An "if" node that renders if the model has a truthy value for the given key. - *

- * In this case truthy means, non-null, non-empty (if string, collection, array or map), a number != - * 0 or true value. - *

- * If the expression starts with a ! then check is not-ed. - *

- * Example: - *

- * For the template: - *


- *     &div fmt-if="key">data&/div>
- * 
- * the div will be rendered if there is a value "key" in the model that is a string or Iterable that - * is non-empty. - * - * @author Jesse on 11/29/2014. - */ -public class TNodeIf extends TNode { - public static final double PRECISION = 0.000000001; - private final String expr; - private final boolean not; - private final Set scriptVariables; - private final boolean onlyChildren; - - public TNodeIf(SystemInfo info, TextContentParser parser, String qName, Attributes attributes, String expr, boolean onlyChildren) throws IOException { - super(info, parser, qName, attributes); - this.onlyChildren = onlyChildren; - final Matcher matcher = TextContentParser.INTERPOLATION_PATTERN.matcher(expr); - if (matcher.find()) { - this.scriptVariables = Sets.newHashSet(); - int start = 0; - StringBuilder builder = new StringBuilder(); - do { - String key = matcher.group(1).trim(); - this.scriptVariables.add(key); - builder.append(expr, start, matcher.start()); - builder.append(key); - - start = matcher.end(); - } while (matcher.find()); - - builder.append(expr.substring(start)); - - this.expr = builder.toString(); - this.not = false; - } else { - this.scriptVariables = null; - if (expr.startsWith("!")) { - this.not = true; - this.expr = expr.substring(1); - } else { - this.not = false; - this.expr = expr; - } - } - } - - @VisibleForTesting - static String isTruthy(Object val) { - if (val == null) { - return "null"; - } - if (val instanceof String) { - String sVal = (String) val; - return sVal.isEmpty() ? "empty" : null; - } else if (val instanceof Iterable) { - Iterable itVal = (Iterable) val; - return itVal.iterator().hasNext() ? null : "empty"; - } else if (val instanceof Enumeration) { - Enumeration itVal = (Enumeration) val; - return itVal.hasMoreElements() ? null : "empty"; - } else if (val instanceof Iterator) { - Iterator itVal = (Iterator) val; - return itVal.hasNext() ? null : "empty"; - } else if (val instanceof Map) { - Map mapVal = (Map) val; - return mapVal.isEmpty() ? "empty" : null; - } else if (val instanceof Boolean) { - return (Boolean) val ? null : "false"; - } else if (val instanceof Double) { - return Math.abs((Double) val) > PRECISION ? null : "0"; - } else if (val instanceof Float) { - return Math.abs((Float) val) > PRECISION ? null : "0"; - } else if (val instanceof Number) { - return ((Number) val).intValue() != 0 ? null : "0"; - } else if (val instanceof Character) { - return null; - } else if (val.getClass().isArray()) { - return ((Object[]) val).length > 0 ? null : "empty"; - } else { - throw new AssertionError("Not a recognized type: " + val.getClass() + ": " + val); - } - } - - @Override - protected Optional canRender(TRenderContext context) { - if (this.scriptVariables == null) { - final Object val = context.getModelValue(this.expr); - final String truthy = isTruthy(val); - if (not) { - return truthy != null ? Optional.absent() : - Optional.of("fmt-if=!" + this.expr + " is false (" + this.expr + " is true)"); - } else { - if (truthy != null) { - return Optional.of("fmt-if=" + this.expr + " is " + truthy); - } - return Optional.absent(); - } - } else { - Binding binding = new Binding(); - for (String scriptVariable : this.scriptVariables) { - binding.setVariable(scriptVariable, context.getModelValue(scriptVariable)); - } - GroovyShell shell = new GroovyShell(binding); - - Object value = shell.evaluate(this.expr); - - if (value instanceof Boolean && (Boolean) value) { - return Optional.absent(); - } else { - return Optional.of(this.expr + " resulted in a non-true value: '" + value + "'"); - } - } - } - - @Override - public void render(TRenderContext context) throws IOException { - final Optional canRenderOptional = canRender(context); - if (!canRenderOptional.isPresent()) { - if (onlyChildren) { - for (TNode child : getChildren()) { - child.render(context); - } - } else { - super.render(context); - } - } else { - addCannontRenderComment(context, canRenderOptional); - } - } - -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatIter.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatIter.java deleted file mode 100644 index aadac749a70d..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatIter.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.base.Joiner; -import com.google.common.base.Optional; -import com.google.common.collect.Maps; -import groovy.util.slurpersupport.GPathResult; -import org.fao.geonet.SystemInfo; -import org.xml.sax.Attributes; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -/** - * @author Jesse on 11/29/2014. - */ -public class TNodeRepeatIter extends TNode { - private static final String INDEX_KEY = "$index"; - private static final String FIRST_KEY = "$first"; - private static final String LAST_KEY = "$last"; - private static final String ODD_KEY = "$odd"; - private static final String EVEN_KEY = "$even"; - private static final String MIDDLE_KEY = "$middle"; - private final String key; - private final String rowContextKey; - private final boolean onlyChildren; - - public TNodeRepeatIter(SystemInfo info, TextContentParser parser, boolean onlyChildren, String qName, Attributes attributes, String key, String rowContextKey) throws IOException { - super(info, parser, qName, attributes); - this.key = key; - this.rowContextKey = rowContextKey; - this.onlyChildren = onlyChildren; - } - - static void addIndexInfo(Map newModelMap, int index, int total) { - newModelMap.put(INDEX_KEY, index); - newModelMap.put(FIRST_KEY, index == 0); - newModelMap.put(LAST_KEY, (total - 1) == index); - newModelMap.put(ODD_KEY, Math.abs(index % 2) == 1); - newModelMap.put(EVEN_KEY, Math.abs(total % 2) == 0); - newModelMap.put(MIDDLE_KEY, (total / 2) == index); - } - - @SuppressWarnings("unchecked") - @Override - public void render(TRenderContext context) throws IOException { - final Object modelValue = context.getModelValue(this.key); - - if (modelValue == null) { - String options = Joiner.on(", ").join(context.getAllModelKeys()); - throw new TemplateException("There is no model item with the key: " + this.key + ". Options include: " + options); - } - - Iterable iter; - int size; - if (modelValue instanceof Collection) { - final Collection collection = (Collection) modelValue; - iter = collection; - size = collection.size(); - } else if (modelValue instanceof GPathResult) { - GPathResult value = (GPathResult) modelValue; - iter = value; - size = value.size(); - } else if (modelValue instanceof Map) { - Map map = (Map) modelValue; - iter = map.entrySet(); - size = map.size(); - } else if (modelValue.getClass().isArray()) { - Object[] value = (Object[]) modelValue; - iter = Arrays.asList(value); - size = value.length; - } else { - iter = Collections.singletonList(modelValue); - size = 1; - } - - int i = 0; - for (Object row : iter) { - Map newModelMap = Maps.newHashMap(); - newModelMap.put(this.rowContextKey, row); - addIndexInfo(newModelMap, i, size); - - TRenderContext childContext = context.childContext(newModelMap); - if (!this.onlyChildren) { - context.append("<").append(qName); - attributes.render(childContext); - context.append(">"); - } - - for (TNode node : getChildren()) { - node.render(childContext); - } - - if (!this.onlyChildren) { - end.render(childContext); - } - - i++; - } - - if (i == 0 && this.info.isDevMode()) { - context.append(""); - } - } - - @Override - protected Attributes customAttributes(TRenderContext context) { - return null; - } - - @Override - protected Optional canRender(TRenderContext context) { - return Optional.absent(); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatMap.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatMap.java deleted file mode 100644 index a616e406837a..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatMap.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.base.Joiner; -import com.google.common.base.Optional; -import com.google.common.collect.Maps; -import org.fao.geonet.SystemInfo; -import org.xml.sax.Attributes; - -import java.io.IOException; -import java.util.Map; - -/** - * @author Jesse on 11/29/2014. - */ -public class TNodeRepeatMap extends TNode { - private final String key, rowKeyName, rowValueName; - private final boolean onlyChildren; - - public TNodeRepeatMap(SystemInfo info, TextContentParser parser, boolean onlyChildren, String qName, Attributes attributes, String key, String rowKeyName, String rowValueName) - throws IOException { - super(info, parser, qName, attributes); - this.key = key; - this.rowKeyName = rowKeyName; - this.rowValueName = rowValueName; - this.onlyChildren = onlyChildren; - } - - @Override - public void render(TRenderContext context) throws IOException { - final Object modelValue = context.getModelValue(this.key); - - if (!(modelValue instanceof Map)) { - if (modelValue == null) { - String options = Joiner.on(", ").join(context.getAllModelKeys()); - throw new TemplateException("There is no model item with the key: " + this.key + ". Options include: " + options); - } else { - throw new TemplateException( - "Expected a map for (" + rowKeyName + ", " + rowValueName + ") in " + this.key + " but got a " + modelValue); - } - - } - @SuppressWarnings("unchecked") - Map map = (Map) modelValue; - - if (map.isEmpty() && this.info.isDevMode()) { - context.append(""); - } - - int i = 0; - int size = map.size(); - for (Map.Entry entry : map.entrySet()) { - Map newModelMap = Maps.newHashMap(); - newModelMap.put(this.rowKeyName, entry.getKey()); - newModelMap.put(this.rowValueName, entry.getValue()); - TNodeRepeatIter.addIndexInfo(newModelMap, i, size); - - TRenderContext childContext = context.childContext(newModelMap); - - if (!this.onlyChildren) { - context.append("<").append(qName); - attributes.render(childContext); - context.append(">"); - } - - for (TNode node : getChildren()) { - node.render(childContext); - } - if (!this.onlyChildren) { - end.render(childContext); - } - - i++; - } - } - - @Override - protected Attributes customAttributes(TRenderContext context) { - return null; - } - - @Override - protected Optional canRender(TRenderContext context) { - return Optional.absent(); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTextContent.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTextContent.java deleted file mode 100644 index ecf4ac22021a..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTextContent.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.base.Optional; -import org.fao.geonet.SystemInfo; - -import java.io.IOException; - -/** - * @author Jesse on 11/30/2014. - */ -public class TNodeTextContent extends TNode { - private final TextBlock textContent; - - public TNodeTextContent(SystemInfo info, TextContentParser parser, TextBlock textContent) throws IOException { - super(info, parser, "", EMPTY_ATTRIBUTES); - this.textContent = textContent; - } - - @Override - public void render(TRenderContext context) throws IOException { - textContent.render(context); - } - - @Override - protected Optional canRender(TRenderContext context) { - return Optional.absent(); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranslate.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranslate.java deleted file mode 100644 index f167dfa0d3b1..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranslate.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.base.Optional; -import org.fao.geonet.Constants; -import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.groovy.Functions; -import org.fao.geonet.api.records.formatters.groovy.TransformationContext; -import org.xml.sax.Attributes; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * @author Jesse on 12/2/2014. - */ -class TNodeTranslate extends TNode { - - private final Translator translator; - - public TNodeTranslate(SystemInfo info, TextContentParser textContentParser, String qName, Attributes attributes, String key) throws IOException { - super(info, textContentParser, qName, attributes); - String[] parts = key.split(">"); - String type = parts.length > 1 ? parts[1] : null; - String context = parts.length > 2 ? parts[2] : null; - if (parts[0].equalsIgnoreCase("codelist")) { - translator = new CodeListTranslator(type, textContentParser, context); - } else if (parts[0].equalsIgnoreCase("node")) { - translator = new NodeTranslator(type, textContentParser, context); - } else if (parts[0].equalsIgnoreCase("default") || parts[0].trim().isEmpty()) { - translator = new DefaultTranslator(type, textContentParser); - } else { - throw new TemplateException( - "Translate type: '" + parts[0] + "' is not one of the recognized type: ['', 'default', 'node', 'codelist']"); - } - } - - @Override - protected Optional canRender(TRenderContext context) { - return Optional.absent(); - } - - @Override - public void setTextContent(String text) throws IOException { - if (text.isEmpty()) { - return; - } - try { - addChild(new Node(info, textContentParser, text)); - } catch (Exception e) { - throw new TemplateException(e); - } - } - - private interface Translator { - TextBlock translate(String text) throws Exception; - } - - private static class CodeListTranslator implements Translator { - private final String type; - private final String context; - private final TextContentParser textContentParser; - - private CodeListTranslator(String type, TextContentParser parser, String context) { - this.type = type; - this.context = context; - this.textContentParser = parser; - } - - public TextBlock translate(String text) throws Exception { - final Functions functions = TransformationContext.getContext().getFunctions(); - final String translation = functions.codelistTranslation(text, context, type); - return textContentParser.parse(translation); - } - } - - private static class NodeTranslator implements Translator { - private final String type; - private final String context; - private final TextContentParser textContentParser; - - private NodeTranslator(String type, TextContentParser parser, String context) { - this.type = type; - this.context = context; - this.textContentParser = parser; - } - - public TextBlock translate(String text) throws Exception { - final Functions functions = TransformationContext.getContext().getFunctions(); - final String translation = functions.nodeTranslation(text, context, type); - return textContentParser.parse(translation); - } - } - - private static class DefaultTranslator implements Translator { - private final String file; - private final TextContentParser textContentParser; - - private DefaultTranslator(String file, TextContentParser parser) { - this.file = file; - this.textContentParser = parser; - } - - public TextBlock translate(String text) throws Exception { - final Functions functions = TransformationContext.getContext().getFunctions(); - final String translation = functions.translate(text, file); - return textContentParser.parse(translation); - } - } - - private class Node extends TNode { - private final String text; - - public Node(SystemInfo info, TextContentParser parser, String text) throws IOException { - super(info, parser, "", EMPTY_ATTRIBUTES); - this.text = text; - } - - @Override - protected Optional canRender(TRenderContext context) { - return Optional.absent(); - } - - @Override - public void render(TRenderContext context) throws IOException { - final TextBlock block = textContentParser.parse(text); - - final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - block.render(new TRenderContext(stream, context.getModel(true))); - - try { - translator.translate(new String(stream.toByteArray(), Constants.CHARSET)).render(context); - } catch (Exception e) { - throw new TemplateException(e); - } - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TRenderContext.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TRenderContext.java deleted file mode 100644 index 05b179fa1809..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TRenderContext.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import groovy.util.slurpersupport.GPathResult; -import org.apache.commons.io.IOUtils; -import org.fao.geonet.Constants; -import org.springframework.beans.BeanUtils; - -import javax.annotation.Nonnull; -import java.beans.PropertyDescriptor; -import java.io.*; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.charset.Charset; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * A render context for rendering a Template Tree. - * - * @author Jesse on 11/29/2014. - */ -public class TRenderContext implements Appendable, Closeable { - private final TRenderContext parent; - private final Map model; - private final OutputStream outputStream; - private final Writer writer; - - private TRenderContext(TRenderContext parent, Map model, OutputStream outputStream, Writer writer) { - this.parent = parent; - this.model = model; - this.outputStream = outputStream; - this.writer = writer; - } - - public TRenderContext(OutputStream outputStream, Map model) { - this(outputStream, Constants.CHARSET, model); - } - - public TRenderContext(OutputStream outputStream, Charset charset, Map model) { - this.parent = null; - this.outputStream = outputStream; - this.model = model; - this.writer = new OutputStreamWriter(outputStream, charset); - } - - @Override - public TRenderContext append(CharSequence csq) throws IOException { - writer.append(csq); - writer.flush(); - return this; - } - - @Override - public TRenderContext append(CharSequence csq, int start, int end) throws IOException { - writer.append(csq, start, end); - writer.flush(); - return this; - } - - @Override - public TRenderContext append(char c) throws IOException { - writer.append(c); - writer.flush(); - return this; - } - - public Set getAllModelKeys() { - Set keys = Sets.newHashSet(); - if (this.parent != null) { - keys.addAll(this.parent.getAllModelKeys()); - } - keys.addAll(this.model.keySet()); - return keys; - } - - @Override - public void close() throws IOException { - IOUtils.closeQuietly(this.writer); - IOUtils.closeQuietly(this.outputStream); - } - - public Object getModelValue(String expr) { - final int indexOfDot = expr.indexOf('.'); - if (indexOfDot > -1) { - String key = expr.substring(0, indexOfDot); - final String property = expr.substring(indexOfDot + 1); - return getModelValue(key, property); - } - - return getModelValue(expr, null); - } - - private Object getModelValue(String expr, String property) { - Object value = this.model.get(expr.trim()); - if (value == null && parent != null) { - value = parent.getModelValue(expr); - } - if (property == null) { - return value; - } - - try { - if (value == null) { - throw new TemplateException( - "There is no object in the model map with the id '" + expr + "' in the model map. The model selection " + - "expression is: " + expr.trim() + "." + property.trim() + "'.\nThe current options are: \n" + getAllModelKeys()); - } - return getProperty(value, property); - } catch (NullPropertyException e) { - throw new TemplateException("The value of the property '" + e + "' is null. The full selection expression is: " + - "'" + expr.trim() + "." + property.trim() + "'"); - } catch (EmptyPropertyException e) { - throw new TemplateException("Model expression: '" + expr.trim() + "." + property.trim() + "' contains an empty section."); - } catch (InvocationTargetException | IllegalAccessException e) { - throw new TemplateException( - "Error accessing the properties in the property path of: '" + - expr.trim() + "." + property + "'. " + e, e); - } catch (NoSuchPropertyException e) { - throw new TemplateException( - "One of the properties in the property path: '" + expr.trim() + "." + property + "' does not exist on " + - "the object selected at that point. The property missing is: " + e); - } - } - - private Object getProperty(@Nonnull Object baseValue, String property) throws InvocationTargetException, IllegalAccessException { - Object value = baseValue; - int indexOfDot = property.indexOf('.'); - while (indexOfDot > -1) { - String prop = property.substring(0, indexOfDot); - property = property.substring(indexOfDot + 1); - - value = safeGetProperty(value, prop); - - indexOfDot = property.indexOf('.'); - - - if (value == null) { - throw new NullPropertyException(prop); - } - } - - return safeGetProperty(value, property); - } - - private Object safeGetProperty(@Nonnull Object value, String prop) throws InvocationTargetException, IllegalAccessException { - prop = prop.trim(); - if (prop.trim().isEmpty()) { - throw new EmptyPropertyException(); - } - if (value instanceof GPathResult) { - GPathResult result = (GPathResult) value; - if (prop.replace("\\s+", "").equals("name()")) { - return result.name(); - } - return result.getProperty(prop); - } - if (value instanceof Map) { - Map map = (Map) value; - return map.get(prop); - } else if (value instanceof List) { - List list = (List) value; - try { - return list.get(Integer.parseInt(prop)); - } catch (NumberFormatException e) { - throw new IllegalArgumentException( - "When accessing a list the property must be a number. Property:" + prop + ". List: " + list); - } - } else { - final PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(value.getClass(), prop.trim()); - if (propertyDescriptor == null) { - try { - final Field declaredField = value.getClass().getDeclaredField(prop.trim()); - declaredField.setAccessible(true); - return declaredField.get(value); - } catch (NoSuchFieldException e) { - // skip - } - throw new NoSuchPropertyException(prop + " on object: " + value + " (" + value.getClass() + ")"); - } - Method method = propertyDescriptor.getReadMethod(); - method.setAccessible(true); - value = method.invoke(value); - return value; - } - } - - public TRenderContext childContext(Map newModel) { - return new TRenderContext(this, newModel, outputStream, writer); - } - - public Map getModel(boolean mergeParentModels) { - Map fullModel; - if (mergeParentModels && this.parent != null) { - fullModel = this.parent.getModel(true); - fullModel.putAll(this.model); - } else { - fullModel = Maps.newHashMap(this.model); - } - - return fullModel; - } - - private static class EmptyPropertyException extends RuntimeException { - } - - private static class NoSuchPropertyException extends RuntimeException { - private NoSuchPropertyException(String message) { - super(message); - } - } - - private static class NullPropertyException extends RuntimeException { - private final String prop; - - private NullPropertyException() { - prop = ""; - } - - private NullPropertyException(String prop) { - this.prop = prop; - } - - @Override - public String toString() { - return prop; - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCache.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCache.java deleted file mode 100644 index c3c08be1a2f8..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCache.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import org.fao.geonet.ApplicationContextHolder; -import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.ConfigFile; -import org.fao.geonet.kernel.SchemaManager; -import org.fao.geonet.utils.IO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.stereotype.Component; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Map; -import java.util.Set; - -import static org.fao.geonet.api.records.formatters.FormatterConstants.SCHEMA_PLUGIN_FORMATTER_DIR; - -/** - * A Cache for the template files that are loaded by FileResult objects. This is intended to reduce - * the number of files that need to be loaded. - * - * @author Jesse on 10/20/2014. - */ -@Component -public class TemplateCache { - - - @VisibleForTesting - final Map canonicalFileNameToText = Maps.newHashMap(); - private final Set filesKnownToNotExist = Sets.newHashSet(); - @VisibleForTesting - @Autowired - TemplateParser xmlTemplateParser; - - public synchronized FileResult createFileResult(Path formatterDir, Path schemaDir, Path rootFormatterDir, String path, - Map model) throws IOException { - return new Request().createFileResult(formatterDir, schemaDir, rootFormatterDir, path, model); - } - - private class Request { - - private final SystemInfo systemInfo; - private final SchemaManager schemaManager; - - public Request() { - final ConfigurableApplicationContext context = ApplicationContextHolder.get(); - this.systemInfo = context.getBean(SystemInfo.class); - this.schemaManager = context.getBean(SchemaManager.class); - } - - public synchronized FileResult createFileResult(Path formatterDir, Path schemaDir, Path rootFormatterDir, String path, - Map model) throws IOException { - final Path originalPath = IO.toPath(path); - Path file = formatterDir.resolve(path); - TNode template = fetchFromCache(originalPath, file); - Path fromParentSchema; - - if (template != null) { - return new FileResult(template, model); - } - - if (schemaDir != null) { - file = schemaDir.resolve(path); - } - - template = fetchFromCache(originalPath, file); - if (template != null) { - return new FileResult(template, model); - } - fromParentSchema = fromParentSchema(formatterDir, schemaDir, path); - if (fromParentSchema != null) { - template = fetchFromCache(originalPath, fromParentSchema); - if (template != null) { - return new FileResult(template, model); - } - } - - file = rootFormatterDir.resolve(path); - template = fetchFromCache(originalPath, file); - if (template != null) { - return new FileResult(template, model); - } - - file = formatterDir.resolve(path); - if (!exists(file) && schemaDir != null) { - file = schemaDir.resolve(path); - } - - if (!exists(file)) { - if (fromParentSchema == null) { - fromParentSchema = fromParentSchema(formatterDir, schemaDir, path); - } - if (fromParentSchema != null) { - file = fromParentSchema; - } - } - if (!exists(file)) { - file = rootFormatterDir.resolve(path); - } - if (!exists(file)) { - throw new IllegalArgumentException("There is no file: " + path + " in any of: \n" + - "\t * " + formatterDir + "\n" + - "\t * " + schemaDir + "\n" + - "\t * if parent exists: " + fromParentSchema + "\n" + - "\t * " + rootFormatterDir); - } - - template = xmlTemplateParser.parse(file); - cacheTemplate(originalPath, file, template); - - return new FileResult(template, model); - } - - public boolean exists(Path file) throws IOException { - if (!this.systemInfo.isDevMode() && - (filesKnownToNotExist.contains(file) || filesKnownToNotExist.contains(file.toAbsolutePath()))) { - return false; - } - final boolean exists = Files.exists(file); - if (!exists) { - filesKnownToNotExist.add(file); - filesKnownToNotExist.add(file.toAbsolutePath()); - } - return exists; - } - - public void cacheTemplate(Path originalPath, Path file, TNode template) throws IOException { - doCache(originalPath, template); - doCache(toRealPath(file), template); - doCache(file, template); - doCache(file.toAbsolutePath(), template); - doCache(file.toAbsolutePath().normalize(), template); - } - - public void doCache(Path originalPath, TNode template) { - filesKnownToNotExist.remove(originalPath); - canonicalFileNameToText.put(originalPath, template); - } - - public TNode fetchFromCache(Path originalPath, Path file) throws IOException { - if (this.systemInfo.isDevMode()) { - return null; - } - TNode template = canonicalFileNameToText.get(originalPath); - boolean recache = false; - if (template == null) { - template = canonicalFileNameToText.get(file); - recache = true; - } - if (template == null) { - template = canonicalFileNameToText.get(file.toAbsolutePath()); - recache = true; - } - if (template == null) { - template = canonicalFileNameToText.get(file.toAbsolutePath().normalize()); - recache = true; - } - if (template == null) { - template = canonicalFileNameToText.get(toRealPath(file)); - recache = true; - } - if (recache && template != null) { - cacheTemplate(originalPath, file, template); - } - return template; - } - - private Path toRealPath(Path file) throws IOException { - if (exists(file)) { - return file.toRealPath(); - } else { - return file.toAbsolutePath().normalize(); - } - } - - private Path fromParentSchema(Path formatterDir, Path schemaDir, String path) throws IOException { - final ConfigFile configFile; - if (formatterDir != null) { - configFile = new ConfigFile(formatterDir, true, schemaDir); - } else { - configFile = new ConfigFile(schemaDir, false, null); - } - - final String schemaName = configFile.dependOn(); - if (schemaName != null) { - Path parentSchema = this.schemaManager.getSchemaDir(schemaName).resolve(SCHEMA_PLUGIN_FORMATTER_DIR); - - Path file = parentSchema.resolve(path); - if (exists(file)) { - return file; - } - - return fromParentSchema(null, parentSchema, path); - } - - - return null; - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateException.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateException.java deleted file mode 100644 index 73400f1d1372..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateException.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -/** - * Exception raised in the template package. - * - * @author Jesse on 11/29/2014. - */ -public class TemplateException extends RuntimeException { - public TemplateException(String message) { - super(message); - } - - public TemplateException(Throwable e) { - super(e); - } - - public TemplateException(String message, Throwable e) { - super(message, e); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateParser.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateParser.java deleted file mode 100644 index b836681cff7d..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateParser.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.annotations.VisibleForTesting; -import org.fao.geonet.Constants; -import org.fao.geonet.SystemInfo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.xml.sax.Attributes; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.Stack; - -/** - * This class parses a XML Template file into a tree data structure representing the template. - *

- * Nodes in the tree can have custom behaviour that is determined according to the attributes on the - * template XML. For example a node might be an nonEmpty node where the node will only be rendered - * if the attribute is nonEmpty (non-empty/non-null string or collection) - * - * @author Jesse on 11/29/2014. - */ -@Component -public class TemplateParser { - @SuppressWarnings("SpringJavaAutowiringInspection") - @Autowired - @VisibleForTesting - List tnodeFactories; - @VisibleForTesting - @Autowired - TextContentParser textContentParser; - - public TNode parse(Path path) { - try { - final TNode root = parse(Files.readAllBytes(path), TemplateType.fromPath(path)); - root.setUnparsedSize(Files.size(path)); - return root; - } catch (IOException e) { - throw new TemplateException(e); - } catch (TemplateException e) { - if (e.getCause() != null) { - throw new TemplateException("Error when parsing " + path + ":" + e.getCause().getMessage(), e.getCause()); - } else { - throw new TemplateException("Error when parsing " + path + ":" + e.getMessage(), e); - } - } - } - - public TNode parse(byte[] in, TemplateType type) { - switch (type) { - case XML: - try { - SAXParserFactory factory = SAXParserFactory.newInstance(); - SAXParser saxParser = factory.newSAXParser(); - - Handler handler = new Handler(); - - InputSource source = new InputSource(new ByteArrayInputStream(in)); - source.setEncoding(Constants.ENCODING); - - saxParser.parse(source, handler); - return handler.root; - } catch (ParserConfigurationException | SAXException | IOException e) { - throw new TemplateException(e); - } - default: - try { - final String unparsedText = new String(in, Constants.ENCODING); - return new TNodeTextContent(getSystemInfo(), textContentParser, textContentParser.parse(unparsedText)); - } catch (IOException e) { - throw new TemplateException(e); - } - } - } - - protected SystemInfo getSystemInfo() { - return SystemInfo.getInfo(); - } - - private class Handler extends DefaultHandler { - - public TNode root; - public Stack stack = new Stack<>(); - public char[] textContent; - - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - try { - processText(); - TNodeFactory found = null; - for (TNodeFactory factory : tnodeFactories) { - if (factory.applicable(localName, qName, attributes)) { - if (found != null) { - throw new TemplateException( - "More than one directive attribute was found on " + qName + "\nFound: " + - found.getClass().getSimpleName() + " and " + factory.getClass().getSimpleName()); - } - setCurrentNode(factory.create(localName, qName, attributes)); - found = factory; - } - } - if (found == null) { - setCurrentNode(new SimpleTNode(getSystemInfo(), textContentParser, qName, attributes)); - } - } catch (IOException e) { - throw new TemplateException(e); - } - } - - private void setCurrentNode(TNode node) { - if (root == null) { - this.root = node; - } else { - this.stack.peek().addChild(node); - } - this.stack.push(node); - - } - - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - processText(); - this.stack.pop(); - } - - @Override - public void characters(final char[] ch, final int start, final int length) throws SAXException { - final int copyToStart; - if (this.textContent != null) { - char[] tmp = this.textContent; - this.textContent = new char[tmp.length + length]; - System.arraycopy(tmp, 0, this.textContent, 0, tmp.length); - copyToStart = tmp.length; - } else { - copyToStart = 0; - this.textContent = new char[length]; - } - System.arraycopy(ch, start, this.textContent, copyToStart, length); - } - - private void processText() { - if (this.textContent != null && !this.stack.isEmpty()) { - try { - this.stack.peek().setTextContent(new String(this.textContent)); - } catch (IOException e) { - throw new TemplateException(e); - } - } - this.textContent = null; - } - - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateType.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateType.java deleted file mode 100644 index f99cb9f87cc5..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateType.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -/** - * Represents the template types supported byt the template parser. - * - * @author Jesse on 11/30/2014. - */ -public enum TemplateType { - XML, TEXT; - - public static TemplateType fromContentType(String type) { - if (type.contains("xml") || type.contains("html") || type.contains("xsd") || type.contains("xsl")) { - return XML; - } else { - return TEXT; - } - } - - public static TemplateType fromPath(Path path) throws IOException { - String type = Files.probeContentType(path); - if (type == null) { - String file = path.getFileName().toString(); - if (file.endsWith(".xsd") || - file.endsWith(".html") || - file.endsWith(".xml")) { - return XML; - } else { - return TEXT; - } - } else { - return fromContentType(Files.probeContentType(path)); - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextBlock.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextBlock.java deleted file mode 100644 index 51a2f306eb8c..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextBlock.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; - -import java.io.IOException; -import java.util.List; - -/** - * Text Block. - * - * @author Jesse on 11/29/2014. - */ -public class TextBlock { - private final List content = Lists.newArrayList(); - - public TextBlock add(TextContent content) { - this.content.add(content); - return this; - } - - public void render(TRenderContext context) throws IOException { - for (TextContent textContent : this.content) { - context.append(textContent.text(context)); - } - } - - @Override - public String toString() { - return Joiner.on(' ').join(content); - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContent.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContent.java deleted file mode 100644 index a173d27a5489..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContent.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -/** - * A part of text Content. - * - * @author Jesse on 11/29/2014. - */ -public interface TextContent { - String text(TRenderContext content); -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentFilter.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentFilter.java deleted file mode 100644 index 462311ef2ab4..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentFilter.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -/** - * Filters to apply to the result of text replacement when parsing text. For example the text - * replacement of: - * - * {{text | filter}} - *

- * Will result in the model value "text" being retrieved from the model and then the filter with the - * name "filter" will process the value to give the final value. - * - * @author Jesse on 12/19/2014. - */ -public interface TextContentFilter { - /** - * Process the input (raw) value. - * - * @param context the render context this filter is operating withing - * @param rawValue the pre-filter value - * @return the filtered value. - */ - String process(TRenderContext context, String rawValue); -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentParser.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentParser.java deleted file mode 100644 index 9f8e580e09d1..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentParser.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Parses text to extract sections that need to be replaced with a value from the model. - * - * @author Jesse on 11/29/2014. - */ -@Component -public class TextContentParser { - final static Pattern INTERPOLATION_PATTERN = Pattern.compile("\\{\\{(\\s*[^}]+\\s*)\\}\\}"); - - @SuppressWarnings("SpringJavaAutowiringInspection") - @Autowired - @VisibleForTesting - Map filters = Maps.newHashMap(); - - public TextBlock parse(String text) { - TextBlock textBlock = new TextBlock(); - - final Matcher matcher = INTERPOLATION_PATTERN.matcher(text); - - int start = 0; - while (matcher.find()) { - String key = matcher.group(1).trim(); - textBlock.add(new TextContentStatic(text.substring(start, matcher.start()))); - - List applicableFilters = Lists.newArrayList(); - final String[] parts = key.split("\\|"); - key = parts[0]; - for (int i = 1; i < parts.length; i++) { - String filterKey = parts[i].trim(); - TextContentFilter filter = this.filters.get(filterKey); - if (filter == null) { - throw new TemplateException("There is no TextContentFilter with the id: '" + filterKey + "'"); - } - - applicableFilters.add(filter); - } - textBlock.add(new TextContentReplacement(key, applicableFilters)); - - start = matcher.end(); - } - - textBlock.add(new TextContentStatic(text.substring(start))); - - return textBlock; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentReplacement.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentReplacement.java deleted file mode 100644 index 943edb88053a..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentReplacement.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import java.util.List; - -/** - * A Text Content where the value is looked up in the Model using the key with a fallback to the - * key. - * - * @author Jesse on 11/29/2014. - */ -public class TextContentReplacement implements TextContent { - private final String key; - private final List filters; - - public TextContentReplacement(String key, List filters) { - this.key = key; - this.filters = filters; - } - - @Override - public String text(TRenderContext content) { - Object value = content.getModelValue(key); - if (value == null) { - value = key; - } - for (TextContentFilter filter : filters) { - value = filter.process(content, value.toString()); - } - - return value.toString(); - } - - - @Override - public String toString() { - return "{{" + key + "}}"; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentStatic.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentStatic.java deleted file mode 100644 index c9e8787a4223..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentStatic.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -/** - * @author Jesse on 11/29/2014. - */ -public class TextContentStatic implements TextContent { - private final String text; - - public TextContentStatic(String text) { - this.text = text; - } - - @Override - public String text(TRenderContext content) { - return this.text; - } - - @Override - public String toString() { - return text; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/AssociatedLink.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/AssociatedLink.java deleted file mode 100644 index 892d28b62cb0..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/AssociatedLink.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.util; - -/** - * Represent a link and the text for the link. - * - * @author Jesse on 11/18/2014. - */ -public class AssociatedLink extends Link { - private String abstr, logo, metadataId, parentUuid; - - public AssociatedLink(String href, String text) { - this(href, text, null); - - } - - public AssociatedLink(String href, String text, String cls) { - super(href, text, cls); - } - - public String getAbstract() { - return abstr; - } - - public void setAbstract(String abstr) { - this.abstr = abstr; - } - - public String getLogo() { - return logo; - } - - public void setLogo(String logo) { - this.logo = "../../" + logo; - this.logo = this.logo.replaceAll("/+", "/"); - } - - public String getMetadataId() { - return metadataId; - } - - public void setMetadataId(String metadataId) { - this.metadataId = metadataId; - } - - public String getParentUuid() { - return parentUuid; - } - - public void setParentUuid(String parentUuid) { - this.parentUuid = parentUuid; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Direction.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Direction.java deleted file mode 100644 index 963a4f72caa1..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Direction.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.util; - -/** - * Represents the direction of a relationship. - * - * @author Jesse on 4/23/2015. - */ -public enum Direction { - /** - * Indicates that the metadata is the parent of a relationship. For most relationships the - * child metadata contains the link to the parent. For example parentIdentifier, - * aggregationInfo and lineage links are in the child. Other types like coupledResource (in - * services) then the parent contains the relationship. - */ - PARENT, - /** - * Indicates that the metadata is the child of a relationship. For most relationships the child - * metadata contains the link to the parent. For example parentIdentifier, aggregationInfo and - * lineage links are in the child. Other types like coupledResource (in services) then the - * parent contains the relationship. - */ - CHILD, - /** - * Indicates that the metadata is the sibling of the related metadata. In otherwords, both - * metadata are part of the same group of related metadata, both are children metadata and part - * of the same group/relationship. - */ - SIBLING - -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Link.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Link.java deleted file mode 100644 index 2514dc271038..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Link.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.util; - -/** - * Represent a link and the text for the link. - * - * @author Jesse on 11/18/2014. - */ -public class Link { - private final String href; - private final String text; - private final String tip; - private final String cls; - - public Link(String href, String text) { - this(href, text, null); - - } - - public Link(String href, String text, String cls) { - this.href = href; - this.tip = text; - if (text != null && text.length() > 60) { - text = text.substring(0, 57) + "..."; - } - this.text = text; - this.cls = cls; - } - - public String getHref() { - return href; - } - - public String getText() { - return text; - } - - public String getTip() { - return tip; - } - - public String getCls() { - return cls; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Link link = (Link) o; - - if (href != null ? !href.equals(link.href) : link.href != null) return false; - return text != null ? text.equals(link.text) : link.text == null; - } - - @Override - public int hashCode() { - int result = href != null ? href.hashCode() : 0; - result = 31 * result + (text != null ? text.hashCode() : 0); - return result; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/LinkBlock.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/LinkBlock.java deleted file mode 100644 index 3d2dd7607698..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/LinkBlock.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.util; - -import com.google.common.base.Function; -import com.google.common.collect.Collections2; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import org.jdom.JDOMException; - -import javax.annotation.Nullable; -import java.io.IOException; -import java.util.Collection; -import java.util.Map; - -/** - * @author Jesse on 11/20/2014. - */ -public class LinkBlock { - public static String CSS_CLASS_PREFIX = "summary-links-"; - - public final Multimap linkMap = LinkedHashMultimap.create(); - /** - * The translation key for the name of this section. - */ - public final String name; - /** - * the classes to put on the link block <i> element. (may be null) - */ - public final String iconClasses; - private String html; - - public LinkBlock(String name, String iconClasses) { - this.name = name; - this.iconClasses = iconClasses; - } - - public String getName() throws JDOMException, IOException { - return name; - } - - public String getIconClasses() { - return iconClasses; - } - - public void put(LinkType type, Link link) { - final Collection links = this.linkMap.get(type); - Link other = null; - for (Link l : links) { - if (l.getHref().equalsIgnoreCase(link.getHref())) { - other = l; - break; - } - } - if (other != null) { - if (other.getText().trim().isEmpty()) { - this.linkMap.remove(type, other); - } else { - return; - } - } - this.linkMap.put(type, link); - } - - public Collection getLinks() { - return Collections2.transform(linkMap.asMap().entrySet(), new Function>, LinkBlockEntry>() { - @Nullable - @Override - public LinkBlockEntry apply(Map.Entry> input) { - return new LinkBlockEntry(input.getKey(), input.getValue()); - } - }); - } - - public String getHtml() { - return html; - } - - public void setHtml(String html) { - this.html = html; - } - - public static final class LinkBlockEntry { - private final LinkType type; - private final Collection links; - - public LinkBlockEntry(LinkType type, Collection links) { - this.type = type; - this.links = links; - } - - public LinkType getType() { - return this.type; - } - - public Collection getLinks() { - return this.links; - } - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/LinkType.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/LinkType.java deleted file mode 100644 index 571f686c07d3..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/LinkType.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.util; - -import org.fao.geonet.api.records.formatters.groovy.Functions; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.Objects; - -/** - * Represents the group name and icon of a type of links. IE Dataset, parent, children, etc... - * - * @author Jesse on 11/20/2014. - */ -public class LinkType { - /** - * The untranslated name of the link. - */ - public String name; - /** - * The direction of the relationship. Indicates if the current metadata is the parent, - * child,sibling of the related item. - *

- * In some cases this is not important (link linking to webpages), in those cases it can be - * null. - */ - public Direction relationDirection; - /** - * The url of the icon for this link group. This may be null. - */ - public String icon; - /** - * The classes to put on the <i> element - */ - public String iconClasses; - /** - * The title attribute to put on the icon elements (<i> if iconClasses != null and <img> - * if icon != null) - */ - public String iconTitle; - /** - * Raw HTML for the icon. - */ - public String iconHtml = ""; - - public LinkType() { - } - - public LinkType(@Nonnull String name, @Nullable Direction relationDirection, - @Nullable String icon, @Nullable String iconClasses) { - this(name, relationDirection, icon, iconClasses, null); - } - - public LinkType(@Nonnull String name, @Nullable Direction relationDirection, - @Nullable String icon, @Nullable String iconClasses, @Nullable String iconTitle) { - Objects.requireNonNull(name); - this.name = name; - this.relationDirection = relationDirection; - this.icon = icon; - this.iconClasses = iconClasses; - this.iconTitle = iconTitle; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - LinkType linkType = (LinkType) o; - return com.google.common.base.Objects.equal(name, linkType.name) && - com.google.common.base.Objects.equal(relationDirection, linkType.relationDirection); - } - - @Override - public int hashCode() { - return com.google.common.base.Objects.hashCode(name, relationDirection); - } - - public String getName(Functions functions) throws Exception { - return functions.translate(name); - } - - @Override - public String toString() { - return "LinkType{" + "dir='" + relationDirection + '\'' + "name='" + name + '\'' + '}'; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/NavBarItem.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/NavBarItem.java deleted file mode 100644 index 06612e01c845..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/NavBarItem.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.util; - -/** - * An Nav Bar item. - * - * @author Jesse on 12/1/2014. - */ -public class NavBarItem { - private String abbrName; - private String name, rel, href; - - public NavBarItem() { - // no op - } - - /** - * Constructor. - * - * @param name the translated full name of the group represented by this item. This will be - * displayed as a tool tip (see view-header.html) - * @param abbrName a shorter translated name to use in the display to keep the size of the items - * reasonable. - * @param rel the value of the rel attribute - */ - public NavBarItem(String name, String abbrName, String rel) { - this(name, abbrName, rel, ""); - } - - /** - * Constructor. - * - * @param name the translated full name of the group represented by this item. This will be - * displayed as a tool tip (see view-header.html) - * @param abbrName a shorter translated name to use in the display to keep the size of the items - * reasonable. - * @param rel the value of the rel attribute - * @param href the value of the href attribute - */ - public NavBarItem(String name, String abbrName, String rel, String href) { - this.name = name; - this.abbrName = abbrName; - if (abbrName == null || abbrName.isEmpty()) { - this.abbrName = name; - } - this.rel = rel; - this.href = href; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getRel() { - return rel; - } - - public void setRel(String rel) { - this.rel = rel; - } - - public String getAbbrName() { - return abbrName; - } - - public void setAbbrName(String abbrName) { - this.abbrName = abbrName; - } - - public String getHref() { - return href; - } - - public void setHref(String href) { - this.href = href; - } -} diff --git a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Summary.java b/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Summary.java deleted file mode 100644 index 9acb199e6100..000000000000 --- a/services/src/main/java/org/fao/geonet/api/records/formatters/groovy/util/Summary.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.util; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import org.fao.geonet.api.records.attachments.Store; -import org.fao.geonet.api.records.formatters.FormatType; -import org.fao.geonet.api.records.formatters.groovy.Environment; -import org.fao.geonet.api.records.formatters.groovy.Functions; -import org.fao.geonet.api.records.formatters.groovy.Handlers; -import org.fao.geonet.api.records.formatters.groovy.template.FileResult; -import org.fao.geonet.domain.MetadataResourceVisibility; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -/** - * Represents the summary of a metadata element. It is often the top section of a metadata view and - * summarizes the critical part of the metadata to most users. - *

- * The purpose of this class is to provide consistent way to display a summary of a metadata for all - * schemas. The formatter/view only needs to populate the fields of this class (or subclass) and - * the class can take care of presentation. - *

- * This implementation includes logo, thumbnail, title, abstract, navigation bar and the content - * (view). Any of the fields can be left with their default values and they will not be displayed - * in the Summary. - *

- * The data is rendered with the view-header.html template. - */ -public class Summary { - protected final Handlers handlers; - protected final Environment env; - protected final Functions functions; - public List links = Lists.newArrayList(); - public List associated = Lists.newArrayList(); - private String logo; - private List thumbnails = Lists.newArrayList(); - private String title = ""; - private String abstr = ""; - private List navBar = Lists.newArrayList(); - private List navBarOverflow = Lists.newArrayList(); - private String content = ""; - private boolean addCompleteNavItem = true; - private boolean addOverviewNavItem = true; - private String keywords = ""; - private String extent = ""; - private String formats = ""; - - public Summary(Handlers handlers, Environment env, Functions functions) throws Exception { - this.handlers = handlers; - this.env = env; - this.functions = functions; - Collection logo = env.getIndexInfo().get("_logo"); - if (logo != null && !logo.isEmpty()) { - this.logo = env.getLocalizedUrl() + "../.." + logo.iterator().next(); - } - } - - public FileResult getResult() throws Exception { - Map params = Maps.newHashMap(); - - params.put("logo", logo); - params.put("title", title != null ? title : ""); - params.put("pageTitle", title != null ? title.replace('"', '\'') : ""); - params.put("abstract", abstr); - params.put("thumbnail", thumbnailUrl()); - params.put("links", links); - params.put("associated", associated); - params.put("addOverviewNavItem", addOverviewNavItem); - params.put("navBar", navBar); - params.put("navBarOverflow", navBarOverflow); - params.put("showNavOverflow", !navBarOverflow.isEmpty()); - params.put("addCompleteNavItem", addCompleteNavItem); - params.put("content", content); - params.put("extents", extent != null ? extent : ""); - params.put("formats", formats != null ? formats : ""); - params.put("keywords", keywords != null ? keywords : ""); - params.put("isHTML", env.getFormatType() == FormatType.html); - params.put("isPDF", env.getFormatType() == FormatType.pdf || env.getFormatType() == FormatType.testpdf); - - return handlers.fileResult("html/view-header.html", params); - } - - String thumbnailUrl() { - String thumbnail = null; - for (String t : thumbnails) { - boolean isUrl = thumbnailIsUrl(t); - boolean isSmall = isSmallThumbnail(t); - // Preferred is large thumbnail that is a resource url: - if (!isUrl && resourceUrlExists(t) && !isSmall) { - thumbnail = resourceThumbnailUrl(t); - break; - } - // Next preference is a full sized thumbnail - if (isUrl) { - thumbnail = t; - } - // Last choice is the small thumbnail - if (thumbnail == null && resourceUrlExists(t)) { - thumbnail = resourceThumbnailUrl(t); - } - } - - if (thumbnail == null) { - thumbnail = ""; - } - - return thumbnail; - } - - private String resourceThumbnailUrl(String t) { - return env.getLocalizedUrl() + "resources.get?fname=" + t + "&access=public&id=" + env.getMetadataId(); - } - - private boolean isSmallThumbnail(String img) { - return img.matches(".*_s\\.[^.]+"); - } - - private boolean resourceUrlExists(String imgFile) { - final Store store = env.getBean("resourceStore", Store.class); - try { - return store.getResourceDescription(env.getContext(), env.getMetadataUUID(), MetadataResourceVisibility.PUBLIC, - imgFile, true) != null; - } catch (Exception e) { - return false; - } - } - - private boolean thumbnailIsUrl(String img) { - return img.startsWith("http://") || img.startsWith("https://"); - } - - public void setLogo(String logo) { - this.logo = logo; - } - - public void setThumbnails(List thumbnails) { - this.thumbnails = thumbnails; - } - - public void addThumbnail(String thumbnail) { - this.thumbnails.add(thumbnail); - } - - - public void setTitle(String title) { - this.title = title; - } - - public void setAbstr(String abstr) { - this.abstr = abstr; - } - - public void addNavBarItem(NavBarItem item) { - this.navBar.add(item); - } - - public void setNavBar(List navBar) { - this.navBar = navBar; - } - - public void addNavBarOverflow(NavBarItem item) { - this.navBarOverflow.add(item); - } - - public void setNavBarOverflow(List navBarOverflow) { - this.navBarOverflow = navBarOverflow; - } - - public void setContent(String content) { - this.content = content; - } - - public boolean isAddCompleteNavItem() { - return addCompleteNavItem; - } - - public void setAddCompleteNavItem(boolean addCompleteNavItem) { - this.addCompleteNavItem = addCompleteNavItem; - } - - public boolean isAddOverviewNavItem() { - return addOverviewNavItem; - } - - public void setAddOverviewNavItem(boolean addOverviewNavItem) { - this.addOverviewNavItem = addOverviewNavItem; - } - - public void setExtent(String extent) { - this.extent = extent; - } - - public void setKeywords(String keywords) { - this.keywords = keywords; - } - - public void setFormats(String formats) { - this.formats = formats; - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/AbstractFormatterTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/AbstractFormatterTest.java index 3598cbaf0588..7c201ebd10dc 100644 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/AbstractFormatterTest.java +++ b/services/src/test/java/org/fao/geonet/api/records/formatters/AbstractFormatterTest.java @@ -23,28 +23,13 @@ package org.fao.geonet.api.records.formatters; -import com.google.common.collect.Maps; import com.google.common.io.Files; - -import groovy.util.XmlSlurper; -import groovy.util.slurpersupport.GPathResult; - +import jeeves.server.context.ServiceContext; import org.fao.geonet.Constants; import org.fao.geonet.SystemInfo; import org.fao.geonet.TestFunction; import org.fao.geonet.api.records.formatters.cache.Key; -import org.fao.geonet.api.records.formatters.groovy.EnvironmentProxy; -import org.fao.geonet.api.records.formatters.groovy.Handler; -import org.fao.geonet.api.records.formatters.groovy.Handlers; -import org.fao.geonet.api.records.formatters.groovy.TransformationContext; -import org.fao.geonet.api.records.formatters.groovy.Transformer; -import org.fao.geonet.domain.ISODate; -import org.fao.geonet.domain.Metadata; -import org.fao.geonet.domain.MetadataDataInfo; -import org.fao.geonet.domain.MetadataHarvestInfo; -import org.fao.geonet.domain.MetadataSourceInfo; -import org.fao.geonet.domain.MetadataType; -import org.fao.geonet.domain.Pair; +import org.fao.geonet.domain.*; import org.fao.geonet.kernel.DataManager; import org.fao.geonet.kernel.SchemaManager; import org.fao.geonet.kernel.UpdateDatestamp; @@ -55,7 +40,6 @@ import org.fao.geonet.services.AbstractServiceIntegrationTest; import org.fao.geonet.utils.Xml; import org.jdom.Element; -import org.jdom.Namespace; import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; @@ -63,10 +47,6 @@ import org.springframework.web.context.request.ServletWebRequest; import java.io.File; -import java.util.Collections; -import java.util.Map; - -import jeeves.server.context.ServiceContext; import static com.google.common.xml.XmlEscapers.xmlContentEscaper; @@ -92,14 +72,6 @@ public abstract class AbstractFormatterTest extends AbstractServiceIntegrationTe @Autowired private IsoLanguagesMapper mapper; - public static GPathResult parseXml(String xmlString, Namespace... namespaces) throws Exception { - Map namespaceUriToPrefix = Maps.newHashMap(); - for (Namespace namespace : namespaces) { - namespaceUriToPrefix.put(namespace.getPrefix(), namespace.getURI()); - } - final XmlSlurper xmlSlurper = new XmlSlurper(false, false); - return xmlSlurper.parseText(xmlString).declareNamespace(namespaceUriToPrefix); - } @Before public void setUp() throws Exception { @@ -134,17 +106,6 @@ public boolean isHarvested() { protected abstract File getTestMetadataFile() throws Exception; - protected Handlers getHandlers(MockHttpServletRequest request, String formatterId) throws Exception { - final Pair formatterAndParams = getFormatterFormatterParamsPair(request, formatterId); - - if (formatterAndParams.one() instanceof GroovyFormatter) { - GroovyFormatter formatter = (GroovyFormatter) formatterAndParams.one(); - final Transformer transformer = formatter.findTransformer(formatterAndParams.two()); - return transformer.getHandlers(); - } else { - throw new AssertionError("This method only applies to groovy formatters"); - } - } protected Pair getFormatterFormatterParamsPair(MockHttpServletRequest request, String formatterId) throws Exception { final ServletWebRequest webRequest = new ServletWebRequest(request); @@ -177,21 +138,6 @@ private double round(double num) { return Math.round(num * 1000) / 1000; } - protected String executeHandler(MockHttpServletRequest request, String formatterId, GPathResult elem, Handler handler) throws Exception { - - final Pair formatterFormatterParamsPair = getFormatterFormatterParamsPair(request, formatterId); - try { - EnvironmentProxy.setCurrentEnvironment(formatterFormatterParamsPair.two()); - TransformationContext context = new TransformationContext(null, null, new EnvironmentProxy()); - context.setThreadLocal(); - StringBuilder result = new StringBuilder(); - handler.handle(context, Collections.singletonList(elem), result); - return result.toString(); - } finally { - EnvironmentProxy.clearContext(); - } - } - protected String escapeXmlText(String text) { return xmlContentEscaper().escape(text.replaceAll("\\s+", " ")).replaceAll("\\&", "&").replaceAll("\"", """); } diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/FormatterApiIntegrationTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/FormatterApiIntegrationTest.java index b0e4d9c7fe21..6899a268294e 100644 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/FormatterApiIntegrationTest.java +++ b/services/src/test/java/org/fao/geonet/api/records/formatters/FormatterApiIntegrationTest.java @@ -24,13 +24,11 @@ package org.fao.geonet.api.records.formatters; import com.google.common.collect.Lists; - -import org.apache.logging.log4j.Level; +import jeeves.config.springutil.JeevesDelegatingFilterProxy; +import jeeves.server.context.ServiceContext; import org.fao.geonet.AbstractCoreIntegrationTest; import org.fao.geonet.MockRequestFactoryGeonet; import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.groovy.EnvironmentProxy; -import org.fao.geonet.constants.Geonet; import org.fao.geonet.domain.Metadata; import org.fao.geonet.domain.MetadataType; import org.fao.geonet.kernel.DataManager; @@ -47,7 +45,6 @@ import org.fao.geonet.utils.MockXmlRequest; import org.fao.geonet.utils.Xml; import org.jdom.Element; -import org.jdom.JDOMException; import org.jdom.Namespace; import org.junit.Before; import org.junit.Ignore; @@ -61,29 +58,17 @@ import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletWebRequest; -import java.io.IOException; -import java.net.URISyntaxException; +import javax.servlet.ServletContext; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; -import java.util.List; import java.util.UUID; -import javax.servlet.ServletContext; - -import jeeves.config.springutil.JeevesDelegatingFilterProxy; -import jeeves.server.context.ServiceContext; - import static org.fao.geonet.api.records.formatters.FormatterWidth._100; import static org.fao.geonet.schema.iso19139.ISO19139Namespaces.GCO; import static org.fao.geonet.schema.iso19139.ISO19139Namespaces.GMD; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; @ContextConfiguration(inheritLocations = true, locations = "classpath:formatter-test-context.xml") public class FormatterApiIntegrationTest extends AbstractServiceIntegrationTest { @@ -140,65 +125,6 @@ public void setUp() throws Exception { } - @Test(expected = AssertionError.class) - public void testGroovyUseEnvDuringConfigStage() throws Exception { - MockHttpServletRequest r = new MockHttpServletRequest(); - r.getSession(); - final ServletWebRequest webRequest = new ServletWebRequest(r, new MockHttpServletResponse()); - final FormatterParams fparams = new FormatterParams(); - fparams.context = this.serviceContext; - fparams.webRequest = webRequest; - // make sure context is cleared - EnvironmentProxy.setCurrentEnvironment(fparams); - - - final String formatterName = "groovy-illegal-env-access-formatter"; - final URL testFormatterViewFile = FormatterApiIntegrationTest.class.getResource(formatterName + "/view.groovy"); - final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent(); - final Path formatterDir = this.dataDirectory.getFormatterDir(); - IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false); - final String functionsXslName = "functions.xsl"; - Files.deleteIfExists(formatterDir.resolve(functionsXslName)); - IO.copyDirectoryOrFile(testFormatter.getParent().resolve(functionsXslName), formatterDir.resolve(functionsXslName), false); - - formatService.exec("eng", "html", "" + id, null, formatterName, null, null, _100, webRequest); - } - - @Ignore - @Test - public void testLoggingNullPointerBug() throws Exception { - final org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger(Geonet.FORMATTER); - Level level = logger.getLevel(); - org.apache.logging.log4j.core.config.Configurator.setLevel(logger,Level.ALL); - try { - MockHttpServletRequest webRequest = new MockHttpServletRequest(); - webRequest.getSession(); - final ServletWebRequest request = new ServletWebRequest(webRequest, new MockHttpServletResponse()); - final FormatterParams fparams = new FormatterParams(); - fparams.context = this.serviceContext; - fparams.webRequest = request; - // make sure context is cleared - EnvironmentProxy.setCurrentEnvironment(fparams); - - - final String formatterName = "logging-null-pointer"; - final URL testFormatterViewFile = FormatterApiIntegrationTest.class.getResource(formatterName + "/view.groovy"); - final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent(); - final Path formatterDir = this.dataDirectory.getFormatterDir(); - IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false); - final String functionsXslName = "functions.xsl"; - Files.deleteIfExists(formatterDir.resolve(functionsXslName)); - IO.copyDirectoryOrFile(testFormatter.getParent().resolve(functionsXslName), formatterDir.resolve(functionsXslName), false); - - - formatService.exec("eng", "html", "" + id, null, formatterName, null, null, _100, request); - - // no Error is success - } finally { - org.apache.logging.log4j.core.config.Configurator.setLevel(logger,level); - } - } - // TODOES @Test @Ignore @@ -340,99 +266,4 @@ public void testXmlFormatRelativeUrl() throws Exception { assertTrue(view.contains("KML (1)")); assertTrue(view.contains("Format")); } - - @Ignore - @Test - public void testExecGroovy() throws Exception { - final String formatterName = configureGroovyTestFormatter(); - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession(); - request.addParameter("h2IdentInfo", "true"); - - final MockHttpServletResponse response = new MockHttpServletResponse(); - formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100, new ServletWebRequest(request, response)); - final String viewString = response.getContentAsString(); -// com.google.common.io.Files.write(viewString, new File("e:/tmp/view.html"), Constants.CHARSET); - - final Element view = Xml.loadString(viewString, false); - assertEquals("html", view.getName()); - assertNotNull("body", view.getChild("body")); - - // Check that the "handlers.add 'gmd:abstract', { el ->" correctly applied - assertElement(view, "body//p[@class = 'abstract']/span[@class='label']", "Abstract", 1); - assertElement(view, "body//p[@class = 'abstract']/span[@class='value']", "Abstract {uuid}", 1); - - // Check that the "handlers.add ~/...:title/, { el ->" correctly applied - assertElement(view, "body//p[@class = 'title']/span[@class='label']", "Title", 1); - assertElement(view, "body//p[@class = 'title']/span[@class='value']", "Title", 1); - - // Check that the "handlers.withPath ~/[^>]+>gmd:identificationInfo>.*extent/, Iso19139Functions.&handleExtent" correctly applied - assertElement(view, "body//p[@class = 'formatter']", "fromFormatterGroovy", 1); - - // Check that the "handlers.withPath ~/[^>]+>gmd:identificationInfo>.*extent/, Iso19139Functions.&handleExtent" correctly applied - assertElement(view, "body//p[@class = 'shared']", "fromSharedFunctions", 1); - - - // Check that the "handlers.add ~/...:title/, { el ->" correctly applied - assertElement(view, "body//p[@class = 'code']/span[@class='label']", "Unique resource identifier", 1); - assertElement(view, "body//p[@class = 'code']/span[@class='value']", "WGS 1984", 1); - - // Check that the handlers.add 'gmd:CI_OnlineResource', { el -> handler is applied - assertElement(view, "body//p[@class = 'online-resource']/h3", "OnLine resource", 1); - assertElement(view, "body//p[@class = 'online-resource']/div/strong", "REPOM", 1); - assertElement(view, "body//p[@class = 'online-resource']/div[@class='desc']", "", 1); - assertElement(view, "body//p[@class = 'online-resource']/div[@class='linkage']/span[@class='label']", "URL:", 1); - assertElement(view, "body//p[@class = 'online-resource']/div[@class='linkage']/span[@class='value']", "http://services.sandre.eaufrance.fr/geo/ouvrage", 1); - - // Check that the handler: - // handlers.add select: {el -> el.name() == 'gmd:identificationInfo' && f.param('h2IdentInfo').toBool()}, - // processChildren: true, { el, childData -> - // was applied - assertElement(view, "*//div[@class = 'identificationInfo']/h2", "Data identification", 1); - List identificationElements = (List) Xml.selectNodes(view, "*//div[@class = 'identificationInfo']/p"); - assertEquals(viewString, 4, identificationElements.size()); - assertEquals(viewString, "abstract", identificationElements.get(0).getAttributeValue("class")); - assertEquals(viewString, "shared", identificationElements.get(1).getAttributeValue("class")); - assertEquals(viewString, "block", identificationElements.get(2).getAttributeValue("class")); - assertEquals(viewString, "block", identificationElements.get(3).getAttributeValue("class")); - assertEquals(viewString, "block", identificationElements.get(3).getAttributeValue("class")); - - // Verify that handler - // handlers.add name: 'codelist handler', select: isoHandlers.matchers.isCodeListEl, isoHandlers.isoCodeListEl - // is handled - assertElement(view, "body//span[@class = 'fileId']", this.uuid, 1); - assertElement(view, "body//span[@class = 'creatorTranslated']", "Creator", 1); - - assertElement(view, "body//span[@class = 'extents']", "2", 1); - - assertNull(Xml.selectElement(view, "body//h1[text() = 'Reference System Information']")); - } - - private String configureGroovyTestFormatter() throws URISyntaxException, IOException { - final String formatterName = "groovy-test-formatter"; - final URL testFormatterViewFile = FormatterApiIntegrationTest.class.getResource(formatterName + "/view.groovy"); - final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent(); - final Path formatterDir = this.dataDirectory.getFormatterDir(); - IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false); - final String groovySharedClasses = "groovy"; - IO.copyDirectoryOrFile(testFormatter.getParent().resolve(groovySharedClasses), formatterDir.resolve(groovySharedClasses), false); - - - final Path iso19139ConfigProperties = this.schemaManager.getSchemaDir("iso19139").resolve("formatter/config.properties"); - Files.write(iso19139ConfigProperties, "dependsOn=dublin-core".getBytes("UTF-8")); - - final Path dublinCoreSchemaDir = this.schemaManager.getSchemaDir("dublin-core").resolve("formatter/groovy"); - Files.createDirectories(dublinCoreSchemaDir); - IO.copyDirectoryOrFile(IO.toPath(FormatterApiIntegrationTest.class.getResource(formatterName + "/dublin-core-groovy").toURI()), - dublinCoreSchemaDir.resolve("DCFunctions.groovy"), false); - return formatterName; - } - - private void assertElement(Element view, String onlineResourceHeaderXpath, String expected, int numberOfElements) throws JDOMException { - assertEquals(Xml.getString(view), numberOfElements, Xml.selectNodes(view, onlineResourceHeaderXpath).size()); - assertEqualsText(expected, view, onlineResourceHeaderXpath); - } - - } diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/ResourceTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/ResourceTest.java index 73fdb3764001..b4b5adb82486 100644 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/ResourceTest.java +++ b/services/src/test/java/org/fao/geonet/api/records/formatters/ResourceTest.java @@ -63,13 +63,9 @@ public void testExec() throws Exception { assertCorrectExec("test.xml", 200, "application/xml"); assertCorrectExec("test.json", 200, "application/json"); assertCorrectExec("testyxz", 200, "application/octet-stream"); - assertCorrectExec("view.groovy", 200, "text/x-groovy-source,groovy"); assertCorrectExec("test.xsl", 200, "application/xslt+xml"); assertCorrectExec("test.xslt", 200, "application/xslt+xml"); assertCorrectExec("nosuchfile", 404, null); - assertCorrectExec("../xml_view/view.groovy", 403, null); - - } protected Path getFile(String fileName) throws URISyntaxException { diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/SchemaLocalizationsIntegrationTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/SchemaLocalizationsIntegrationTest.java index 8d30edaa2d34..b7a762a612ea 100644 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/SchemaLocalizationsIntegrationTest.java +++ b/services/src/test/java/org/fao/geonet/api/records/formatters/SchemaLocalizationsIntegrationTest.java @@ -23,7 +23,7 @@ package org.fao.geonet.api.records.formatters; -import org.fao.geonet.api.records.formatters.groovy.CurrentLanguageHolder; +import org.fao.geonet.api.records.formatters.CurrentLanguageHolder; import org.fao.geonet.languages.IsoLanguagesMapper; import org.fao.geonet.services.AbstractServiceIntegrationTest; import org.junit.Test; diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/SchemaLocalizationsTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/SchemaLocalizationsTest.java index b839159fdc25..c48876b7ad6c 100644 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/SchemaLocalizationsTest.java +++ b/services/src/test/java/org/fao/geonet/api/records/formatters/SchemaLocalizationsTest.java @@ -24,11 +24,7 @@ package org.fao.geonet.api.records.formatters; import com.google.common.collect.Maps; - -import groovy.util.XmlSlurper; -import groovy.util.slurpersupport.GPathResult; - -import org.fao.geonet.api.records.formatters.groovy.CurrentLanguageHolder; +import jeeves.server.dispatchers.guiservices.XmlFile; import org.fao.geonet.domain.IsoLanguage; import org.fao.geonet.kernel.SchemaManager; import org.fao.geonet.repository.IsoLanguageRepository; @@ -44,8 +40,6 @@ import java.util.Collection; import java.util.Map; -import jeeves.server.dispatchers.guiservices.XmlFile; - import static org.fao.geonet.api.records.formatters.SchemaLocalizations.LANG_CODELIST_NS; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -157,24 +151,7 @@ public void testLabel() throws Exception { assertEquals("Element One No Parent", localizations.nodeLabel("elem1", null)); assertEquals("Desc Element One No Parent", localizations.nodeDesc("elem1", null)); assertEquals("Desc Element One No Parent", localizations.nodeDesc("elem1", "random parent")); - - GPathResult gPathResult = new XmlSlurper().parseText("hi"); - assertEquals("Element One No Parent", localizations.nodeLabel(gPathResult)); - assertEquals("Desc Element One No Parent", localizations.nodeDesc(gPathResult)); - - gPathResult = new XmlSlurper().parseText("hi"); - assertEquals("Element One", localizations.nodeLabel((GPathResult) gPathResult.children().getAt(0))); - assertEquals("Desc Element One", localizations.nodeDesc((GPathResult) gPathResult.children().getAt(0))); - - - gPathResult = new XmlSlurper().parseText("hi"); - assertEquals("Element One No Parent", localizations.nodeLabel((GPathResult) gPathResult.children().getAt(0))); - assertEquals("Desc Element One No Parent", localizations.nodeDesc((GPathResult) gPathResult.children().getAt(0))); - - assertEquals("Desc Element Two", localizations.nodeDesc("elem2", "random parent")); - - } @Test @@ -183,9 +160,6 @@ public void testCodeListValue() throws Exception { assertEquals("Code Three", localizations.codelistValueLabel("http://yaya.com#codelist2", "code1")); assertEquals("Desc Code One", localizations.codelistValueDesc("http://yaya.com#codelist1", "code1")); assertEquals("Desc Code Three", localizations.codelistValueDesc("http://yaya.com#codelist2", "code1")); - final GPathResult gPathResult = new XmlSlurper().parseText(""); - assertEquals("Code One", localizations.codelistValueLabel(gPathResult)); - assertEquals("Desc Code One", localizations.codelistValueDesc(gPathResult)); } @Test diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/XmlViewFormatterTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/XmlViewFormatterTest.java deleted file mode 100644 index eee00db71a9a..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/XmlViewFormatterTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters; - -import com.google.common.collect.Lists; - -import org.fao.geonet.api.records.formatters.groovy.Environment; -import org.fao.geonet.api.records.formatters.groovy.EnvironmentImpl; -import org.fao.geonet.api.records.formatters.groovy.Functions; -import org.fao.geonet.kernel.SchemaManager; -import org.fao.geonet.languages.IsoLanguagesMapper; -import org.fao.geonet.repository.IsoLanguageRepository; -import org.fao.geonet.utils.Xml; -import org.jdom.Content; -import org.jdom.Element; -import org.jdom.Text; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.web.context.request.ServletWebRequest; - -import java.io.File; -import java.util.List; - -import static org.fao.geonet.api.records.formatters.FormatterWidth._100; - -/** - * @author Jesse on 10/17/2014. - */ -public class XmlViewFormatterTest extends AbstractFormatterTest { - - @Autowired - private IsoLanguagesMapper mapper; - @Autowired - private IsoLanguageRepository langRepo; - @Autowired - private SchemaManager schemaManager; - - @Test - @SuppressWarnings("unchecked") - public void testBasicFormat() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.getSession(); - request.addParameter("html", "true"); - - final String formatterId = "xml_view"; - FormatterParams fparams = getFormatterFormatterParamsPair - (request, formatterId).two(); - Environment env = new EnvironmentImpl(fparams, mapper); - final Functions functions = new Functions(fparams, env); - -// measureFormatterPerformance(request, formatterId); - - final MockHttpServletResponse response = new MockHttpServletResponse(); - formatService.exec("eng", "html", "" + id, null, formatterId, "true", false, _100, new ServletWebRequest(request, response)); - final String view = response.getContentAsString(); -// Files.write(view, new File("e:/tmp/view.html"), Constants.CHARSET); - - final Element xmlEl = Xml.loadString(xml, false); - final List text = Lists.newArrayList(Xml.selectNodes(xmlEl, "*//node()/text()")); - - StringBuilder missingStrings = new StringBuilder(); - for (Object t : text) { - final String path; - final String requiredText; - if (t instanceof Text) { - requiredText = ((Text) t).getTextTrim(); - path = getXPath((Content) t).trim(); - } else { - throw new AssertionError(t.getClass() + " is not handled"); - } - if (!requiredText.isEmpty() && !view.contains(requiredText)) { - missingStrings.append("\n").append(path).append(" -> ").append(requiredText); - } - } - - if (missingStrings.length() > 0) { - throw new AssertionError("The following text elements are missing from the view:" + missingStrings); - } - } - - private String getXPath(Content el) { - String path = ""; - if (el.getParentElement() != null) { - path = getXPath(el.getParentElement()); - } - if (el instanceof Element) { - return path + " > " + ((Element) el).getQualifiedName(); - } else { - return path + " > " + el.getClass().getSimpleName(); - } - } - - @Override - protected File getTestMetadataFile() throws Exception { - return new File(XmlViewFormatterTest.class.getResource("xml_view/test.xml").toURI()); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/FunctionsTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/FunctionsTest.java deleted file mode 100644 index 878acaff1ab6..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/FunctionsTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import com.google.common.collect.Maps; -import com.google.common.io.Resources; - -import groovy.util.slurpersupport.GPathResult; - -import org.fao.geonet.AbstractCoreIntegrationTest; -import org.fao.geonet.Constants; -import org.fao.geonet.api.records.formatters.AbstractFormatterTest; -import org.fao.geonet.api.records.formatters.ConfigFile; -import org.fao.geonet.api.records.formatters.FormatterApi; -import org.fao.geonet.api.records.formatters.FormatterParams; -import org.fao.geonet.domain.IsoLanguage; -import org.fao.geonet.kernel.GeonetworkDataDirectory; -import org.fao.geonet.kernel.SchemaManager; -import org.fao.geonet.languages.IsoLanguagesMapper; -import org.fao.geonet.repository.IsoLanguageRepository; -import org.fao.geonet.utils.IO; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.context.ConfigurableApplicationContext; - -import java.io.IOException; -import java.net.URL; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.Iterator; - -import jeeves.server.context.ServiceContext; -import jeeves.server.dispatchers.guiservices.XmlCacheManager; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class FunctionsTest { - private final String schema = "iso19139"; - private FormatterParams fparams; - private Functions functions; - private Path schemaDir; - - private static IsoLanguage isoLang(String engTranslation) { - final IsoLanguage isoLanguage = new IsoLanguage(); - isoLanguage.getLabelTranslations().put("eng", engTranslation); - return isoLanguage; - } - - @Before - public void setUp() throws Exception { - - final IsoLanguageRepository repository = Mockito.mock(IsoLanguageRepository.class); - Mockito.when(repository.findAllByCode("ger")).thenReturn(Arrays.asList(isoLang("German"))); - Mockito.when(repository.findAllByCode("eng")).thenReturn(Arrays.asList(isoLang("English"))); - Mockito.when(repository.findAllByShortCode("en")).thenReturn(Arrays.asList(isoLang("English"))); - Mockito.when(repository.findAllByShortCode("de")).thenReturn(Arrays.asList(isoLang("German"))); - - this.schemaDir = IO.toPath(FunctionsTest.class.getResource("translation-test/schema-dir/formatter/config.properties").toURI()) - .getParent().getParent(); - SchemaManager schemaManager = Mockito.mock(SchemaManager.class); - Mockito.when(schemaManager.getSchemaDir("parent-schema")).thenReturn(schemaDir.getParent().resolve("parent-schema")); - - final ConfigurableApplicationContext appContext = Mockito.mock(ConfigurableApplicationContext.class); - Mockito.when(appContext.getBean(SchemaManager.class)).thenReturn(schemaManager); - Mockito.when(appContext.getBean(IsoLanguageRepository.class)).thenReturn(repository); - GeonetworkDataDirectory dataDir = Mockito.mock(GeonetworkDataDirectory.class); - Mockito.when(dataDir.getWebappDir()).thenReturn(AbstractCoreIntegrationTest.getWebappDir(FunctionsTest.class)); - Mockito.when(dataDir.getSystemDataDir()).thenReturn(AbstractCoreIntegrationTest.getWebappDir(FunctionsTest.class)); - Mockito.when(appContext.getBean(GeonetworkDataDirectory.class)).thenReturn(dataDir); - Mockito.when(appContext.getBean(XmlCacheManager.class)).thenReturn(new XmlCacheManager()); - - final IsoLanguagesMapper languagesMapper = Mockito.mock(IsoLanguagesMapper.class); - Mockito.when(languagesMapper.iso639_1_to_iso639_2("en")).thenReturn("eng"); - Mockito.when(languagesMapper.iso639_1_to_iso639_2("en", "en")).thenReturn("eng"); - Mockito.when(appContext.getBean(IsoLanguagesMapper.class)).thenReturn(languagesMapper); - - fparams = new FormatterParams() { - @Override - public boolean isDevMode() { - return false; - } - }; - fparams.schema = schema; - fparams.context = new ServiceContext("test", appContext, Maps.newHashMap(), null); - fparams.context.setAsThreadLocal(); - fparams.context.setLanguage("eng"); - fparams.config = new ConfigFile(IO.toPath("."), false, IO.toPath(".").getParent()); - - fparams.schema = "schema"; - fparams.schemaDir = schemaDir; - fparams.formatDir = schemaDir.getParent().resolve("formatter-dir"); - - fparams.format = new FormatterApi() { - @Override - protected boolean isDevMode(ServiceContext context) { - return false; - } - }; - - Environment env = Mockito.mock(Environment.class); - Mockito.when(env.getLang3()).thenReturn("eng"); - Mockito.when(env.getLang2()).thenReturn("#EN"); - - functions = new Functions(fparams, env) { - @Override - protected ConfigFile getConfigFile(SchemaManager schemaManager, String schema) throws IOException { - return Mockito.mock(ConfigFile.class); - } - }; - } - - @Test - public void testTranslate() throws Exception { - - assertEquals("FormatterStrings", functions.translate("formatter-strings")); - final String inBoth = functions.translate("in-both"); - assertTrue(inBoth, inBoth.equals("In Both strings") || inBoth.equals("In Both other-strings")); - assertEquals("In Both other-strings", functions.translate("in-both", "other-strings")); - assertEquals("In Both strings", functions.translate("in-both", "strings")); - assertEquals("Schema Normal Strings XML", functions.translate("schema-strings")); - assertEquals("Parent Schema Normal Strings XML", functions.translate("parent-schema-strings")); - assertEquals("Parent Schema More Strings XML", functions.translate("parent-schema-more")); - final String inBothParent = functions.translate("in-both-parent"); - assertTrue(inBothParent.equals("In Both Parent Strings XML") || inBothParent.equals("In Both Parent More Strings XML")); - assertEquals("In Both Parent Strings XML", functions.translate("in-both-parent", "strings")); - assertEquals("In Both Parent More Strings XML", functions.translate("in-both-parent", "more-strings")); - assertEquals("This String is here for testing don't delete", functions.translate("testString")); - } - - @Test - public void testTranslateNoLocDir() throws Exception { - fparams.formatDir = schemaDir.getParent().resolve("doesnotexist"); - - // no exception? good - } - - @Test - public void testGetXPath() throws Exception { - final URL resource = AbstractCoreIntegrationTest.class.getResource("kernel/valid-metadata.iso19139.xml"); - final String sampleMetadataXml = Resources.toString(resource, Constants.CHARSET); - final GPathResult xml = AbstractFormatterTest.parseXml(sampleMetadataXml); - - GPathResult polygon = null, bbox = null; - final Iterator iterator = xml.depthFirst(); - while (iterator.hasNext()) { - Object elem = iterator.next(); - if (elem instanceof GPathResult) { - GPathResult result = (GPathResult) elem; - if (result.name().equals("gmd:EX_BoundingPolygon")) { - polygon = result; - } - if (result.name().equals("gmd:EX_GeographicBoundingBox")) { - bbox = result; - } - } - } - - assertEquals("gmd:identificationInfo/gmd:MD_DataIdentification/gmd:extent[2]/gmd:EX_Extent/gmd:geographicElement[2]/gmd:EX_GeographicBoundingBox", functions.getXPathFrom(bbox)); - assertEquals("gmd:identificationInfo/gmd:MD_DataIdentification/gmd:extent[2]/gmd:EX_Extent/gmd:geographicElement[1]/gmd:EX_BoundingPolygon", functions.getXPathFrom(polygon)); - - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/HandlersTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/HandlersTest.java deleted file mode 100644 index f324759b09bc..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/HandlersTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy; - -import com.google.common.collect.Lists; - -import groovy.lang.Closure; - -import org.codehaus.groovy.runtime.GStringImpl; -import org.fao.geonet.api.records.formatters.FormatterParams; -import org.junit.Assert; -import org.junit.Test; - -import java.util.Arrays; - -public class HandlersTest { - - @Test - public void testRoots() throws Exception { - final Handlers handlers = new Handlers(new FormatterParams(), null, null, null); - handlers.roots("root1", "root2"); - - Assert.assertArrayEquals(new String[]{"root1", "root2"}, sort(handlers.getRoots().toArray())); - - handlers.root("newroot"); - Assert.assertArrayEquals(new String[]{"newroot", "root1", "root2"}, sort(handlers.getRoots().toArray())); - - handlers.root(new GStringImpl(new Object[0], new String[]{"newroot2"})); - Assert.assertArrayEquals(new String[]{"newroot", "newroot2", "root1", "root2"}, sort(handlers.getRoots().toArray())); - - handlers.roots("root1", new GStringImpl(new Object[0], new String[]{"root2"})); - Assert.assertArrayEquals(new Object[]{"root1", "root2"}, sort(handlers.getRoots().toArray())); - - handlers.roots(new Closure(handlers) { - @Override - public Object call() { - return Lists.newArrayList("cr1", "cr2"); - } - - @Override - public Object call(Object arguments) { - return call(); - } - }); - Assert.assertArrayEquals(new String[]{"cr1", "cr2"}, sort(handlers.getRoots().toArray())); - - handlers.roots(new Closure(handlers) { - @Override - public Object call() { - return Lists.newArrayList(new GStringImpl(new Object[0], new String[]{"gr1"})); - } - - @Override - public Object call(Object arguments) { - return call(); - } - }); - Assert.assertArrayEquals(new String[]{"gr1"}, sort(handlers.getRoots().toArray())); - } - - private Object[] sort(Object[] objects) { - Arrays.sort(objects); - return objects; - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/AbstractTemplateParserTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/AbstractTemplateParserTest.java deleted file mode 100644 index ff65c008e37a..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/AbstractTemplateParserTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Lists; - -import org.fao.geonet.SystemInfo; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public abstract class AbstractTemplateParserTest { - - public static void assertCorrectRender(TNode parseTree, Map model, String expected) throws IOException { - final ByteArrayOutputStream result = new ByteArrayOutputStream(); - TRenderContext context = new TRenderContext(result, model); - - parseTree.render(context); - - assertEquals(expected + "\n" + result, expected.replaceAll("\\n|\\r|\\s+", ""), result.toString().replaceAll("\\n|\\r|\\s+", "")); - } - - public static TemplateParser createTestParser(String systemInfoStage) throws IllegalAccessException, InstantiationException { - SystemInfo info = SystemInfo.createForTesting(systemInfoStage); - final TemplateParser parser = new TemplateParser(); - final TextContentParser contentParser = TextContentParserTest.createTestTextContentParser(); - parser.textContentParser = contentParser; - parser.tnodeFactories = Lists.newArrayList( - new TNodeFactoryIf(info, contentParser), new TNodeFactoryRepeat(info, contentParser), new TNodeFactoryTranslate(info, contentParser), - new TNodeFactoryInclude(info, contentParser), new TNodeFactoryTransclude(info, contentParser)); - return parser; - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterCapitalizeTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterCapitalizeTest.java deleted file mode 100644 index b37cde1047e9..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterCapitalizeTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class FilterCapitalizeTest { - - @Test - public void testProcess() throws Exception { - assertEquals("It Is A Title", new FilterCapitalize().process(null, "it is a title")); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlAttrsTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlAttrsTest.java deleted file mode 100644 index 2e55cb99efbe..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlAttrsTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class FilterEscapeXmlAttrsTest { - - @Test - public void testProcess() throws Exception { - assertEquals("&<>", new FilterEscapeXmlAttrs().process(null, "&<>")); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlContentTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlContentTest.java deleted file mode 100644 index 82aae19e625b..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterEscapeXmlContentTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class FilterEscapeXmlContentTest { - - @Test - public void testProcess() throws Exception { - assertEquals(">&<", new FilterEscapeXmlContent().process(null, ">&<")); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLowerCaseTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLowerCaseTest.java deleted file mode 100644 index f008a9507721..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterLowerCaseTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class FilterLowerCaseTest { - - @Test - public void testProcess() throws Exception { - assertEquals("word", new FilterLowerCase().process(null, "WOrD")); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUUIDTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUUIDTest.java deleted file mode 100644 index bfd97f34d97d..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUUIDTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Maps; - -import org.fao.geonet.SystemInfo; -import org.fao.geonet.utils.IO; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.net.URL; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * Test the UUID template filters - * - * @author Jesse on 4/27/2015. - */ -public class FilterUUIDTest extends AbstractTemplateParserTest { - - @Test - public void testProcess() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TemplateParserTest.class.getResource("uuid-filter-template.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - Map model = Maps.newHashMap(); - final ByteArrayOutputStream result = new ByteArrayOutputStream(); - TRenderContext context = new TRenderContext(result, model); - - parseTree.render(context); - - String uuid = FilterGenerateUUID.LAST_UUID.get(); - assertNotNull(uuid); - String expected = String.format("

", uuid, uuid); - - assertEquals(expected, result.toString().replaceAll("\n*\r*", "")); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUpperCaseTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUpperCaseTest.java deleted file mode 100644 index 1b85e5126d25..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/FilterUpperCaseTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class FilterUpperCaseTest { - - @Test - public void testProcess() throws Exception { - assertEquals("WORD", new FilterUpperCase().process(null, "woRd")); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIfTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIfTest.java deleted file mode 100644 index 9ea9199ae859..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIfTest.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import groovy.util.XmlSlurper; -import groovy.util.slurpersupport.GPathResult; - -import org.fao.geonet.ApplicationContextHolder; -import org.fao.geonet.SystemInfo; -import org.fao.geonet.utils.IO; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.context.ConfigurableApplicationContext; - -import java.io.ByteArrayOutputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class TNodeIfTest extends AbstractTemplateParserTest { - SystemInfo info = SystemInfo.createForTesting(SystemInfo.STAGE_TESTING); - - @Test - public void testParseIfDirective() throws Exception { - ConfigurableApplicationContext context = Mockito.mock(ConfigurableApplicationContext.class); - ApplicationContextHolder.set(context); - Mockito.when(context.getBean(SystemInfo.class)).thenReturn(info); - - final TemplateParser parser = createTestParser(SystemInfo.STAGE_PRODUCTION); - final URL url = AbstractTemplateParserTest.class.getResource("non-empty-template.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - model.put("title", "Title"); - model.put("lang", "en"); - model.put("body", "y"); - model.put("div", "Div Data"); - - String expected = "Title" - + "
Div Data
"; - assertCorrectRender(parseTree, model, expected); - - model.remove("title"); - expected = "
Div Data
"; - assertCorrectRender(parseTree, model, expected); - - model.remove("body"); - expected = ""; - assertCorrectRender(parseTree, model, expected); - - model.put("title", "Title"); - expected = "Title"; - assertCorrectRender(parseTree, model, expected); - - model.put("body", "y"); - model.remove("div"); - expected = "Title"; - assertCorrectRender(parseTree, model, expected); - - model.clear(); - final ArrayList list = Lists.newArrayList(1, "2"); - model.put("title", list); - - expected = "" + list + ""; - assertCorrectRender(parseTree, model, expected); - - final GPathResult gPathResult = new XmlSlurper().parseText("gpath"); - model.put("title", gPathResult); - expected = "" + gPathResult + ""; - assertCorrectRender(parseTree, model, expected); - } - - @Test - public void testCommentWhenFalse() throws Exception { - TNodeIf ifNode = new TNodeIf(info, TextContentParserTest.createTestTextContentParser(), "div", TNode.EMPTY_ATTRIBUTES, "item", false); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ifNode.render(new TRenderContext(out, Collections.emptyMap())); - assertEquals("", out.toString()); - - out = new ByteArrayOutputStream(); - ifNode.render(new TRenderContext(out, Collections.singletonMap("item", false))); - assertEquals("", out.toString()); - - out = new ByteArrayOutputStream(); - ifNode.render(new TRenderContext(out, Collections.singletonMap("item", Collections.emptyList()))); - assertEquals("", out.toString()); - - out = new ByteArrayOutputStream(); - ifNode.render(new TRenderContext(out, Collections.singletonMap("item", Collections.emptyMap()))); - assertEquals("", out.toString()); - - out = new ByteArrayOutputStream(); - ifNode.render(new TRenderContext(out, Collections.singletonMap("item", 0))); - assertEquals("", out.toString()); - - out = new ByteArrayOutputStream(); - ifNode.render(new TRenderContext(out, Collections.singletonMap("item", 0.0))); - assertEquals("", out.toString()); - - out = new ByteArrayOutputStream(); - ifNode.render(new TRenderContext(out, Collections.singletonMap("item", ""))); - assertEquals("", out.toString()); - - - ifNode = new TNodeIf(info, TextContentParserTest.createTestTextContentParser(), "div", TNode.EMPTY_ATTRIBUTES, "!item", false); - - out = new ByteArrayOutputStream(); - ifNode.render(new TRenderContext(out, Collections.singletonMap("item", "blarg"))); - assertEquals("", out.toString()); - } - - @Test - public void testEquals() throws Exception { - TNodeIf div = new TNodeIf(null, TextContentParserTest.createTestTextContentParser(), "div", TNode.EMPTY_ATTRIBUTES, "{{label}} == 'one'", false); - - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - assertFalse(div.canRender(new TRenderContext(out, Collections.singletonMap("label", "one"))).isPresent()); - assertTrue(div.canRender(new TRenderContext(out, Collections.singletonMap("label", "two"))).isPresent()); - assertTrue(div.canRender(new TRenderContext(out, Collections.emptyMap())).isPresent()); - - div = new TNodeIf(null, TextContentParserTest.createTestTextContentParser(), "div", TNode.EMPTY_ATTRIBUTES, "'one' == {{label}}", false); - - assertFalse(div.canRender(new TRenderContext(out, Collections.singletonMap("label", "one"))).isPresent()); - assertTrue(div.canRender(new TRenderContext(out, Collections.singletonMap("label", "two"))).isPresent()); - assertTrue(div.canRender(new TRenderContext(out, Collections.emptyMap())).isPresent()); - - - } - - @Test - public void testIsTruthy() throws Exception { - assertNull(TNodeIf.isTruthy("1")); - assertNull(TNodeIf.isTruthy("hi")); - assertNull(TNodeIf.isTruthy(true)); - assertNull(TNodeIf.isTruthy(1.0)); - assertNull(TNodeIf.isTruthy(0.5f)); - assertNull(TNodeIf.isTruthy(0.5)); - assertNull(TNodeIf.isTruthy(1)); - assertNull(TNodeIf.isTruthy(new String[]{"1"})); - assertNull(TNodeIf.isTruthy(Lists.newArrayList(2))); - assertNull(TNodeIf.isTruthy(Lists.newArrayList(2))); - assertNull(TNodeIf.isTruthy(Lists.newArrayList(2).iterator())); - assertNull(TNodeIf.isTruthy(Collections.singletonMap("key", 2))); - - - assertNotNull(TNodeIf.isTruthy(Collections.emptyMap())); - assertNotNull(TNodeIf.isTruthy(Collections.emptyEnumeration())); - assertNotNull(TNodeIf.isTruthy(Collections.emptyList())); - assertNotNull(TNodeIf.isTruthy(Collections.emptyList().iterator())); - assertNotNull(TNodeIf.isTruthy(0)); - assertNotNull(TNodeIf.isTruthy(0.000000000000000001)); - assertNotNull(TNodeIf.isTruthy(0.000000000000000001f)); - assertNotNull(TNodeIf.isTruthy(false)); - assertNotNull(TNodeIf.isTruthy("")); - assertNotNull(TNodeIf.isTruthy(null)); - } - - @Test - public void testNot() throws Exception { - TNodeIf not = new TNodeIf(info, TextContentParserTest.createTestTextContentParser(), "Node", TNode.EMPTY_ATTRIBUTES, "!expr", false); - - TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), Collections.singletonMap("expr", true)); - assertTrue(not.canRender(context).isPresent()); - - context = new TRenderContext(new ByteArrayOutputStream(), Collections.singletonMap("expr", false)); - assertFalse(not.canRender(context).isPresent()); - - TNodeIf normal = new TNodeIf(info, TextContentParserTest.createTestTextContentParser(), "Node", TNode.EMPTY_ATTRIBUTES, "expr", false); - - context = new TRenderContext(new ByteArrayOutputStream(), Collections.singletonMap("expr", false)); - assertTrue(normal.canRender(context).isPresent()); - - context = new TRenderContext(new ByteArrayOutputStream(), Collections.singletonMap("expr", true)); - assertFalse(normal.canRender(context).isPresent()); - - } - - - @Test - public void testOnlyChildren() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_PRODUCTION); - final URL url = AbstractTemplateParserTest.class.getResource("if-children-only.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - model.put("title", "Title"); - - String expected = "\n" - + " Title\n" - + ""; - assertCorrectRender(parseTree, model, expected); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIncludeTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIncludeTest.java deleted file mode 100644 index 949710d9fef3..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeIncludeTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Maps; - -import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.groovy.Environment; -import org.fao.geonet.api.records.formatters.groovy.Functions; -import org.fao.geonet.api.records.formatters.groovy.Handlers; -import org.fao.geonet.api.records.formatters.groovy.TransformationContext; -import org.fao.geonet.utils.IO; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -import java.net.URL; -import java.util.Map; - -/** - * @author Jesse on 12/3/2014. - */ -public class TNodeIncludeTest extends AbstractTemplateParserTest { - Handlers handlers; - Functions functions; - Environment env; - - @Before - public void setUp() throws Exception { - handlers = Mockito.mock(Handlers.class); - functions = Mockito.mock(Functions.class); - env = Mockito.mock(Environment.class); - - FileResult result = Mockito.mock(FileResult.class); - Mockito.when(result.toString()).thenReturn("
included
"); - Mockito.when(handlers.fileResult(Mockito.anyString(), Mockito.anyMap())).thenReturn(result); - - new TransformationContext(handlers, functions, env).setThreadLocal(); - - } - - @Test - public void testInclude() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TNodeRepeatTest.class.getResource("include-template.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - String expected = "\n" - + "
included
\n" - + ""; - assertCorrectRender(parseTree, model, expected); - } - - @Test - public void testIncludeReplace() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TNodeRepeatTest.class.getResource("include-template-replace.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - String expected = "\n" - + "
included
\n" - + ""; - assertCorrectRender(parseTree, model, expected); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatIterTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatIterTest.java deleted file mode 100644 index deab2f9d16a5..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatIterTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.fao.geonet.SystemInfo; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.util.Collections; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class TNodeRepeatIterTest { - SystemInfo info = SystemInfo.createForTesting(SystemInfo.STAGE_TESTING); - - @Test - public void testEmptyRender() throws Exception { - final TNodeRepeatIter repeat = new TNodeRepeatIter(info, TextContentParserTest.createTestTextContentParser(), - false, null, TNode.EMPTY_ATTRIBUTES, "iter", "key"); - Map model = Collections.singletonMap("iter", Collections.emptyList()); - final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - repeat.render(new TRenderContext(outputStream, model)); - - assertEquals("", outputStream.toString()); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatMapTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatMapTest.java deleted file mode 100644 index d6aa71e9ea47..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatMapTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.fao.geonet.SystemInfo; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.util.Collections; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class TNodeRepeatMapTest { - SystemInfo info = SystemInfo.createForTesting(SystemInfo.STAGE_TESTING); - - @Test - public void testEmptyRender() throws Exception { - final TNodeRepeatMap repeat = new TNodeRepeatMap(info, TextContentParserTest.createTestTextContentParser(), false, null, TNode.EMPTY_ATTRIBUTES, "map", "key", "value"); - Map model = Collections.singletonMap("map", Collections.emptyMap()); - final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - repeat.render(new TRenderContext(outputStream, model)); - - assertEquals("", outputStream.toString()); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatTest.java deleted file mode 100644 index 099306498060..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeRepeatTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import org.fao.geonet.Constants; -import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.groovy.Functions; -import org.fao.geonet.api.records.formatters.groovy.TransformationContext; -import org.fao.geonet.api.records.formatters.groovy.util.NavBarItem; -import org.fao.geonet.utils.IO; -import org.junit.Test; -import org.mockito.Mockito; - -import java.net.URL; -import java.util.Map; - -/** - * @author Jesse on 12/3/2014. - */ -public class TNodeRepeatTest extends AbstractTemplateParserTest { - - @Test - public void testRepeatDirective() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TNodeRepeatTest.class.getResource("repeat-template.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - Map row1 = Maps.newLinkedHashMap(); - row1.put("key1", "value1"); - row1.put("key2", "value2"); - Map row2 = Maps.newLinkedHashMap(); - row2.put("key1", "value3"); - row2.put("key2", "value4"); - model.put("maps", Lists.newArrayList(row1, row2)); - model.put("type", "x"); - - String expected = "" + - "
true - false - 0
0 - x - key1 - value1
1 - x - key2 - value2
" + - "
false - true - 1
0 - x - key1 - value3
1 - x - key2 - value4
" + - ""; - assertCorrectRender(parseTree, model, expected); - } - - @Test(expected = TemplateException.class) - public void testRepeatMissingIterModelValue() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final String template = "
{{item}}
"; - final TNode parseTree = parser.parse(template.getBytes(Constants.CHARSET), TemplateType.XML); - assertCorrectRender(parseTree, Maps.newHashMap(), ""); - } - - @Test(expected = TemplateException.class) - public void testRepeatMissingMapModelValue() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final String template = "
{{key}}
"; - final TNode parseTree = parser.parse(template.getBytes(Constants.CHARSET), TemplateType.XML); - assertCorrectRender(parseTree, Maps.newHashMap(), ""); - } - - @Test - public void testRepeatOnlyChildren() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TNodeRepeatTest.class.getResource("repeat-only-children-template.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - Map map = Maps.newLinkedHashMap(); - map.put("key1", "value1"); - map.put("key2", "value2"); - model.put("map", map); - model.put("list", Lists.newArrayList("item1", "item2", "item3")); - - String expected = "" + - "
  • key1 - value1
  • " + - "
  • key2 - value2
  • " + - "
  • item1
  • " + - "
  • item2
  • " + - "
  • item3
  • " + - ""; - assertCorrectRender(parseTree, model, expected); - } - - @Test - public void testRepeatDirectiveObject() throws Exception { - final Functions mock = Mockito.mock(Functions.class); - Mockito.when(mock.translate("name1", null)).thenReturn("Name 1"); - Mockito.when(mock.translate("name2", null)).thenReturn("Name 2"); - new TransformationContext(null, mock, null).setThreadLocal(); - - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TNodeRepeatTest.class.getResource("repeat-object-template.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - final NavBarItem item1 = new NavBarItem(); - item1.setRel("rel1"); - item1.setName("name1"); - final NavBarItem item2 = new NavBarItem(); - item2.setRel("rel2"); - item2.setName("name2"); - model.put("items", Lists.newArrayList(item1, item2)); - - String expected = ""; - - assertCorrectRender(parseTree, model, expected); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranscludeTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranscludeTest.java deleted file mode 100644 index 9c16542b2f62..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranscludeTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Maps; - -import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.groovy.Environment; -import org.fao.geonet.api.records.formatters.groovy.Functions; -import org.fao.geonet.api.records.formatters.groovy.Handlers; -import org.fao.geonet.api.records.formatters.groovy.TransformationContext; -import org.fao.geonet.utils.IO; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.net.URL; -import java.util.Map; - -/** - * @author Jesse on 12/3/2014. - */ -public class TNodeTranscludeTest extends AbstractTemplateParserTest { - Handlers handlers; - Functions functions; - Environment env; - - @Before - public void setUp() throws Exception { - handlers = Mockito.mock(Handlers.class); - functions = Mockito.mock(Functions.class); - env = Mockito.mock(Environment.class); - - Mockito.when(handlers.fileResult(Mockito.anyString(), Mockito.anyMap())).then(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - final SystemInfo info = SystemInfo.createForTesting(SystemInfo.STAGE_TESTING); - SimpleTNode node = new SimpleTNode(info, TextContentParserTest.createTestTextContentParser(), "div", TNode.EMPTY_ATTRIBUTES); - node.setTextContent("{{include}}{{other1}}{{other2}}{{other3}}"); - final Map substitutions = (Map) invocation.getArguments()[1]; - return new FileResult(node, substitutions); - } - }); - - new TransformationContext(handlers, functions, env).setThreadLocal(); - - } - - @Test - public void testTransclude() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TNodeRepeatTest.class.getResource("transclude-template.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - model.put("other2", "Other&Two"); - model.put("other3", "Other Three"); - String expected = "
    " - + " within" - + "
    Other OneOther&TwoOther Three
    "; - - assertCorrectRender(parseTree, model, expected); - } - - @Test - public void testTranscludeReplace() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TNodeRepeatTest.class.getResource("transclude-template-replace.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - model.put("other2", "Other&Two"); - model.put("other3", "Other Three"); - - String expected = "
    withinOther OneOther&TwoOther Three
    "; - assertCorrectRender(parseTree, model, expected); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranslateTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranslateTest.java deleted file mode 100644 index a57a3db261be..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TNodeTranslateTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.groovy.Functions; -import org.fao.geonet.api.records.formatters.groovy.TransformationContext; -import org.fao.geonet.utils.IO; -import org.junit.Test; -import org.mockito.Mockito; - -import java.net.URL; -import java.util.Collections; - -/** - * @author Jesse on 12/3/2014. - */ -public class TNodeTranslateTest extends AbstractTemplateParserTest { - - @Test - public void testTranslateDirective() throws Exception { - final Functions mock = Mockito.mock(Functions.class); - Mockito.when(mock.translate("testString", null)).thenReturn("translation null"); - Mockito.when(mock.translate("testString", "file")).thenReturn("translation file"); - Mockito.when(mock.translate("nameKey", null)).thenReturn("Translated After resolve"); - Mockito.when(mock.codelistTranslation("testString", null, "name")).thenReturn("translation codelist null name"); - Mockito.when(mock.codelistTranslation("testString", "context1", "desc")).thenReturn("translation codelist desc context1"); - Mockito.when(mock.codelistTranslation("testString", "context2", "desc")).thenReturn("translation codelist desc context2"); - Mockito.when(mock.nodeTranslation("testString", "context", "name")).thenReturn("translation node name context"); - Mockito.when(mock.nodeTranslation("testString", null, "desc")).thenReturn("translation node desc null"); - new TransformationContext(null, mock, null).setThreadLocal(); - - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TNodeTranslateTest.class.getResource("translate.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - String expected = "\n" - + "
    translation null
    \n" - + "
    translation null
    \n" - + "
    translation file
    \n" - + "
    translation file
    \n" - + "
    translation codelist null name
    \n" - + "
    translation codelist desc context1
    \n" - + "
    translation codelist desc context2
    \n" - + "
    translation node name context
    \n" - + "
    translation node desc null
    \n" - + "
    Translated After resolve
    \n" - + ""; - - assertCorrectRender(parseTree, Collections.singletonMap("key", "nameKey"), expected); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TRenderContextTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TRenderContextTest.java deleted file mode 100644 index 35124e1696f5..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TRenderContextTest.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Maps; - -import groovy.util.XmlSlurper; -import groovy.util.slurpersupport.GPathResult; - -import org.fao.geonet.api.records.formatters.groovy.util.NavBarItem; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class TRenderContextTest { - - @Test - public void testGetModelValue() throws Exception { - final TestObj item = new TestObj(); - final Map model = Collections.singletonMap("item", item); - final TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), model); - assertEquals("KEY", context.getModelValue("item.inner.name")); - assertEquals("REL", context.getModelValue("item.inner.rel")); - assertEquals(item.toString(), context.getModelValue("item").toString()); - assertEquals(item.getInner().toString(), context.getModelValue("item.inner").toString()); - } - - @Test - public void testEmbeddedMap() throws Exception { - String itemKey = "item"; - final String expr = itemKey + ".inner.name"; - final Map inner = Collections.singletonMap("name", "KEY"); - Map item = Collections.singletonMap("inner", inner); - - final Map model = Collections.singletonMap(itemKey, item); - final TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), model); - - assertEquals(item.toString(), context.getModelValue("item").toString()); - assertEquals(item.get("inner").toString(), context.getModelValue("item.inner").toString()); - - context.getModelValue(expr); - assertEquals("KEY", context.getModelValue("item.inner.name")); - } - - @Test - public void testEmbeddedList() throws Exception { - String itemKey = "item"; - final String expr = itemKey + ".0.0"; - final List inner = Collections.singletonList("KEY"); - List item = Collections.singletonList(inner); - - final Map model = Collections.singletonMap(itemKey, item); - final TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), model); - assertEquals(item.toString(), context.getModelValue("item").toString()); - assertEquals(item.get(0).toString(), context.getModelValue("item.0").toString()); - - context.getModelValue(expr); - assertEquals("KEY", context.getModelValue("item.0.0")); - } - - @Test - public void testGPath() throws Exception { - String itemKey = "item"; - final XmlSlurper xmlSlurper = new XmlSlurper(false, false); - final String xml = - "da165110-88fd-11da-a88f-000d939bc5d8" - + ""; - - Map nsMapping = Maps.newHashMap(); - nsMapping.put("gmd", "http://www.isotc211.org/2005/gmd"); - nsMapping.put("gco", "http://www.isotc211.org/2005/gco"); - - final GPathResult gpath = xmlSlurper.parseText(xml).declareNamespace(nsMapping); - - final Map model = Collections.singletonMap(itemKey, gpath); - final TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), model); - - assertEquals("gmd:MD_Metadata", ((GPathResult) context.getModelValue("item")).name()); - assertEquals("gmd:fileIdentifier", ((GPathResult) context.getModelValue("item.gmd:fileIdentifier")).name()); - assertEquals("gmd:fileIdentifier", context.getModelValue("item.gmd:fileIdentifier.name()")); - assertEquals("gco:CharacterString", ((GPathResult) context.getModelValue("item.gmd:fileIdentifier.gco:CharacterString")).name()); - } - - @Test - public void testEmptyPathSection() throws Exception { - String itemKey = "item"; - final String expr = itemKey + "." + ".name"; - try { - final TestObj item = new TestObj(); - final Map model = Collections.singletonMap(itemKey, item); - final TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), model); - context.getModelValue(expr); - fail("Expected an exception"); - } catch (TemplateException e) { - assertTrue(e.getMessage(), e.getMessage().contains(expr)); - assertTrue(e.getMessage(), e.getMessage().contains("empty section")); - } - } - - @Test - public void testNoProperty() throws Exception { - String itemKey = "item"; - final String expr = itemKey + "." + "name"; - try { - final TestObj item = new TestObj(); - final Map model = Collections.singletonMap(itemKey, item); - final TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), model); - context.getModelValue(expr); - fail("Expected an exception"); - } catch (TemplateException e) { - assertTrue(e.getMessage(), e.getMessage().contains(expr)); - assertTrue(e.getMessage(), e.getMessage().contains("does not exist")); - } - } - - @Test - public void testNoItem() throws Exception { - String itemKey = "item"; - final String expr = "wrongKey.inner.name"; - try { - final TestObj item = new TestObj(); - final Map model = Collections.singletonMap(itemKey, item); - final TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), model); - context.getModelValue(expr); - fail("Expected an exception"); - } catch (TemplateException e) { - assertTrue(e.getMessage(), e.getMessage().contains(expr)); - assertTrue(e.getMessage(), e.getMessage().contains("There is no object in the model")); - } - } - - @Test - public void testNullItem() throws Exception { - String itemKey = "item"; - final String expr = itemKey + ".other.name"; - try { - final TestObj item = new TestObj(); - final Map model = Collections.singletonMap(itemKey, item); - final TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), model); - context.getModelValue(expr); - fail("Expected an exception"); - } catch (TemplateException e) { - assertTrue(e.getMessage(), e.getMessage().contains(expr)); - assertTrue(e.getMessage(), e.getMessage().contains("value of the property")); - assertTrue(e.getMessage(), e.getMessage().contains("is null")); - } - } - - private static class TestObj { - final NavBarItem inner = new NavBarItem(); - final NavBarItem other = null; - - private TestObj() { - inner.setName("KEY"); - inner.setRel("REL"); - } - - public NavBarItem getInner() { - return inner; - } - - @Override - public String toString() { - return "TestObj"; - } - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCacheIntegrationTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCacheIntegrationTest.java deleted file mode 100644 index 9e3c38c267dc..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCacheIntegrationTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import org.fao.geonet.api.records.formatters.AbstractFormatterTest; -import org.fao.geonet.kernel.SchemaManager; -import org.fao.geonet.schema.iso19139.ISO19139SchemaPlugin; -import org.fao.geonet.services.AbstractServiceIntegrationTest; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.fao.geonet.api.records.formatters.FormatterConstants.SCHEMA_PLUGIN_FORMATTER_DIR; -import static org.junit.Assert.assertTrue; - -public class TemplateCacheIntegrationTest extends AbstractServiceIntegrationTest { - @Autowired - private TemplateCache templateCache; - @Autowired - private SchemaManager schemaManager; - - @Test - public void testOnlineResource() throws Exception { - final Path schemaDir = schemaManager.getSchemaDir(ISO19139SchemaPlugin.IDENTIFIER); - Path rootFormatterDir = schemaDir.resolve(SCHEMA_PLUGIN_FORMATTER_DIR); - Path formatterDir = Paths.get(AbstractFormatterTest.class.getResource("template-cache-test").toURI()); - - Map model = Maps.newHashMap(); - List> links = Lists.newArrayList(); - links.add(newLink("href&1", "name&1", "desc&1")); - links.add(newLink("href2", null, "desc2")); - links.add(newLink(null, "name3", "desc3")); - links.add(newLink(null, "name4", null)); - model.put("links", links); - - FileResult fileResult = templateCache.createFileResult(formatterDir, schemaDir, rootFormatterDir, - "html/online-resource.html", model); - - final String finalResult = fileResult.toString(); - assertTrue(finalResult, finalResult.contains("href&1")); - assertTrue(finalResult, finalResult.contains("name&1")); - assertTrue(finalResult, finalResult.contains("desc&1")); - assertTrue(finalResult, finalResult.contains("href2")); - assertTrue(finalResult, finalResult.contains("desc2")); - assertTrue(finalResult, finalResult.contains("name3")); - assertTrue(finalResult, finalResult.contains("desc3")); - assertTrue(finalResult, finalResult.contains("name4")); - } - - private Map newLink(String href, String name, String desc) { - final HashMap model = Maps.newHashMap(); - model.put("href", href); - model.put("name", name); - model.put("desc", desc); - return model; - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCacheTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCacheTest.java deleted file mode 100644 index 2850c49aaebf..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateCacheTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import org.fao.geonet.ApplicationContextHolder; -import org.fao.geonet.Constants; -import org.fao.geonet.SystemInfo; -import org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest; -import org.fao.geonet.kernel.SchemaManager; -import org.fao.geonet.utils.IO; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.context.ConfigurableApplicationContext; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Collections; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class TemplateCacheTest { - - @Test - public void testCreateFileResult() throws Exception { - ConfigurableApplicationContext context = Mockito.mock(ConfigurableApplicationContext.class); - ApplicationContextHolder.set(context); - Mockito.when(context.getBean(SystemInfo.class)).thenReturn(SystemInfo.createForTesting(SystemInfo.STAGE_PRODUCTION)); - - final TemplateCache templateCache = new TemplateCache(); - templateCache.xmlTemplateParser = AbstractTemplateParserTest.createTestParser(SystemInfo.STAGE_TESTING); - final Path functionFile = IO.toPath(FormatterApiIntegrationTest.class.getResource("functions.xsl").toURI()); - final FileResult fileResult = templateCache.createFileResult(functionFile.getParent(), functionFile.getParent(), - functionFile.getParent(), functionFile.getFileName().toString(), Collections.emptyMap()); - - assertNotNull(fileResult); - assertNotNull(templateCache.canonicalFileNameToText.get(functionFile.toRealPath())); - } - - @Test - public void testFallback() throws Exception { - String[] stagingProfiles = {SystemInfo.STAGE_TESTING, SystemInfo.STAGE_DEVELOPMENT, SystemInfo.STAGE_PRODUCTION}; - - final Path file0 = IO.toPath(FormatterApiIntegrationTest.class.getResource("template-cache-test/formatter/file0.txt").toURI()); - final Path file1 = IO.toPath(FormatterApiIntegrationTest.class.getResource("template-cache-test/schema1/formatter/file1.txt").toURI()); - final Path file2 = IO.toPath(FormatterApiIntegrationTest.class.getResource("template-cache-test/schema2/formatter/file2.txt").toURI()); - final Path file3 = IO.toPath(FormatterApiIntegrationTest.class.getResource("template-cache-test/file3.txt").toURI()); - - for (String profile : stagingProfiles) { - SchemaManager schemaManager = Mockito.mock(SchemaManager.class); - Mockito.when(schemaManager.getSchemaDir("schema1")).thenReturn(file1.getParent().getParent()); - Mockito.when(schemaManager.getSchemaDir("schema2")).thenReturn(file2.getParent().getParent()); - - ConfigurableApplicationContext context = Mockito.mock(ConfigurableApplicationContext.class); - ApplicationContextHolder.set(context); - Mockito.when(context.getBean(SystemInfo.class)).thenReturn(SystemInfo.createForTesting(SystemInfo.STAGE_PRODUCTION)); - Mockito.when(context.getBean(SchemaManager.class)).thenReturn(schemaManager); - - final TemplateCache templateCache = new TemplateCache(); - templateCache.xmlTemplateParser = AbstractTemplateParserTest.createTestParser(SystemInfo.STAGE_TESTING); - final Path schemaAndRootDir = file0.getParent().getParent(); - - final Map emptyMap = Collections.emptyMap(); - FileResult fileResult = templateCache.createFileResult(file0.getParent(), schemaAndRootDir, - schemaAndRootDir, file0.getFileName().toString(), emptyMap); - assertEquals(new String(Files.readAllBytes(file0), Constants.CHARSET).length(), fileResult.toString().length()); - - fileResult = templateCache.createFileResult(file0.getParent(), schemaAndRootDir, - schemaAndRootDir, file1.getFileName().toString(), emptyMap); - assertEquals(new String(Files.readAllBytes(file1), Constants.CHARSET).length(), fileResult.toString().length()); - - - fileResult = templateCache.createFileResult(file0.getParent(), schemaAndRootDir, - schemaAndRootDir, file2.getFileName().toString(), emptyMap); - assertEquals(new String(Files.readAllBytes(file2), Constants.CHARSET).length(), fileResult.toString().length()); - - - fileResult = templateCache.createFileResult(file0.getParent(), schemaAndRootDir, - schemaAndRootDir, file3.getFileName().toString(), emptyMap); - assertEquals(new String(Files.readAllBytes(file3), Constants.CHARSET).length(), fileResult.toString().length()); - - } - - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateParserTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateParserTest.java deleted file mode 100644 index fcf937940976..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TemplateParserTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import org.fao.geonet.SystemInfo; -import org.fao.geonet.utils.IO; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.net.URL; -import java.nio.file.Path; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * @author Jesse on 12/3/2014. - */ -public class TemplateParserTest extends AbstractTemplateParserTest { - @Test(expected = TemplateException.class) - public void testRepeatNotMapWhenMapRequired() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TemplateParserTest.class.getResource("repeat-template.html"); - final TNode parseTree = parser.parse(IO.toPath(url.toURI())); - - Map model = Maps.newHashMap(); - model.put("maps", Lists.newArrayList(Lists.newArrayList("elem1"))); - model.put("type", "x"); - String expected = "This doesn't matter because the render should fail"; - assertCorrectRender(parseTree, model, expected); - } - - @Test(expected = TemplateException.class) - public void testMultipleDirectivesPerElem() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_TESTING); - final URL url = TemplateParserTest.class.getResource("multiple-directives-per-el-template.html"); - parser.parse(IO.toPath(url.toURI())); - } - - - @Test - public void testSpacing() throws Exception { - final TemplateParser parser = createTestParser(SystemInfo.STAGE_PRODUCTION); - final URL url = AbstractTemplateParserTest.class.getResource("template-spacing.html"); - final Path path = IO.toPath(url.toURI()); - final TNode parseTree = parser.parse(path); - - Map model = Maps.newHashMap(); - model.put("title", "Title"); - - String expected = "\n" - + "\n" - + " Title\n" - + "\n" - + ""; - final ByteArrayOutputStream result = new ByteArrayOutputStream(); - TRenderContext context = new TRenderContext(result, model); - - parseTree.render(context); - - assertEquals(expected + "\n" + result, expected, result.toString()); - } - -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentParserTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentParserTest.java deleted file mode 100644 index 616cf0f01f39..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentParserTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Maps; - -import org.junit.Test; -import org.springframework.stereotype.Component; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class TextContentParserTest { - - public static void assertCorrectRender(TextBlock contents, Map model, String expected) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - TRenderContext context = new TRenderContext(out, model); - contents.render(context); - - assertEquals(expected, out.toString()); - } - - public static TextContentParser createTestTextContentParser() throws InstantiationException, IllegalAccessException { - final TextContentParser parser = new TextContentParser(); - addFilters(parser, FilterCapitalize.class, FilterEscapeXmlAttrs.class, FilterEscapeXmlContent.class, FilterLowerCase.class, - FilterUpperCase.class, FilterGenerateUUID.class, FilterLastUUID.class); - return parser; - } - - private static void addFilters(TextContentParser parser, Class... filters) throws IllegalAccessException, - InstantiationException { - for (Class filter : filters) { - final Component componentAnnotation = filter.getAnnotation(Component.class); - parser.filters.put(componentAnnotation.value(), filter.newInstance()); - } - } - - @Test - public void testParse() throws Exception { - final TextContentParser parser = createTestTextContentParser(); - - final TextBlock contents = parser.parse("Hi {{name}}\n\n\tThis is a great test\n\nFrom {{from}}"); - - Map model = Maps.newHashMap(); - model.put("name", "Name"); - model.put("from", "From"); - assertCorrectRender(contents, model, "Hi Name\n\n\tThis is a great test\n\nFrom From"); - - model.remove("from"); - assertCorrectRender(contents, model, "Hi Name\n\n\tThis is a great test\n\nFrom from"); - - model.remove("name"); - assertCorrectRender(contents, model, "Hi name\n\n\tThis is a great test\n\nFrom from"); - - model.put("name", "Name"); - model.put("from", "From"); - assertCorrectRender(parser.parse("{{name}}{{from}}"), model, "NameFrom"); - } - - @Test - public void testParseAmp() throws Exception { - final TextContentParser parser = createTestTextContentParser(); - - TextBlock contents = parser.parse("{{name}}"); - - Map model = Maps.newHashMap(); - model.put("name", "&Name"); - assertCorrectRender(contents, model, "&Name"); - - final Component annotation = FilterEscapeXmlAttrs.class.getAnnotation(Component.class); - contents = parser.parse("{{name | " + annotation.value() + "}}"); - model.put("name", "&Name"); - assertCorrectRender(contents, model, "&Name"); - } -} diff --git a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentReplacementTest.java b/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentReplacementTest.java deleted file mode 100644 index 6ee935a63ddc..000000000000 --- a/services/src/test/java/org/fao/geonet/api/records/formatters/groovy/template/TextContentReplacementTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -package org.fao.geonet.api.records.formatters.groovy.template; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.io.UnsupportedEncodingException; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class TextContentReplacementTest { - - @Test - public void testText() throws Exception { - final TextContentReplacement textContentReplacement = new TextContentReplacement("key", Lists.newArrayList()); - - - String expected = "value"; - Map model = Maps.newHashMap(); - model.put("key", expected); - - assertCorrectText(textContentReplacement, expected, model); - } - - @Test - public void testTextAttributeEscape() throws Exception { - final TextContentReplacement textContentReplacement = new TextContentReplacement("key", - Lists.newArrayList(new FilterEscapeXmlAttrs())); - - - String expected = "value"; - Map model = Maps.newHashMap(); - model.put("key", expected); - - assertCorrectText(textContentReplacement, expected, model); - } - - public void assertCorrectText(TextContentReplacement textContentReplacement, String expected, Map model) throws UnsupportedEncodingException { - TRenderContext context = new TRenderContext(new ByteArrayOutputStream(), model); - final String text = textContentReplacement.text(context); - assertEquals(expected, text); - } -} diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-illegal-env-access-formatter/view.groovy b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-illegal-env-access-formatter/view.groovy deleted file mode 100644 index ff71854babc5..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-illegal-env-access-formatter/view.groovy +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -// This file should throw an error because env cannot be used in the config. it has to be used in a closure that is executed during -// the Metadata processing stage - -if (env.lang2 == "en") { - handlers.roots('gmd:distributionInfo//gmd:onLine[1]', 'gmd:identificationInfo/*', 'gmd:referenceSystemInfo') -} else { - handlers.roots('gmd:distributionInfo//gmd:onLine[1]') -} diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/Iso19139Functions.groovy b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/Iso19139Functions.groovy deleted file mode 100644 index 537a61b2633f..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/Iso19139Functions.groovy +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -public class Iso19139Functions { - static def handleTopic() { - return '

    fromFormatterGroovy

    ' - } -} \ No newline at end of file diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/block.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/block.html deleted file mode 100644 index ee2a451d98b8..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/block.html +++ /dev/null @@ -1,28 +0,0 @@ - - -

    - {{empty}} -

    {{label}}

    -{{childData}} -

    diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/dublin-core-groovy b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/dublin-core-groovy deleted file mode 100644 index 3bf382c71563..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/dublin-core-groovy +++ /dev/null @@ -1,6 +0,0 @@ -// This file will be put in the dublin-core/formatter/groovy directory for the test and will -// used by the test to test the dependsOn functionality - -public class DCFunctions { - static def isFileId = {it.name() == 'gmd:fileIdentifier'} -} diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/view.groovy b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/view.groovy deleted file mode 100644 index 81de6fa39da1..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy-test-formatter/view.groovy +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -/* - * The view.groovy script is a groovy script which must configure the handlers object - * (org.fao.geonet.api.records.formatters.groovy.Handlers). To script has - * the following variables bound before execution: - * - * - handlers - an org.fao.geonet.api.records.formatters.groovy.Handlers object - * - f - an org.fao.geonet.api.records.formatters.groovy.Functions object - * - env - an org.fao.geonet.api.records.formatters.groovy.Environment object. - * *IMPORTANT* this object can only be used during process time. When this - * script is executed the org.fao.geonet.api.records.formatters.groovy.Transformer - * object is created but not executed. The transformer is cached so that the - * groovy processing only needs to be executed once. - */ - - -/* - * the handlers.roots method allows you to select the elements in the document where the recursive processing - * of the xml should begin. If this is not present then there will be a single root which is - * root element of the metadata. - * The strings in the roots method are XPath selectors as take by org.fao.geonet.utils.Xml#selectNodes() - * All nodes selected by the selectors will be the root nodes - * - * the method roots will set the roots, the method root will add to the existing roots - */ -handlers.roots ('gmd:distributionInfo//gmd:onLine[1]', 'gmd:identificationInfo/*', 'gmd:referenceSystemInfo') - -// According to Groovy the brackets in a method call are optional (in many cases) so roots can be written: -// handlers.roots 'gmd:identificationInfo/*', 'gmd:distributionInfo//*[gco:CharacterString]' - -/** - * Another way to set the roots is to call the roots method with a closure. This is useful - * if you need to use data in the env object to determine which roots to select. - */ -handlers.roots { - if (env.param('brief') == 'true') { - ['gmd:distributionInfo//gmd:onLine[1]'] - } else { - ['gmd:distributionInfo//gmd:onLine[1]', 'gmd:identificationInfo/*', 'gmd:referenceSystemInfo'] - } -} - -/* - * a root can also be added by calling: - */ -handlers.root 'gmd:DataQuality' -/** - * Adding another root - */ -handlers.root 'gmd:fileIdentifier' - - -/* - * the handlers object is used to register handlers for the identified elements - * there are a few ways to specify what a handler can handle. - * - * The first and most performant is to specify the name of the element - * in the following any time a gmd:abstract element is encountered the - * function/closer will be executed passing in the selected element - * as mentioned above a handle function can return a string, file or XML - * in the case below it returns a string which will be parsed into XML - * groovy has multi-line strings with interpolation (see below) - * - * exact name have a default priority of 1 where as matchers that use functions to do the matching have a priority of 0 - * the matchers are checked to see if they are applied first by priority and then in the order that they are defined. - * - * The parameters passed to the handler are: - * - the GPathResult representing the current node - * - the current TransformationContext. This contains information about the current state of the transformation. it is not - * normally of use in the closures. - * - * Like Javascript you only need to specify as many parameters as needed. - * - * The return value will be converted to a string via the toString method and that string will be added to the resulting xml/html - */ -handlers.add 'gmd:abstract', { el -> - // Don't need a return because last expression of a function is - // always returned in groovy - """

    - ${f.nodeLabel('gmd:abstract', el.parent().name())} - ${el.'gco:CharacterString'.text()} -

    """ -} - -/* - * A start handler is executed when the view creation process begins. This is required when - * there are multiple roots or if there will be multiple top level elements. - * For example if the root is gmd:spatialRepresentation and there are multiple spatialRepresentation - * elements, then start and end handlers are required to wrap the elements with a single top-level - * element - * - * There is ever only one start and one end handler calling the method multiple times will replace the previous handler and thus - * the first call will have no effect. - * - * There are no parameters to a start and end handler - */ -handlers.start { - ''' - -''' -} - -/* - * End handlers are executed when the metadata is finished being processed - */ -handlers.end { - ''' - -''' -} - -handlers.skip('gmd:referenceSystemInfo', {it.'gmd:MD_ReferenceSystem'.'gmd:referenceSystemIdentifier'}) - -/* - * In addition to matching an element name exactly a regexp can be used for the matching - * Like Javascript regular expression in groovy start and end with / - */ -handlers.add ~/...:title/, { el -> - """

    - ${f.nodeLabel(el)} - ${el.'gco:CharacterString'.text()} -

    """ -} - -/* - * it is also possible to match on the path of the node. When matching against a path the path separator is - * > instead of / because / is the terminator of a regular expression in Groovy - * - * The function in this case turns a static method in the class Iso19139Functions into a function (done by the & operator) - * and passes that function as the handler. - * - * The following directories will be scanned for groovy files and made available to the script - * - format bundle directory - * - formatter/groovy directory - * - schema_plugins//formatter/groovy - */ -handlers.withPath ~/[^>]+>gmd:identificationInfo>.+topicCategory>gmd:MD_TopicCategoryCode/, Iso19139Functions.&handleTopic - -/* - * This example is similar but the class is from the /groovy - */ -handlers.withPath ~/[^>]+>gmd:identificationInfo>[^>]+>gmd:pointOfContact/, SharedFunctions.&text - -/* - * Methods can be defined which can used anywhere in the script. - * This method will take an element which has gco:CharacterString and/or gmd:PT_FreeText - * children and finds the translation that best matches the UI language - * the UI language is a global variable available to the script as f.lang3 and f.lang2 - * where they are the 3 and 2 letter language codes respectively - */ -def isoText = { el -> - def uiCode = "#${env.lang2.toUpperCase()}" // using interpolation to create a code like #DE - def locStrings = el.'**'.find{ it.name == 'gmd:LocalisedCharacterString'} - def ptEl = locStrings.find{it.'@locale' == uiCode} - if (ptEl != null) return ptEl.text() - if (el.'gco:CharacterString') return el.'gco:CharacterString'.text() - if (!locStrings.isEmpty) return locStrings[0].text() - "" -} - -/* - * A second way to define a handler is to provide a function as the first parameter which returns a - * boolean. (Again you don't need a return because return is implicit) - * In groovy functions there is a magic _it_ variable which refers to the single parameter - * passed in. You can either simply use it in the function or define a parameter like el -> - * The matcher function can have 0 - 2 parameters, they are: - * - GPathResult - the current node - * - String - the full path of the node - */ -def isRefSysCode = {el, path -> el.name() == 'gmd:code' && path.contains ('gmd:referenceSystemInfo')} - -/* - * due to a limitation of the groovy language the closure must always be the last argument so the matcher - * must either be a method and provide the &methodName reference or be assigned to a variable like in this - * example - */ -handlers.add isRefSysCode, { el -> - /* - * The html function in f (org.fao.geonet.api.records.formatters.groovy.Functions) allows - * the use of the very handy groovy.xml.MarkupBuilder which provides a light-weight method of writing XML or HTML. - * - * The f.html method takes a closure which can use the groovy.xml.MarkupBuilder and will return the html that has been - * created as a string. There for it is very useful for building html in handlers - */ - f.html { html -> - html.p('class': 'code') { - span('class': 'label', f.nodeLabel(el)) // translate is a method provided by framework - span('class': 'value', isoText(el)) - } - } -} - -/* - * This example illustrates another way of configuring a handler. this add method take a map of values and - * constructs a handler from them. The values that will be used from the map are, select and any JavaBean properties - * in the object. For example: - * - * - name - a name to help with logging and debugging - * - priority - handlers with a higher priority will be evaluated before handlers with a lower priority - */ -handlers.add name: 'container el', select: { it.children().size() > 0 }, priority: -1, { el -> - def childData = handlers.processElements(el.children(), el) - - /* - * we are returning a FileResult which has a path to the file as first parameter and takes a map - * of String -> Object which are the replacements. When this is returned the file will be loaded - * (UTF-8 by default) and all parts of the file with the pattern: ${key} will be replaced with the - * the value in the replacement map. So in this example ${label} will be replaced with the - * translated node name and ${children} will be replaced with the children XML. - * - * File resolution is as follows: - * - Check for file in same directory as the view.groovy file - * - If in a schema-plugin then look in the root formatter directory for the file - * - Finally look in the formatter directory for the file - */ - if (!childData.isEmpty()) { - return handlers.fileResult("block.html", [label: f.nodeLabel(el), childData: childData]) - } - - // return null if we don't want to add this element, just because it matches doesn't mean it has to produce data -} - -/* - * Another example of FileResult. In this case it is for a specific element and the template is looked up in the root - * formatter/groovy directory. - * - * This example mixes using a new MarkupBuilder object to create an XML string and then use that (and other) text as substitutions - * in the FileResult object that is returned. - * - * Note: It is possible to convert a FileResult object to a string via the toString() method. - * This is useful when you want to embed the data from one FileResult in another. - * - */ -handlers.add 'gmd:CI_OnlineResource', { el -> - def linkage = el.'gmd:linkage'.'gmd:URL'.text() - - if (!linkage.trim().isEmpty()) { - linkage = f.html {html -> - html.div ('class':'linkage') { - span ('class': 'label', f.nodeLabel(el.'gmd:linkage'.'gmd:URL') + ":") - span ('class': 'value', linkage) - } - } - } - handlers.fileResult ("groovy/online-resource.html",[ - resourceLabel: f.nodeLabel(el), - name: isoText(el.'gmd:name'), // get text of name child - desc: isoText(el.'gmd:description'), // get text of description child - linkage: linkage, - - ]) -} - -/* - * This example demonstrates accessing the request parameters. - * - * The env (org.fao.geonet.api.records.formatters.groovy.Environment) object has a method for getting the parameters - */ -handlers.add name: 'h2IdentInfo option', - select: {el -> el.name() == 'gmd:MD_DataIdentification' && env.param('h2IdentInfo').toBool()}, { el -> - def childData = handlers.processElements(el.children(), el) - - f.html { - it.div('class':'identificationInfo') { - h2 (f.nodeLabel(el)) - // mkp.yield and mkp.yieldUnescaped addes data to the body of the current tag. You can also add text - // as the last parameter of the tag params but that will be escaped. - // - // mkp has several useful methods for making XML - mkp.yieldUnescaped(childData) - } - } -} - - -/* - * The config.properties file has a property: dependsOn: dublin-core which means all the classes and functions available in - * /dublin-core/formatter/groovy are also available to this formatter. - * - * For this test we have added a class DCFunctions to the dublin-core groovy directory we will test this functionality by - * using the static method that class contains. - */ -handlers.add name: 'codelist handler', select: DCFunctions.isFileId, {el -> - "${el.text()}${f.nodeLabel('dc:creator', null)}" -} - -/** - * Sorters can be used to control the order in which the data is added to the resulting document. When the children of an - * element are being processed a sorter (if its matches method selects the element) will sort the data before it is added - * to the document. - * - * Like handlers, sorters can be prioritized so that the highest priority sorter that matches an element will be applied. - * - * The data passed to be sorted are org.fao.geonet.api.records.formatters.groovy.SortData objects. - */ -handlers.sort ~/.*/, {el1, el2 -> - el1.name().compareTo(el2.name()) -} - -def sortVal = { el -> - switch (el.name()) { - case "gmd:abstract": - case "gmd:pointOfContact": - return 0 - default: - return 1; - } -} - -/* - * As with handlers sorters have priority and can be created using the map form - * - * Note: Both handlers and sorters have a name parameter that is used during debugging and logging. It does not - * have a functional function. - * - * For the map form of handler and handlers any - */ -handlers.sort name:'Sort data identification children', select: 'gmd:MD_DataIdentification', priority: 5, {el1, el2 -> - sortVal(el1) - sortVal(el2) -} - -/* - * The following handler will accept a list of elements to the closure instead of a single element. Like the typical handler. - * - * A typical use would be to have a single header/label for all elements and list the values in a column under the header/label. - * - * When the select matches an element the rest of the siblings will be matched with the select and all of the selected elements - * will be passed to the handler. The selected elements will be skipped when normal processing is continued. - */ -handlers.add name: 'extent handler', select: 'gmd:extent', group: true, {els -> - "${els.size()}" -} diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/SharedFunctions.groovy b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/SharedFunctions.groovy deleted file mode 100644 index 461a7f0609f6..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/SharedFunctions.groovy +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2001-2016 Food and Agriculture Organization of the - * United Nations (FAO-UN), United Nations World Food Programme (WFP) - * and United Nations Environment Programme (UNEP) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 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 - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, - * Rome - Italy. email: geonetwork@osgeo.org - */ - -public class SharedFunctions { - static def text() { - return '

    fromSharedFunctions

    ' - } -} \ No newline at end of file diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/online-resource.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/online-resource.html deleted file mode 100644 index c65b6be62a74..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/online-resource.html +++ /dev/null @@ -1,29 +0,0 @@ - - -

    -

    {{resourceLabel}}

    -
    {{name}}
    -
    {{desc}}
    -{{linkage}} -

    diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/if-children-only.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/if-children-only.html deleted file mode 100644 index 928183473387..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/if-children-only.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - {{ title}} - - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/include-template-replace.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/include-template-replace.html deleted file mode 100644 index cdbc8cc4119e..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/include-template-replace.html +++ /dev/null @@ -1,26 +0,0 @@ - - - -
    - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/include-template.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/include-template.html deleted file mode 100644 index 639099ffcefe..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/include-template.html +++ /dev/null @@ -1,26 +0,0 @@ - - - -
    - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/multiple-directives-per-el-template.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/multiple-directives-per-el-template.html deleted file mode 100644 index aa2696bf87a1..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/multiple-directives-per-el-template.html +++ /dev/null @@ -1,27 +0,0 @@ - - - -
    -
    - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/non-empty-template.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/non-empty-template.html deleted file mode 100644 index b0a92ce0f3d8..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/non-empty-template.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - {{ title}} - - -
    {{div }}
    - - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-object-template.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-object-template.html deleted file mode 100644 index 11d8afb5cce1..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-object-template.html +++ /dev/null @@ -1,26 +0,0 @@ - - - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-only-children-template.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-only-children-template.html deleted file mode 100644 index a86bc6692282..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-only-children-template.html +++ /dev/null @@ -1,31 +0,0 @@ - - - -
    -
  • {{key}} - {{val}}
  • -
    -
    -
  • {{item}}
  • -
    - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-template.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-template.html deleted file mode 100644 index 444d3d7dee2b..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/repeat-template.html +++ /dev/null @@ -1,29 +0,0 @@ - - - -
    - {{$first}} - {{$last}} - {{$index}} -
    {{$index}} - {{type}} - {{key}} - {{val}}
    -
    - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/template-spacing.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/template-spacing.html deleted file mode 100644 index b6a40879dc67..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/template-spacing.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - {{ title}} - - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/transclude-template-replace.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/transclude-template-replace.html deleted file mode 100644 index cc5c964e01e3..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/transclude-template-replace.html +++ /dev/null @@ -1,29 +0,0 @@ - - -
    - within -
    diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/transclude-template.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/transclude-template.html deleted file mode 100644 index 9015d56fcb43..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/transclude-template.html +++ /dev/null @@ -1,29 +0,0 @@ - - -
    - within -
    diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/translate.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/translate.html deleted file mode 100644 index c05b332d51e2..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/translate.html +++ /dev/null @@ -1,35 +0,0 @@ - - - -
    testString
    -
    testString
    -
    testString
    -
    testString
    -
    testString
    -
    testString
    -
    testString
    -
    testString
    -
    testString
    -
    {{key}}
    - diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/uuid-filter-template.html b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/uuid-filter-template.html deleted file mode 100644 index 362ca0457e5f..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/template/uuid-filter-template.html +++ /dev/null @@ -1,26 +0,0 @@ - - - -
    - \ No newline at end of file diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/formatter-dir/loc/en-other-strings.json b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/formatter-dir/loc/en-other-strings.json deleted file mode 100644 index a95b4cf2a619..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/formatter-dir/loc/en-other-strings.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "other-strings": "Other Strings", - "in-both": "In Both other-strings" -} \ No newline at end of file diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/formatter-dir/loc/en-strings.json b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/formatter-dir/loc/en-strings.json deleted file mode 100644 index 486e54a14250..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/formatter-dir/loc/en-strings.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "formatter-strings": "FormatterStrings", - "in-both": "In Both strings" -} \ No newline at end of file diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/parent-schema/formatter/loc/en-more-strings.json b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/parent-schema/formatter/loc/en-more-strings.json deleted file mode 100644 index 5013854b0273..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/parent-schema/formatter/loc/en-more-strings.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "parent-schema-more": "Parent Schema More Strings XML", - "in-both-parent": "In Both Parent More Strings XML" -} \ No newline at end of file diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/parent-schema/formatter/loc/en-strings.json b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/parent-schema/formatter/loc/en-strings.json deleted file mode 100644 index 3eb68e643aff..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/parent-schema/formatter/loc/en-strings.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "parent-schema-strings": "Parent Schema Normal Strings XML", - "in-both-parent": "In Both Parent Strings XML" -} \ No newline at end of file diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/schema-dir/formatter/config.properties b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/schema-dir/formatter/config.properties deleted file mode 100644 index 83e44d92312e..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/schema-dir/formatter/config.properties +++ /dev/null @@ -1,24 +0,0 @@ -# -# Copyright (C) 2001-2016 Food and Agriculture Organization of the -# United Nations (FAO-UN), United Nations World Food Programme (WFP) -# and United Nations Environment Programme (UNEP) -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 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 -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA -# -# Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, -# Rome - Italy. email: geonetwork@osgeo.org -# - -dependsOn=parent-schema \ No newline at end of file diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/schema-dir/formatter/loc/en-strings.json b/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/schema-dir/formatter/loc/en-strings.json deleted file mode 100644 index c7fe4cc8b105..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/groovy/translation-test/schema-dir/formatter/loc/en-strings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "schema-strings": "Schema Normal Strings XML" -} \ No newline at end of file diff --git a/services/src/test/resources/org/fao/geonet/api/records/formatters/xml_view/test.xml b/services/src/test/resources/org/fao/geonet/api/records/formatters/xml_view/test.xml deleted file mode 100644 index ccf8342544c9..000000000000 --- a/services/src/test/resources/org/fao/geonet/api/records/formatters/xml_view/test.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - ä$£éàü¨è!|¢¬°§¬@°@#@ç&"*+"*ç"3)(=)§°ݤ㼷㼺ᴓꦍ - diff --git a/web-ui/src/main/resources/catalog/style/gn_metadata.less b/web-ui/src/main/resources/catalog/style/gn_metadata.less index 0753279c0c97..d12b9d700afc 100644 --- a/web-ui/src/main/resources/catalog/style/gn_metadata.less +++ b/web-ui/src/main/resources/catalog/style/gn_metadata.less @@ -358,17 +358,6 @@ header div.gn-abstract { } } -.gn-metadata-view-groovy { - font-family: Arial @font-family-sans-serif; - font-size: 13px; - dd, - .offseted { - border-left: 1px solid @gray-light; - background: @gray-lighter; - padding-left: 0.6em; - } -} - .gn-period { border-radius: 4px; padding-left: 8px; diff --git a/web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Functions.groovy b/web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Functions.groovy deleted file mode 100644 index 12cf4df35905..000000000000 --- a/web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Functions.groovy +++ /dev/null @@ -1,69 +0,0 @@ -package common - -import org.fao.geonet.api.records.formatters.FormatType -import org.fao.geonet.api.records.formatters.groovy.Environment -import org.nibor.autolink.*; - -public class Functions { - org.fao.geonet.api.records.formatters.groovy.Handlers handlers; - def org.fao.geonet.api.records.formatters.groovy.Functions f - def Environment env - - def isHtmlOutput = { - env.formatType == FormatType.html || env.formatType == FormatType.pdf || - env.formatType == FormatType.testpdf - } - - def isPDFOutput = { - env.formatType == FormatType.pdf || env.formatType == FormatType.testpdf - } - - /** - * Creates the default html for a label -> text pair. This is the element for primitive/simple data. - * This does not return a function it is returns the actual html and thus can be used within handlers/functions to - * directly get the html - */ - def textEl(label, text) { - return handlers.fileResult("html/text-el.html", ["label": label, "text" : text]) - } - - /** - * Same as textEl but doesn't escape the XML - */ - def wikiTextEl(label, text) { - return handlers.fileResult("html/wikitext-el.html", ["label": label, "text" : text]) - } - - /** - * Creates the default html for a label -> text pair. This is the element for primitive/simple data. - * This does not return a function it is returns the actual html and thus can be used within handlers/functions to - * directly get the html - */ - def urlEl(label, href, text) { - return handlers.fileResult("html/url-el.html", ["label": label, "href" : href, "text" : - text.length() > 50 ? (text.substring(0, 50) + "...") : text]) - } - - def textColEl(content, cols) { - return '
    ' + content + '
    ' - } - - def urlToHtml(content) { - LinkExtractor linkExtractor = LinkExtractor.builder() - .linkTypes(EnumSet.of(LinkType.URL)) // limit to URLs - .build(); - - Iterable links = linkExtractor.extractLinks(content); - String result = Autolink.renderLinks(content, links, new LinkRenderer() { - void render(LinkSpan link, CharSequence text, StringBuilder sb) { - sb.append(""); - sb.append(text, link.getBeginIndex(), link.getEndIndex()); - sb.append(""); - } - }); - return result - } - -} diff --git a/web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Handlers.groovy b/web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Handlers.groovy deleted file mode 100644 index ea804b3ce53d..000000000000 --- a/web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Handlers.groovy +++ /dev/null @@ -1,279 +0,0 @@ -package common - -import jeeves.server.context.ServiceContext -import org.fao.geonet.api.records.MetadataUtils -import org.fao.geonet.api.records.formatters.groovy.Environment -import org.fao.geonet.api.records.formatters.groovy.util.* -import org.fao.geonet.api.records.model.related.RelatedItemType -import org.fao.geonet.constants.Geonet -import org.fao.geonet.kernel.GeonetworkDataDirectory -import org.fao.geonet.utils.Xml -import org.jdom.Element - -public class Handlers { - private org.fao.geonet.api.records.formatters.groovy.Handlers handlers; - private org.fao.geonet.api.records.formatters.groovy.Functions f - private Environment env - - common.Matchers matchers - common.Functions func - boolean requireValidMetadataForPublish = false; - - public Handlers(handlers, f, env) { - this.handlers = handlers - this.f = f - this.env = env - func = new common.Functions(handlers: handlers, f:f, env:env) - matchers = new common.Matchers(handlers: handlers, f:f, env:env) - } - - def addDefaultStartAndEndHandlers() { - handlers.start htmlOrXmlStart - handlers.end htmlOrXmlEnd - } - - def entryEl(labeller) { - return entryEl(labeller, null) - } - /** - * Creates a function that will process all children and sort then according to the sorter that applies to the elements. Then - * returns the default html for the container elements. - * - * @param labeller a function for creating a label from the element - * @param classer a function taking the element class(es) to add to the entry element. The method should return a string. - */ - def entryEl(labeller, classer) { - return { el -> - def childData = handlers.processElements(el.children(), el); - def replacement = [label: labeller(el), childData: childData, name:''] - - if (classer != null) { - replacement.name = classer(el); - } - - if (!childData.isEmpty()) { - return handlers.fileResult('html/2-level-entry.html', replacement) - } - return null - } - } - def processChildren(childSelector) { - return {el -> - handlers.processElements(childSelector(el), el); - } - } - /** - * Creates a function which will: - * - * 1. Select a single element using the selector function - * 2. Process all children of the element selected in step 1 with sorter that applies to the element selected in step 1 - * 3. Create a label using executing the labeller on the element passed to handler functions (not element selected in step 1) - * - * @param selector a function that will select a single element from the descendants of the element passed to it - * @param labeller a function for creating a label from the element - */ - def flattenedEntryEl(selector, labeller) { - return { parentEl -> - def el = selector(parentEl) - def childData = handlers.processElements(el.children(), el); - - if (!childData.isEmpty()) { - return handlers.fileResult('html/2-level-entry.html', [label: labeller(el), childData: childData]) - } - return null - } - } - - def selectIsotype(name) { - return { - it.children().find { ch -> - ch.name() == name || ch['@gco:isoType'].text() == name - } - } - } - - - def htmlOrXmlStart = { - if (func.isHtmlOutput()) { - def minimize = '' - def baseUrl = func.f.fparams.url; - if (env.param("debug").toBool()) { - minimize = '?minimize=false' - } - String cssLinks = """ - - """; - - if (func.isPDFOutput()) { - cssLinks = """""" - } - return """ - - - - - $cssLinks - - - - -""" - } else { - return '' - } - } - - def htmlOrXmlEnd = { - def required = ""; - def tabToggle = ""; - def activeTab = env.param('tab').toString(); - - if (activeTab != 'Null Value') { - tabToggle = "gnFormatter.toggleTab('$activeTab');" - } - - if (!func.isPDFOutput()) { - required = """ -""" - } - if (func.isHtmlOutput()) { - return required + '' - } else { - return required - } - } - - - NavBarItem createXmlNavBarItem() { - return new NavBarItem(f.translate("xml"), f.translate("xml"), "", "xml.metadata.get?uuid=${env.metadataUUID}") - } - - def loadHierarchyLinkBlocks() { - def uuid = this.env.metadataUUID - def id = this.env.metadataId - - LinkBlock hierarchy = new LinkBlock("associated-link", "fa fa-sitemap") - Element related = getRelatedReport(id, uuid) - - related.getChildren().each { rel -> - - rel.getChildren("item").each { item -> - def type = rel.name - def direction = Direction.CHILD - def association - if (type == "siblings") { - association = item.getChildText("associationType") - if (association != null && association != '') { - type = association; - direction = Direction.PARENT - } - } else if (type == "services" || type == "sources" || type == "parent" || type == "fcats") { - direction = Direction.PARENT - } else if( type == 'associated') { - Element aggIndexEl = item.getChildren().find{it.getName() startsWith "agg_"} - if (aggIndexEl != null) { - type = aggIndexEl.name.substring(4) - } - } else if (type == "onlines" || type == "thumbnails") { - return; - } - - def relatedIdInfo = addRelation(hierarchy, uuid, item, type, direction) - - if (relatedIdInfo != null && direction == Direction.PARENT) { - def parentUUID = relatedIdInfo['uuid'] as String - def report = getRelatedReport(relatedIdInfo['id'] as int, parentUUID) - - report.getChildren().each { potentialSiblingRel -> - def relType = potentialSiblingRel.name - potentialSiblingRel.getChildren("item"). - findAll { it.getChildren("id").any {!it.getTextTrim().equals(uuid)}}. - each { potentialSiblingItem -> - if (association != null) { - boolean isAggSibling = potentialSiblingItem.getChildren("agg_$association").any { - it.getTextTrim() == parentUUID - } - if (isAggSibling) { - addRelation(hierarchy, parentUUID, potentialSiblingItem, association, Direction.SIBLING) - } - } else if (relType == 'datasets' || relType == 'hassource' || relType == 'hasfeaturecat') { - addRelation(hierarchy, parentUUID, potentialSiblingItem, relType, Direction.SIBLING) - } else if (relType == 'children') { - addRelation(hierarchy, parentUUID, potentialSiblingItem, "siblings", Direction.SIBLING) - } - } - } - } - } - } - return hierarchy; - } - - private Element getRelatedReport(int id, String uuid) { - def relatedXsl = this.env.getBean(GeonetworkDataDirectory).getWebappDir().resolve("xslt/services/metadata/relation.xsl"); - def RelatedItemType[] types = []; - def raw = MetadataUtils.getRelated(ServiceContext.get(), id, uuid, types, 1, 1000) - def withGui = new Element("root").addContent(Arrays.asList( - new Element("gui").addContent(Arrays.asList( - new Element("language").setText(env.lang3), - new Element("locUrl").setText(env.getLocalizedUrl()) - )), - raw)); - def related = Xml.transform(withGui, relatedXsl); - related - } - - private Map addRelation(hierarchy, uuid, rel, type, direction) { - def arrow; - switch (direction) { - case Direction.CHILD: - arrow = "pad-left fa-long-arrow-down" - break - case Direction.PARENT: - arrow = "pad-left fa-long-arrow-up" - break - default: - arrow = "fa-arrows-h" - } - def linkType = new LinkType() - linkType.name = type - linkType.relationDirection = direction - linkType.iconHtml = """ - -""" - def relUuid = rel.getChild("id").getText() - def relId = rel.getChild("mdid").getText() - def title = rel.getChild("title").getChild("value").getText() - def desc = rel.getChild("description").getChild("value").getText() - if (title == null || title.isEmpty()) { - title = relUuid; - } - - def href = createShowMetadataHref(relUuid) - def cls = uuid.trim().isEmpty() ? "text-muted" : '' - - def link = new AssociatedLink(href, title, cls) - link.setAbstract(desc); - link.metadataId = relUuid; - link.setLogo(rel.getChildText('logo')); - - hierarchy.put(linkType, link) - - return ['uuid': relUuid, 'id': relId] - - } - - private String createShowMetadataHref(String uuid) { - if (uuid.trim().isEmpty()) { - return "javascript:alert('" + this.f.translate("noUuidInLink") + "');" - } else { - return this.env.localizedUrl + "display#/" + URLEncoder.encode(uuid, "UTF-8") + "/formatters/full_view" - } - } - -} diff --git a/web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Matchers.groovy b/web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Matchers.groovy deleted file mode 100644 index 4d522a1013e4..000000000000 --- a/web/src/main/webapp/WEB-INF/data/data/formatter/groovy/common/Matchers.groovy +++ /dev/null @@ -1,11 +0,0 @@ -package common - -public class Matchers { - def handlers; - def f - def env - - def hasChild(childName) { - return { !it.children().find {it.name() == childName}.isEmpty() } - } -} diff --git a/web/src/main/webapp/WEB-INF/data/data/formatter/hierarchy_view/config.properties b/web/src/main/webapp/WEB-INF/data/data/formatter/hierarchy_view/config.properties deleted file mode 100644 index 10e79565120b..000000000000 --- a/web/src/main/webapp/WEB-INF/data/data/formatter/hierarchy_view/config.properties +++ /dev/null @@ -1 +0,0 @@ -published=false \ No newline at end of file diff --git a/web/src/main/webapp/WEB-INF/data/data/formatter/hierarchy_view/view.groovy b/web/src/main/webapp/WEB-INF/data/data/formatter/hierarchy_view/view.groovy deleted file mode 100644 index 750399fb5c24..000000000000 --- a/web/src/main/webapp/WEB-INF/data/data/formatter/hierarchy_view/view.groovy +++ /dev/null @@ -1,3 +0,0 @@ -handlers.add select: ~/.*/, {els -> - handlers.fileResult("html/associated.html", ["associated" : new common.Handlers(handlers, f, env).loadHierarchyLinkBlocks()]) -} \ No newline at end of file diff --git a/web/src/main/webapp/WEB-INF/data/data/formatter/html/2-level-entry.html b/web/src/main/webapp/WEB-INF/data/data/formatter/html/2-level-entry.html deleted file mode 100644 index 0e8e44fa8b12..000000000000 --- a/web/src/main/webapp/WEB-INF/data/data/formatter/html/2-level-entry.html +++ /dev/null @@ -1,15 +0,0 @@ -
    - -

    - - {{label}} -

    - -
    -
    - {{childData}} -
    -
    -
    diff --git a/web/src/main/webapp/WEB-INF/data/data/formatter/html/associated.html b/web/src/main/webapp/WEB-INF/data/data/formatter/html/associated.html deleted file mode 100644 index d414cceaa27c..000000000000 --- a/web/src/main/webapp/WEB-INF/data/data/formatter/html/associated.html +++ /dev/null @@ -1,54 +0,0 @@ -