diff --git a/modules/admin/admin-event/src/test/java/com/enonic/xp/admin/event/impl/json/EventJsonSerializerTest.java b/modules/admin/admin-event/src/test/java/com/enonic/xp/admin/event/impl/json/EventJsonSerializerTest.java index 1e18dee791c..22986fa2ac7 100644 --- a/modules/admin/admin-event/src/test/java/com/enonic/xp/admin/event/impl/json/EventJsonSerializerTest.java +++ b/modules/admin/admin-event/src/test/java/com/enonic/xp/admin/event/impl/json/EventJsonSerializerTest.java @@ -15,8 +15,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.event.Event; -import com.enonic.xp.json.ObjectMapperHelper; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; diff --git a/modules/admin/admin-impl/src/test/java/com/enonic/xp/admin/impl/StatusApiHandlerTest.java b/modules/admin/admin-impl/src/test/java/com/enonic/xp/admin/impl/StatusApiHandlerTest.java index 23a081a3c16..bcf7d2b96fa 100644 --- a/modules/admin/admin-impl/src/test/java/com/enonic/xp/admin/impl/StatusApiHandlerTest.java +++ b/modules/admin/admin-impl/src/test/java/com/enonic/xp/admin/impl/StatusApiHandlerTest.java @@ -4,7 +4,7 @@ import org.junit.jupiter.api.Test; -import com.enonic.xp.json.ObjectMapperHelper; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.server.VersionInfo; import com.enonic.xp.web.WebResponse; diff --git a/modules/app/app-system/build.gradle b/modules/app/app-system/build.gradle index 4897ccc29b9..5f0cbe3775c 100644 --- a/modules/app/app-system/build.gradle +++ b/modules/app/app-system/build.gradle @@ -1,6 +1,7 @@ dependencies { compileOnly project( ':core:core-api' ) compileOnly project( ':script:script-api' ) + compileOnly project( ':core:core-internal' ) testImplementation project( ':tools:testing' ) } diff --git a/modules/app/app-system/src/main/java/com/enonic/xp/app/system/VacuumTaskHandler.java b/modules/app/app-system/src/main/java/com/enonic/xp/app/system/VacuumTaskHandler.java index dc2cbf6c463..0029565d1d7 100644 --- a/modules/app/app-system/src/main/java/com/enonic/xp/app/system/VacuumTaskHandler.java +++ b/modules/app/app-system/src/main/java/com/enonic/xp/app/system/VacuumTaskHandler.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.enonic.xp.app.system.listener.VacuumListenerImpl; -import com.enonic.xp.json.ObjectMapperHelper; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.script.bean.BeanContext; import com.enonic.xp.script.bean.ScriptBean; import com.enonic.xp.task.ProgressReporter; diff --git a/modules/core/core-api/build.gradle b/modules/core/core-api/build.gradle index 9b786373847..59f277de364 100644 --- a/modules/core/core-api/build.gradle +++ b/modules/core/core-api/build.gradle @@ -2,23 +2,23 @@ dependencies { api ( libs.guava.guava ) { exclude group: 'com.google.code.findbugs' } - api libs.jackson.databind api libs.osgi.core api libs.jakarta.mail api libs.metrics.core // The following libraries are not really API. Remove in future versions of XP. + api libs.jackson.databind api libs.slf4j.api compileOnlyApi libs.osgi.service.componentannotations api libs.osgi.service.component implementation project( ':core:core-internal' ) - implementation libs.jackson.datatype.jsr310 implementation libs.jparsec testFixturesImplementation libs.junit.jupiter.api testFixturesImplementation libs.mockito.core + testFixturesImplementation project( ':core:core-internal' ) testImplementation project( ':core:core-internal' ) } diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyArrayJson.java b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyArrayJson.java index a659aef3d04..487f54de171 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyArrayJson.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyArrayJson.java @@ -1,55 +1,15 @@ package com.enonic.xp.data; -import java.util.ArrayList; import java.util.List; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - import com.enonic.xp.annotation.PublicApi; @PublicApi -@JsonInclude(JsonInclude.Include.NON_NULL) -public class PropertyArrayJson +public final class PropertyArrayJson { - @JsonProperty("name") - private String name; - - @JsonProperty("type") - private String type; - - @JsonProperty("values") - private List values; - - public PropertyArrayJson() - { - } - - static PropertyArrayJson toJson( final PropertyArray propertyArray ) - { - final PropertyArrayJson json = new PropertyArrayJson(); - json.name = propertyArray.getName(); - json.type = propertyArray.getValueType().getName(); - - json.values = new ArrayList<>( propertyArray.size() ); - for ( final Property property : propertyArray.getProperties() ) - { - json.values.add( new PropertyValueJson( property ) ); - } - - return json; - } - - void fromJson( final PropertySet parent ) - { - final ValueType valueType = ValueTypes.getByName( type ); - final PropertyArray array = new PropertyArray( parent, name, valueType, values.size() ); + public String name; - for ( final PropertyValueJson valueJson : values ) - { - valueJson.fromJson( array, valueType ); - } + public String type; - parent.addPropertyArray( array ); - } + public List values; } diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertySet.java b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertySet.java index 1cd8918782a..f476a087505 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertySet.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertySet.java @@ -6,6 +6,7 @@ import java.time.LocalTime; import java.util.ArrayList; import java.util.Collection; +import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; @@ -317,7 +318,7 @@ public Property setProperty( final PropertyPath path, final Value value ) /** * WARNING: This method may be removed at any time. It is not recommended to use it in new code. * This method is only used to simulate the behavior of PropertySet Serialisation. - * See {@link com.enonic.xp.data.PropertyArrayJson#fromJson} + * See {@link com.enonic.xp.data.PropertyTreeJson#fromJson} *
*
* Ensures that the property with the given name has type of valueType given. @@ -325,7 +326,7 @@ public Property setProperty( final PropertyPath path, final Value value ) * If the property with values exists and is not a type of valueType given, an exception will be thrown. * Difference with setProperty is that this method does not set the property value. * - * @param name property name + * @param name property name * @param valueType expected value type */ public void ensureProperty( final String name, final ValueType valueType ) @@ -675,9 +676,7 @@ public Property[] addStrings( final String name, final String... values ) public Property[] addStrings( final String name, final Collection values ) { - return values.stream(). - map( ( value ) -> addProperty( name, ValueFactory.newString( value ) ) ). - toArray( Property[]::new ); + return values.stream().map( ( value ) -> addProperty( name, ValueFactory.newString( value ) ) ).toArray( Property[]::new ); } // setting xml @@ -1436,4 +1435,60 @@ private String enumToString( final Enum e ) return e.toString(); } + static void translate( final Map json, final PropertySet into ) + { + for ( Map.Entry field : json.entrySet() ) + { + addValue( into, field.getKey(), field.getValue() ); + } + } + + private static void addValue( final PropertySet parent, final String key, final Object value ) + { + if ( value instanceof Collection ) + { + for ( final Object objNode : (Collection) value ) + { + addValue( parent, key, objNode ); + } + } + else if ( value instanceof Map ) + { + final PropertySet parentSet = parent.addSet( key ); + for ( final Map.Entry next : ( (Map) value ).entrySet() ) + { + addValue( parentSet, next.getKey(), next.getValue() ); + } + } + else + { + parent.addProperty( key, resolveCoreValue( value ) ); + } + } + + private static Value resolveCoreValue( final Object value ) + { + return switch ( value ) + { + case String s -> ValueFactory.newString( s ); + case Integer i -> ValueFactory.newLong( i.longValue() ); + case Float v -> ValueFactory.newDouble( v.doubleValue() ); + case Double v -> ValueFactory.newDouble( v ); + case Boolean b -> ValueFactory.newBoolean( b ); + case Long l -> ValueFactory.newLong( l ); + case Byte b -> ValueFactory.newLong( b.longValue() ); + case Short s -> ValueFactory.newLong( s.longValue() ); + case Instant instant -> ValueFactory.newDateTime( instant ); + case Date date -> ValueFactory.newDateTime( date.toInstant() ); + case LocalTime localTime -> ValueFactory.newLocalTime( localTime ); + case LocalDateTime localDateTime -> ValueFactory.newLocalDateTime( localDateTime ); + case LocalDate localDate -> ValueFactory.newLocalDate( localDate ); + case GeoPoint geoPoint -> ValueFactory.newGeoPoint( geoPoint ); + case Reference reference -> ValueFactory.newReference( reference ); + case BinaryReference binaryReference -> ValueFactory.newBinaryReference( binaryReference ); + case Link link -> ValueFactory.newLink( link ); + case null -> ValueFactory.newString( null ); + default -> ValueFactory.newString( value.toString() ); + }; + } } diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyTree.java b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyTree.java index 5d6738c0883..12f6a69b39b 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyTree.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyTree.java @@ -51,6 +51,13 @@ public Map toMap() return root.toMap(); } + public static PropertyTree fromMap( Map map ) + { + final PropertyTree into = new PropertyTree(); + PropertySet.translate( map, into.root ); + return into; + } + @Override public boolean equals( final Object o ) { diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyTreeJson.java b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyTreeJson.java index 337d9067fb5..c4f57b0721b 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyTreeJson.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyTreeJson.java @@ -14,7 +14,7 @@ public static PropertyTree fromJson( final List list ) final PropertySet propertySet = tree.getRoot(); for ( PropertyArrayJson propertyArrayJson : list ) { - propertyArrayJson.fromJson( propertySet ); + fromArrayJson( propertyArrayJson, propertySet ); } return tree; } @@ -24,8 +24,87 @@ public static List toJson( final PropertyTree propertyTree ) final List list = new ArrayList<>(); for ( final PropertyArray propertyArray : propertyTree.getRoot().getPropertyArrays() ) { - list.add( PropertyArrayJson.toJson( propertyArray ) ); + list.add( propertyArrayToJson( propertyArray ) ); } return list; } + + private static void fromArrayJson( PropertyArrayJson from, final PropertySet parent ) + { + final ValueType valueType = ValueTypes.getByName( from.type ); + final PropertyArray array = new PropertyArray( parent, from.name, valueType, from.values.size() ); + + for ( final PropertyValueJson valueJson : from.values ) + { + fromValueJson( valueJson, array, valueType ); + } + + parent.addPropertyArray( array ); + } + + private static void fromValueJson( PropertyValueJson valueJson, final PropertyArray into, final ValueType type ) + { + final Value value; + if ( type.equals( ValueTypes.PROPERTY_SET ) ) + { + if ( valueJson.set != null ) + { + final PropertySet newSet = new PropertySet( into.getParent().getTree(), valueJson.set.size() ); + + for ( final PropertyArrayJson propertyArrayJson : valueJson.set ) + { + fromArrayJson( propertyArrayJson, newSet ); + } + value = ValueFactory.newPropertySet( newSet ); + } + else + { + value = ValueFactory.newPropertySet( null ); + } + } + else + { + value = type.fromJsonValue( valueJson.v ); + } + + into.addValue( value ); + } + + static PropertyArrayJson propertyArrayToJson( final PropertyArray propertyArray ) + { + final PropertyArrayJson json = new PropertyArrayJson(); + json.name = propertyArray.getName(); + json.type = propertyArray.getValueType().getName(); + + json.values = new ArrayList<>( propertyArray.size() ); + for ( final Property property : propertyArray.getProperties() ) + { + json.values.add( propertyToJson( property ) ); + } + + return json; + } + + private static PropertyValueJson propertyToJson( final Property property) { + final PropertyValueJson json = new PropertyValueJson(); + if ( property.getType().equals( ValueTypes.PROPERTY_SET ) ) + { + final PropertySet propertySet = property.getSet(); + if ( propertySet != null ) + { + final List propertyArrayJsonList = new ArrayList<>(); + + for ( final PropertyArray propertyArray : propertySet.getPropertyArrays() ) + { + propertyArrayJsonList.add( propertyArrayToJson( propertyArray ) ); + } + json.set = propertyArrayJsonList; + } + } + else + { + json.v = property.getValue().toJsonValue(); + } + return json; + } } diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyValueJson.java b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyValueJson.java index 0b430076424..d909e743c47 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyValueJson.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/data/PropertyValueJson.java @@ -1,72 +1,13 @@ package com.enonic.xp.data; -import java.util.ArrayList; import java.util.List; -import com.fasterxml.jackson.annotation.JsonInclude; - import com.enonic.xp.annotation.PublicApi; @PublicApi -@JsonInclude(JsonInclude.Include.NON_NULL) public final class PropertyValueJson { public Object v; public List set; - - public PropertyValueJson() - { - // Needed for Jackson - } - - PropertyValueJson( final Property property ) - { - if ( property.getType().equals( ValueTypes.PROPERTY_SET ) ) - { - final PropertySet propertySet = property.getSet(); - if ( propertySet != null ) - { - final List propertyArrayJsonList = new ArrayList<>(); - - for ( final PropertyArray propertyArray : propertySet.getPropertyArrays() ) - { - propertyArrayJsonList.add( PropertyArrayJson.toJson( propertyArray ) ); - } - this.set = propertyArrayJsonList; - } - } - else - { - this.v = property.getValue().toJsonValue(); - } - } - - void fromJson( final PropertyArray array, final ValueType type ) - { - final Value value; - if ( type.equals( ValueTypes.PROPERTY_SET ) ) - { - if ( this.set != null ) - { - final PropertySet newSet = new PropertySet( array.getParent().getTree(), set.size() ); - - for ( final PropertyArrayJson propertyArrayJson : set ) - { - propertyArrayJson.fromJson( newSet ); - } - value = ValueFactory.newPropertySet( newSet ); - } - else - { - value = ValueFactory.newPropertySet( null ); - } - } - else - { - value = type.fromJsonValue( v ); - } - - array.addValue( value ); - } } diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/issue/FindIssuesParams.java b/modules/core/core-api/src/main/java/com/enonic/xp/issue/FindIssuesParams.java index a703424602d..5b93b4d2bcf 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/issue/FindIssuesParams.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/issue/FindIssuesParams.java @@ -1,9 +1,9 @@ package com.enonic.xp.issue; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.enonic.xp.content.ContentIds; +@Deprecated public final class FindIssuesParams { private final IssueStatus status; @@ -61,7 +61,6 @@ public Integer getSize() return size; } - @JsonIgnore public ContentIds getItems() { return items; diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/json/JsonToPropertyTreeTranslator.java b/modules/core/core-api/src/main/java/com/enonic/xp/json/JsonToPropertyTreeTranslator.java deleted file mode 100644 index 70f60b92270..00000000000 --- a/modules/core/core-api/src/main/java/com/enonic/xp/json/JsonToPropertyTreeTranslator.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.enonic.xp.json; - -import java.util.Iterator; -import java.util.Map; - -import com.fasterxml.jackson.databind.JsonNode; - -import com.enonic.xp.annotation.PublicApi; -import com.enonic.xp.data.Property; -import com.enonic.xp.data.PropertySet; -import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.data.Value; -import com.enonic.xp.data.ValueFactory; -import com.enonic.xp.form.Form; -import com.enonic.xp.form.FormItemPath; -import com.enonic.xp.form.Input; -import com.enonic.xp.inputtype.InputType; -import com.enonic.xp.inputtype.InputTypeResolver; -import com.enonic.xp.inputtype.InputTypes; - - -/** - * @deprecated As of release 6.9 - */ -@PublicApi -@Deprecated(since = "6.9") -public final class JsonToPropertyTreeTranslator -{ - private final Form form; - - private final PropertyTree propertyTree; - - private final InputTypeResolver inputTypeResolver; - - private final boolean strictMode; - - @SuppressWarnings("unused") - // Kept for backward compatibility - public JsonToPropertyTreeTranslator() - { - this( null, false ); - } - - @SuppressWarnings("unused") - // Kept for backward compatibility - public JsonToPropertyTreeTranslator( final Form form, final boolean strict ) - { - this.form = form != null ? form : Form.create().build(); - this.strictMode = strict; - this.propertyTree = new PropertyTree(); - this.inputTypeResolver = InputTypes.BUILTIN; - } - - public PropertyTree translate( final JsonNode json ) - { - traverse( json, this.propertyTree.getRoot() ); - return this.propertyTree; - } - - private void traverse( final JsonNode json, final PropertySet parent ) - { - final Iterator> fields = json.fields(); - - while ( fields.hasNext() ) - { - final Map.Entry next = fields.next(); - addValue( parent, next.getKey(), next.getValue() ); - } - } - - private void addValue( final PropertySet parent, final String key, final JsonNode value ) - { - if ( value.isArray() ) - { - for ( final JsonNode objNode : value ) - { - addValue( parent, key, objNode ); - } - } - else if ( value.isObject() && !hasInput( parent.getProperty(), key ) ) - { - final PropertySet parentSet = parent.addSet( key ); - value.fields().forEachRemaining( ( objectValue ) -> addValue( parentSet, objectValue.getKey(), objectValue.getValue() ) ); - } - else - { - mapValue( parent, key, value ); - } - } - - private void mapValue( final PropertySet parent, final String key, final JsonNode value ) - { - final Property parentProperty = parent.getProperty(); - final Input input = getInput( parentProperty, key ); - - if ( input == null ) - { - if ( this.strictMode ) - { - throw new IllegalArgumentException( - "No mapping defined for property " + key + " with value " + resolveStringValue( value ) ); - } - - parent.addProperty( key, resolveCoreValue( value ) ); - } - else - { - final InputType type = this.inputTypeResolver.resolve( input.getInputType() ); - final Value mappedPropertyValue = type.createValue( resolveCoreValue( value ), input.getInputTypeConfig() ); - - parent.addProperty( key, mappedPropertyValue ); - } - } - - private Value resolveCoreValue( final JsonNode value ) - { - if ( value.isTextual() ) - { - return ValueFactory.newString( value.textValue() ); - } - - if ( value.isDouble() ) - { - return ValueFactory.newDouble( value.doubleValue() ); - } - - if ( value.isInt() ) - { - return ValueFactory.newLong( (long) value.intValue() ); - } - - if ( value.isLong() ) - { - return ValueFactory.newLong( value.longValue() ); - } - - if ( value.isObject() ) - { - PropertySet propertySet = new PropertySet(); - value.fields(). - forEachRemaining( ( field ) -> { - if ( field.getValue().isArray() ) - { - for ( final JsonNode arrayNode : field.getValue() ) - { - propertySet.addProperty( field.getKey(), resolveCoreValue( arrayNode ) ); - } - } - else - { - propertySet.addProperty( field.getKey(), resolveCoreValue( field.getValue() ) ); - } - } ); - return ValueFactory.newPropertySet( propertySet ); - } - - return ValueFactory.newString( value.toString() ); - } - - private String resolveStringValue( final JsonNode value ) - { - if ( value.isTextual() ) - { - return value.textValue(); - } - - return value.toString(); - } - - private FormItemPath resolveInputPath( final String key, final Property parentProperty ) - { - if ( parentProperty == null ) - { - return FormItemPath.from( key ); - } - - final FormItemPath parentPath = FormItemPath.from( parentProperty.getPath().resetAllIndexesTo( 0 ).toString() ); - return FormItemPath.from( parentPath, key ); - } - - private boolean hasInput( final Property parentProperty, final String key ) - { - return this.form.getFormItem( resolveInputPath( key, parentProperty ) ) instanceof Input; - } - - private Input getInput( final Property parentProperty, final String key ) - { - return this.form.getInput( resolveInputPath( key, parentProperty ), true ); - } - -} diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/json/ObjectMapperHelper.java b/modules/core/core-api/src/main/java/com/enonic/xp/json/ObjectMapperHelper.java index 8208a48493d..b3c76a40652 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/json/ObjectMapperHelper.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/json/ObjectMapperHelper.java @@ -1,25 +1,16 @@ package com.enonic.xp.json; -import java.text.SimpleDateFormat; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.json.JsonMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +@Deprecated public final class ObjectMapperHelper { + private ObjectMapperHelper() + { + } + public static ObjectMapper create() { - final JsonMapper.Builder mapper = JsonMapper.builder(); - mapper.defaultDateFormat( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ) ); - mapper.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS ); - mapper.disable( SerializationFeature.FAIL_ON_EMPTY_BEANS ); - mapper.enable( MapperFeature.SORT_PROPERTIES_ALPHABETICALLY ); - mapper.serializationInclusion( JsonInclude.Include.ALWAYS ); - mapper.addModule( new JavaTimeModule() ); - return mapper.build(); + return com.enonic.xp.core.internal.json.ObjectMapperHelper.create(); } } diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/region/ComponentName.java b/modules/core/core-api/src/main/java/com/enonic/xp/region/ComponentName.java index 180b1bb5bf6..2939c7e4974 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/region/ComponentName.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/region/ComponentName.java @@ -13,7 +13,6 @@ public ComponentName( final String value ) { if ( value == null ) { - System.out.println( "ComponentName.value is null" ); throw new NullPointerException( "ContentName value cannot be null" ); } this.value = value; diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/repository/IndexMapping.java b/modules/core/core-api/src/main/java/com/enonic/xp/repository/IndexMapping.java index f83a334ee26..5cd66f18422 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/repository/IndexMapping.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/repository/IndexMapping.java @@ -1,46 +1,67 @@ package com.enonic.xp.repository; import java.net.URL; +import java.util.Map; import com.fasterxml.jackson.databind.JsonNode; import com.enonic.xp.annotation.PublicApi; +import com.enonic.xp.core.internal.json.JsonHelper; import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.util.JsonHelper; @PublicApi public class IndexMapping { private final JsonNode jsonNode; + @Deprecated + public IndexMapping( final JsonNode resourceNode ) + { + this.jsonNode = resourceNode.deepCopy(); + } + + private IndexMapping( final JsonNode resourceNode, boolean ignore ) + { + this.jsonNode = resourceNode; + } + + @Deprecated public static IndexMapping from( final PropertyTree propertyTree ) { - return new IndexMapping( JsonHelper.from( propertyTree ) ); + return new IndexMapping( JsonHelper.from( propertyTree.toMap() ), false ); } + @Deprecated public static IndexMapping from( final URL url ) { - return new IndexMapping( JsonHelper.from( url ) ); + return new IndexMapping( JsonHelper.from( url ), false ); } + @Deprecated public static IndexMapping from( final String string ) { - return new IndexMapping( JsonHelper.from( string ) ); + return new IndexMapping( JsonHelper.from( string ), false ); } - public IndexMapping( final JsonNode resourceNode ) + public static IndexMapping from( final Map data ) { - this.jsonNode = resourceNode; + return new IndexMapping( JsonHelper.from( data ), false ); } + public Map getData() + { + return JsonHelper.toMap( jsonNode ); + } + + @Deprecated public JsonNode getNode() { return jsonNode; } + @Deprecated public String getAsString() { return this.jsonNode.toString(); } - } diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/repository/IndexSettings.java b/modules/core/core-api/src/main/java/com/enonic/xp/repository/IndexSettings.java index 442b93bdf5e..820f6a203b7 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/repository/IndexSettings.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/repository/IndexSettings.java @@ -6,47 +6,62 @@ import com.fasterxml.jackson.databind.JsonNode; import com.enonic.xp.annotation.PublicApi; +import com.enonic.xp.core.internal.json.JsonHelper; import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.util.JsonHelper; @PublicApi public class IndexSettings { private final JsonNode jsonNode; + @Deprecated + public IndexSettings( final JsonNode resourceNode ) + { + this.jsonNode = resourceNode.deepCopy(); + } + + private IndexSettings( final JsonNode resourceNode, final boolean ignore) + { + this.jsonNode = resourceNode; + } + + @Deprecated public static IndexSettings from( final PropertyTree propertyTree ) { - return new IndexSettings( JsonHelper.from( propertyTree ) ); + return new IndexSettings( JsonHelper.from( propertyTree.toMap() ), false ); } + @Deprecated public static IndexSettings from( final URL url ) { - return new IndexSettings( JsonHelper.from( url ) ); + return new IndexSettings( JsonHelper.from( url ), false ); } + @Deprecated public static IndexSettings from( final String string ) { - return new IndexSettings( JsonHelper.from( string ) ); + return new IndexSettings( JsonHelper.from( string ), false ); } - public static IndexSettings from( final Map settings ) + public static IndexSettings from( final Map settings ) { - return new IndexSettings( JsonHelper.from( settings ) ); + return new IndexSettings( JsonHelper.from( settings ), false ); } - public IndexSettings( final JsonNode resourceNode ) + public Map getData() { - this.jsonNode = resourceNode; + return JsonHelper.toMap( jsonNode ); } + @Deprecated public JsonNode getNode() { return jsonNode; } + @Deprecated public String getAsString() { return this.jsonNode.toString(); } - } diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/status/JsonStatusReporter.java b/modules/core/core-api/src/main/java/com/enonic/xp/status/JsonStatusReporter.java index 36dbda9505b..269c9680a55 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/status/JsonStatusReporter.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/status/JsonStatusReporter.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.google.common.net.MediaType; +@Deprecated public abstract class JsonStatusReporter implements StatusReporter { diff --git a/modules/core/core-api/src/main/java/com/enonic/xp/util/JsonHelper.java b/modules/core/core-api/src/main/java/com/enonic/xp/util/JsonHelper.java index c59b8ef4951..72141901707 100644 --- a/modules/core/core-api/src/main/java/com/enonic/xp/util/JsonHelper.java +++ b/modules/core/core-api/src/main/java/com/enonic/xp/util/JsonHelper.java @@ -1,86 +1,41 @@ package com.enonic.xp.util; -import java.io.IOException; import java.net.URL; -import java.util.Iterator; import java.util.Map; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.node.ObjectNode; import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.json.ObjectMapperHelper; -public class JsonHelper +@Deprecated +public final class JsonHelper { - private static final ObjectMapper MAPPER = ObjectMapperHelper.create(). - enable( SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED ); + private JsonHelper() + { + } public static JsonNode merge( JsonNode mainNode, JsonNode updateNode ) { - Iterator fieldNames = updateNode.fieldNames(); - while ( fieldNames.hasNext() ) - { - String fieldName = fieldNames.next(); - JsonNode jsonNode = mainNode.get( fieldName ); - - final boolean fieldExistsAndIsEmbeddedObject = jsonNode != null && jsonNode.isObject(); - if ( fieldExistsAndIsEmbeddedObject ) - { - merge( jsonNode, updateNode.get( fieldName ) ); - } - else - { - if ( mainNode instanceof ObjectNode ) - { - JsonNode value = updateNode.get( fieldName ); - ( (ObjectNode) mainNode ).replace( fieldName, value ); - } - } - } - return mainNode; + return com.enonic.xp.core.internal.json.JsonHelper.merge( mainNode, updateNode ); } public static JsonNode from( final URL url ) { - if ( url == null ) - { - throw new IllegalArgumentException( "Cannot read JsonNode: URL not given" ); - } - - try - { - return MAPPER.readTree( url ); - } - catch ( IOException e ) - { - throw new IllegalArgumentException( "Cannot load settings from URL [" + url + "]", e ); - } + return com.enonic.xp.core.internal.json.JsonHelper.from( url ); } public static JsonNode from( final PropertyTree propertyTree ) { - final Map settingsMap = propertyTree.toMap(); - - return from( settingsMap ); + return from( propertyTree.toMap() ); } public static JsonNode from( final Map settings ) { - return MAPPER.valueToTree( settings ); + return com.enonic.xp.core.internal.json.JsonHelper.from( settings ); } public static JsonNode from( final String json ) { - try - { - return MAPPER.readTree( json ); - } - catch ( IOException e ) - { - throw new IllegalArgumentException( "Cannot serialize settings from string [" + json + "]", e ); - } + return com.enonic.xp.core.internal.json.JsonHelper.from( json ); } } diff --git a/modules/core/core-api/src/test/java/com/enonic/xp/data/PropertySetJsonTest.java b/modules/core/core-api/src/test/java/com/enonic/xp/data/PropertySetJsonTest.java index d241b473907..dc5c06f6f69 100644 --- a/modules/core/core-api/src/test/java/com/enonic/xp/data/PropertySetJsonTest.java +++ b/modules/core/core-api/src/test/java/com/enonic/xp/data/PropertySetJsonTest.java @@ -27,7 +27,7 @@ public void deserialize_serialization_of_Property() tree.addString( "myProp", "a" ); tree.addString( "myProp", "b" ); tree.addString( "myProp", "c" ); - PropertyArrayJson propertyArrayJson = PropertyArrayJson.toJson( tree.getRoot().getPropertyArray( "myProp" ) ); + PropertyArrayJson propertyArrayJson = PropertyTreeJson.propertyArrayToJson( tree.getRoot().getPropertyArray( "myProp" ) ); // serialize from object String expectedSerialization = jsonTestHelper.objectToString( propertyArrayJson ); @@ -53,7 +53,7 @@ public void deserialize_serialization_of_DataSet() dataSet.setDouble( "Double", 1.1 ); dataSet.setLocalDate( "DateMidnight", LocalDate.of( 2012, 12, 12 ) ); dataSet.setXml( "Xml", "
" ); - PropertyArrayJson dataSetJson = PropertyArrayJson.toJson( tree.getRoot().getPropertyArray( "mySet" ) ); + PropertyArrayJson dataSetJson = PropertyTreeJson.propertyArrayToJson( tree.getRoot().getPropertyArray( "mySet" ) ); // serialize from object String expectedSerialization = jsonTestHelper.objectToString( dataSetJson ); diff --git a/modules/core/core-api/src/test/java/com/enonic/xp/data/PropertyTreeTest.java b/modules/core/core-api/src/test/java/com/enonic/xp/data/PropertyTreeTest.java index ab9e2faa4fe..0b1a6d69006 100644 --- a/modules/core/core-api/src/test/java/com/enonic/xp/data/PropertyTreeTest.java +++ b/modules/core/core-api/src/test/java/com/enonic/xp/data/PropertyTreeTest.java @@ -6,8 +6,11 @@ import java.time.LocalTime; import java.util.ArrayList; import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import org.junit.jupiter.api.Test; @@ -16,12 +19,15 @@ import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; +import com.enonic.xp.node.NodeId; import com.enonic.xp.support.SerializableUtils; import com.enonic.xp.util.BinaryReference; import com.enonic.xp.util.GeoPoint; import com.enonic.xp.util.Link; import com.enonic.xp.util.Reference; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.withPrecision; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -815,6 +821,65 @@ private PropertyTree createTreeWithAllTypes() } + @Test + public void fromMap() + { + final HashMap map = new HashMap<>(); + map.put( "myString", "a" ); + map.put( "myDoable", 1.1 ); + map.put("myFloat", 1.1f); + map.put( "myInt", 1 ); + map.put( "myLong", 1L ); + map.put( "myByte", (byte) 1 ); + map.put( "myShort", (short) 1 ); + map.put( "myBoolean", true ); + map.put( "myNull", null ); + map.put( "myList", List.of( "a", "b" ) ); + map.put( "myMap", Map.of( "a", "b" ) ); + map.put( "myMapMap", Map.of( "a", Map.of("k", "v") ) ); + map.put( "mySet", Set.of( "a", "b" ) ); + map.put( "myEmptyList", List.of() ); + map.put( "myEmptyMap", Map.of() ); + map.put( "myGeoPoint", GeoPoint.from( "0,1" )); + map.put( "myInstant", Instant.parse( "2018-01-01T00:00:00Z" ) ); + map.put( "myDate", Date.from( Instant.parse( "2018-01-01T00:00:00Z" ) ) ); + map.put( "myLocalDate", LocalDate.parse( "2018-01-01" ) ); + map.put( "myLocalDateTime", LocalDate.parse( "2018-01-01" ).atStartOfDay() ); + map.put( "myLocalTime", LocalDate.parse( "2018-01-01" ).atStartOfDay().toLocalTime() ); + map.put( "myReference", Reference.from( "nodeId" ) ); + map.put( "myBinaryReference", BinaryReference.from( "binaryReference" ) ); + map.put( "myLink", Link.from( "/link" ) ); + map.put( "myObject", NodeId.from( "becomeString") ); + + final PropertyTree result = PropertyTree.fromMap( map ); + + assertEquals( "a", result.getString( "myString" ) ); + assertEquals( 1.1D, result.getDouble( "myDoable" ) ); + assertThat( result.getDouble( "myFloat" ) ).isEqualTo(1.1, withPrecision(0.001)); + assertEquals( 1L, result.getLong( "myInt" ) ); + assertEquals( 1L, result.getLong( "myLong" ) ); + assertEquals( 1L, result.getLong( "myByte" ) ); + assertEquals( 1L, result.getLong( "myShort" ) ); + assertTrue( result.getBoolean( "myBoolean" ) ); + assertNull( result.getString( "myNull" ) ); + assertEquals( "a", result.getString( "myList[0]" ) ); + assertEquals( "b", result.getString( "myList[1]" ) ); + assertEquals( "b", result.getString( "myMap.a" ) ); + assertEquals( "v", result.getString( "myMapMap.a.k" ) ); + assertThat( result.getStrings( "mySet" ) ).containsExactlyInAnyOrder( "a", "b" ); + assertThat( result.getStrings( "myEmptyList" ) ).isEmpty(); + assertThat( result.getSet( "myEmptyMap" ).getProperties() ).isEmpty(); + assertEquals( GeoPoint.from( "0,1" ), result.getGeoPoint( "myGeoPoint" ) ); + assertEquals( Instant.parse( "2018-01-01T00:00:00Z" ), result.getInstant( "myInstant" ) ); + assertEquals( Instant.parse( "2018-01-01T00:00:00Z" ) , result.getInstant( "myDate" ) ); + assertEquals( LocalDate.parse( "2018-01-01" ), result.getLocalDate( "myLocalDate" ) ); + assertEquals( LocalDate.parse( "2018-01-01" ).atStartOfDay(), result.getLocalDateTime( "myLocalDateTime" ) ); + assertEquals( LocalDate.parse( "2018-01-01" ).atStartOfDay().toLocalTime(), result.getLocalTime( "myLocalTime" ) ); + assertEquals( Reference.from( "nodeId" ), result.getReference( "myReference" ) ); + assertEquals( BinaryReference.from( "binaryReference" ), result.getBinaryReference( "myBinaryReference" ) ); + assertEquals( Link.from( "/link" ), result.getLink( "myLink" ) ); + assertEquals( "becomeString", result.getString( "myObject" ) ); + } } diff --git a/modules/core/core-api/src/test/java/com/enonic/xp/json/JsonToPropertyTreeTranslatorTest.java b/modules/core/core-api/src/test/java/com/enonic/xp/json/JsonToPropertyTreeTranslatorTest.java deleted file mode 100644 index 4a66086cc1f..00000000000 --- a/modules/core/core-api/src/test/java/com/enonic/xp/json/JsonToPropertyTreeTranslatorTest.java +++ /dev/null @@ -1,216 +0,0 @@ -package com.enonic.xp.json; - -import java.net.URL; - -import org.junit.jupiter.api.Test; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import com.enonic.xp.data.Property; -import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.data.ValueTypes; -import com.enonic.xp.form.Form; -import com.enonic.xp.form.FormItemSet; -import com.enonic.xp.form.FormOptionSet; -import com.enonic.xp.form.FormOptionSetOption; -import com.enonic.xp.form.Input; -import com.enonic.xp.inputtype.InputTypeName; -import com.enonic.xp.inputtype.InputTypeProperty; -import com.enonic.xp.schema.content.ContentTypeName; -import com.enonic.xp.schema.relationship.RelationshipTypeName; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -public class JsonToPropertyTreeTranslatorTest -{ - private static final ObjectMapper MAPPER = new ObjectMapper(); - - @Test - public void all_input_types() - throws Exception - { - final JsonNode node = loadJson( "allInputTypes" ); - final PropertyTree data = new JsonToPropertyTreeTranslator( createFormForAllInputTypes(), true ).translate( node ); - - final Property media = data.getProperty( "media" ); - assertNotNull( media ); - assertEquals( ValueTypes.PROPERTY_SET.getName(), media.getType().getName() ); - } - - @Test - public void map_array_values() - throws Exception - { - final JsonNode node = loadJson( "allInputTypes" ); - - final PropertyTree data = new JsonToPropertyTreeTranslator( null, false ).translate( node ); - - final Property myArray = data.getProperty( "stringArray" ); - assertNotNull( myArray ); - assertEquals( ValueTypes.STRING.getName(), myArray.getType().getName() ); - - final Property myArray0 = data.getProperty( "stringArray[0]" ); - assertNotNull( myArray0 ); - - final Property myArray1 = data.getProperty( "stringArray[1]" ); - assertNotNull( myArray1 ); - - final Property myArray2 = data.getProperty( "stringArray[2]" ); - assertNotNull( myArray2 ); - } - - @Test - public void map_dateTime() - throws Exception - { - final JsonNode node = loadJson( "allInputTypes" ); - - final PropertyTree data = new JsonToPropertyTreeTranslator( createFormForAllInputTypes(), false ).translate( node ); - - final Property noTimezone = data.getProperty( "localDateTime" ); - assertNotNull( noTimezone ); - assertEquals( ValueTypes.LOCAL_DATE_TIME.getName(), noTimezone.getType().getName() ); - - final Property timezoned = data.getProperty( "dateTime" ); - assertNotNull( timezoned ); - assertEquals( ValueTypes.DATE_TIME.getName(), timezoned.getType().getName() ); - } - - private JsonNode loadJson( final String name ) - throws Exception - { - final String resource = "/" + getClass().getName().replace( '.', '/' ) + "-" + name + ".json"; - final URL url = getClass().getResource( resource ); - - assertNotNull( url, "File [" + resource + "] not found" ); - return MAPPER.readTree( url ); - } - - private Form createFormForAllInputTypes() - { - final FormItemSet set = FormItemSet.create(). - name( "set" ). - addFormItem( Input.create(). - name( "setString" ). - label( "String" ). - inputType( InputTypeName.TEXT_LINE ). - build() ). - addFormItem( Input.create(). - name( "setDouble" ). - label( "Double" ). - inputType( InputTypeName.DOUBLE ). - build() ). - build(); - - final FormOptionSet formOptionSet = FormOptionSet.create(). - name( "myOptionSet" ). - label( "My option set" ). - addOptionSetOption( FormOptionSetOption.create().name( "myOptionSetOption1" ).label( "option label1" ). - addFormItem( - Input.create().name( "myTextLine1" ).label( "myTextLine1" ).inputType( InputTypeName.TEXT_LINE ).build() ).build() ). - addOptionSetOption( FormOptionSetOption.create().name( "myOptionSetOption2" ).label( "option label2" ). - addFormItem( - Input.create().name( "myTextLine2" ).label( "myTextLine2" ).inputType( InputTypeName.TEXT_LINE ).build() ).build() ). - build(); - - return Form.create(). - addFormItem( Input.create(). - name( "textLine" ). - label( "Textline" ). - inputType( InputTypeName.TEXT_LINE ). - build() ). - addFormItem( Input.create(). - name( "stringArray" ). - label( "String array" ). - inputType( InputTypeName.TEXT_LINE ). - build() ). - addFormItem( Input.create(). - name( "double" ). - label( "Double" ). - inputType( InputTypeName.DOUBLE ). - build() ). - addFormItem( Input.create(). - name( "long" ). - label( "Long" ). - inputType( InputTypeName.LONG ). - build() ). - addFormItem( Input.create(). - name( "comboBox" ). - label( "Combobox" ). - inputType( InputTypeName.COMBO_BOX ). - inputTypeProperty( InputTypeProperty.create( "option", "label1" ).attribute( "value", "value1" ).build() ). - inputTypeProperty( InputTypeProperty.create( "option", "label2" ).attribute( "value", "value2" ).build() ). - build() ). - addFormItem( Input.create(). - name( "checkbox" ). - label( "Checkbox" ). - inputType( InputTypeName.CHECK_BOX ). - build() ). - addFormItem( Input.create(). - name( "tag" ). - label( "Tag" ). - inputType( InputTypeName.TAG ). - build() ). - addFormItem( Input.create(). - name( "contentSelector" ). - label( "Content selector" ). - inputType( InputTypeName.CONTENT_SELECTOR ). - inputTypeProperty( InputTypeProperty.create( "allowContentType", ContentTypeName.folder().toString() ).build() ). - inputTypeProperty( InputTypeProperty.create( "relationshipType", RelationshipTypeName.REFERENCE.toString() ).build() ). - build() ). - addFormItem( Input.create(). - name( "contentTypeFilter" ). - label( "Content type filter" ). - inputType( InputTypeName.CONTENT_TYPE_FILTER ). - build() ). - addFormItem( Input.create(). - name( "siteConfigurator" ). - inputType( InputTypeName.SITE_CONFIGURATOR ). - label( "Site configurator" ). - build() ). - addFormItem( Input.create(). - name( "date" ). - label( "Date" ). - inputType( InputTypeName.DATE ). - build() ). - addFormItem( Input.create(). - name( "time" ). - label( "Time" ). - inputType( InputTypeName.TIME ). - build() ). - addFormItem( Input.create(). - name( "geoPoint" ). - label( "Geo point" ). - inputType( InputTypeName.GEO_POINT ). - build() ). - addFormItem( Input.create(). - name( "htmlArea" ). - label( "Html area" ). - inputType( InputTypeName.HTML_AREA ). - build() ). - addFormItem( Input.create(). - name( "localDateTime" ). - label( "Local datetime" ). - inputType( InputTypeName.DATE_TIME ). - inputTypeProperty( InputTypeProperty.create( "timezone", "false" ).build() ). - build() ). - addFormItem( Input.create(). - name( "dateTime" ). - label( "Datetime" ). - inputType( InputTypeName.DATE_TIME ). - inputTypeProperty( InputTypeProperty.create( "timezone", "true" ).build() ). - build() ). - addFormItem( Input.create(). - name( "media" ). - label( "Image Uploader" ). - inputType( InputTypeName.IMAGE_UPLOADER ). - build() ). - addFormItem( set ). - addFormItem( formOptionSet ). - build(); - } - -} - diff --git a/modules/core/core-api/src/testFixtures/java/com/enonic/xp/status/JsonStatusReporterTest.java b/modules/core/core-api/src/testFixtures/java/com/enonic/xp/status/JsonStatusReporterTest.java deleted file mode 100644 index 0ef57cccd72..00000000000 --- a/modules/core/core-api/src/testFixtures/java/com/enonic/xp/status/JsonStatusReporterTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.enonic.xp.status; - -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.SerializationFeature; - -public abstract class JsonStatusReporterTest -{ - private static final ObjectMapper MAPPER = new ObjectMapper(). - disable( SerializationFeature.FAIL_ON_EMPTY_BEANS ). - enable( MapperFeature.SORT_PROPERTIES_ALPHABETICALLY ). - setSerializationInclusion( JsonInclude.Include.ALWAYS ); - - private static final ObjectReader OBJECT_READER = MAPPER.reader(); - - private static final ObjectWriter OBJECT_WRITER = MAPPER.writerWithDefaultPrettyPrinter(); - - protected String readFromFile( final String fileName ) - throws Exception - { - final InputStream stream = - Objects.requireNonNull( getClass().getResourceAsStream( fileName ), "Resource file [" + fileName + "] not found" ); - try (stream) - { - return new String( stream.readAllBytes(), StandardCharsets.UTF_8 ); - } - } - - protected JsonNode parseJson( final String json ) - throws Exception - { - return OBJECT_READER.readTree( json ); - } - - protected String toJson( final Object value ) - throws Exception - { - return OBJECT_WRITER.writeValueAsString( value ); - } -} diff --git a/modules/core/core-api/src/testFixtures/java/com/enonic/xp/support/JsonTestHelper.java b/modules/core/core-api/src/testFixtures/java/com/enonic/xp/support/JsonTestHelper.java index 0030fa117a2..fc7a7d4e84d 100644 --- a/modules/core/core-api/src/testFixtures/java/com/enonic/xp/support/JsonTestHelper.java +++ b/modules/core/core-api/src/testFixtures/java/com/enonic/xp/support/JsonTestHelper.java @@ -3,14 +3,12 @@ import java.io.IOException; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; -import com.enonic.xp.json.ObjectMapperHelper; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -39,7 +37,7 @@ public JsonNode loadTestJson( final String fileName ) return stringToJson( resourceTestHelper.loadTestFile( fileName ) ); } - public String jsonToString( final JsonNode value ) + public String objectToString( final Object value ) { try { @@ -51,11 +49,11 @@ public String jsonToString( final JsonNode value ) } } - public String objectToString( final Object value ) + public JsonNode objectToJson( final Object value ) { try { - return OBJECT_WRITER.writeValueAsString( value ); + return MAPPER.valueToTree( value ); } catch ( Exception e ) { @@ -63,26 +61,23 @@ public String objectToString( final Object value ) } } - public JsonNode objectToJson( final Object value ) + public JsonNode stringToJson( final String jsonString ) { try { - return MAPPER.valueToTree( value ); + return MAPPER.readTree( jsonString ); } - catch ( Exception e ) + catch ( IOException e ) { throw new RuntimeException( e ); } } - - public JsonNode stringToJson( final String jsonString ) + public JsonNode bytesToJson( final byte[] jsonBytes ) { try { - final JsonFactory factory = MAPPER.getFactory(); - final JsonParser parser = factory.createParser( jsonString ); - return parser.readValueAsTree(); + return MAPPER.readTree( jsonBytes ); } catch ( IOException e ) { @@ -92,6 +87,6 @@ public JsonNode stringToJson( final String jsonString ) public void assertJsonEquals( final JsonNode expectedJson, final JsonNode actualJson ) { - assertEquals( jsonToString( expectedJson ), jsonToString( actualJson ) ); + assertEquals( objectToString( expectedJson ), objectToString( actualJson ) ); } } diff --git a/modules/core/core-cluster/src/main/java/com/enonic/xp/cluster/impl/report/ClusterManagerReporter.java b/modules/core/core-cluster/src/main/java/com/enonic/xp/cluster/impl/report/ClusterManagerReporter.java index a1db59d088c..abdab39ba35 100644 --- a/modules/core/core-cluster/src/main/java/com/enonic/xp/cluster/impl/report/ClusterManagerReporter.java +++ b/modules/core/core-cluster/src/main/java/com/enonic/xp/cluster/impl/report/ClusterManagerReporter.java @@ -1,29 +1,43 @@ package com.enonic.xp.cluster.impl.report; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; import com.enonic.xp.cluster.ClusterManager; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) public class ClusterManagerReporter - extends JsonStatusReporter + implements StatusReporter { - private ClusterManager clusterManager; + private final ClusterManager clusterManager; + + @Activate + public ClusterManagerReporter( @Reference final ClusterManager clusterManager ) + { + this.clusterManager = clusterManager; + } @Override - public JsonNode getReport() + public final MediaType getMediaType() { - return ClusterManagerReport.create(). - clusters( clusterManager.getClusters() ). - clusterState( clusterManager.getClusterState() ). - build(). - toJson(); + return MediaType.JSON_UTF_8; + } + + @Override + public final void report( final OutputStream outputStream ) + throws IOException + { + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); } @Override @@ -32,10 +46,12 @@ public String getName() return "cluster.manager"; } - @SuppressWarnings("WeakerAccess") - @Reference - public void setClusterManager( final ClusterManager clusterManager ) + private JsonNode getReport() { - this.clusterManager = clusterManager; + return ClusterManagerReport.create(). + clusters( clusterManager.getClusters() ). + clusterState( clusterManager.getClusterState() ). + build(). + toJson(); } } diff --git a/modules/core/core-cluster/src/test/java/com/enonic/xp/cluster/impl/report/ClusterManagerReporterTest.java b/modules/core/core-cluster/src/test/java/com/enonic/xp/cluster/impl/report/ClusterManagerReporterTest.java index 43e2956af29..fb74cbad228 100644 --- a/modules/core/core-cluster/src/test/java/com/enonic/xp/cluster/impl/report/ClusterManagerReporterTest.java +++ b/modules/core/core-cluster/src/test/java/com/enonic/xp/cluster/impl/report/ClusterManagerReporterTest.java @@ -1,12 +1,13 @@ package com.enonic.xp.cluster.impl.report; +import java.io.ByteArrayOutputStream; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; import com.enonic.xp.cluster.Cluster; import com.enonic.xp.cluster.ClusterHealth; @@ -23,6 +24,8 @@ public class ClusterManagerReporterTest { + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + private ClusterManager clusterManager; @BeforeEach @@ -48,15 +51,15 @@ public void setUp() public void report() throws Exception { + final ClusterManagerReporter reporter = new ClusterManagerReporter(this.clusterManager ); - final ClusterManagerReporter reporter = new ClusterManagerReporter(); - reporter.setClusterManager( this.clusterManager ); - - final JsonNode result = reporter.getReport(); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); assertEquals( "cluster.manager", reporter.getName() ); - - assertJson( "report.json", result ); + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( "report.json" ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); } private Cluster createCluster( final ClusterId cluster1Id ) @@ -70,11 +73,4 @@ private Cluster createCluster( final ClusterId cluster1Id ) build() ). build(); } - - private void assertJson( final String fileName, final JsonNode json ) - { - final JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); - final JsonNode jsonFromFile = jsonTestHelper.loadTestJson( fileName ); - jsonTestHelper.assertJsonEquals( jsonFromFile, json ); - } } diff --git a/modules/core/core-content/src/main/java/com/enonic/xp/core/impl/content/serializer/ContentDataSerializer.java b/modules/core/core-content/src/main/java/com/enonic/xp/core/impl/content/serializer/ContentDataSerializer.java index 308c5ca07bc..d45e5192de5 100644 --- a/modules/core/core-content/src/main/java/com/enonic/xp/core/impl/content/serializer/ContentDataSerializer.java +++ b/modules/core/core-content/src/main/java/com/enonic/xp/core/impl/content/serializer/ContentDataSerializer.java @@ -30,11 +30,11 @@ import com.enonic.xp.content.ValidationErrorCode; import com.enonic.xp.content.ValidationErrors; import com.enonic.xp.content.WorkflowInfo; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.data.PropertyPath; import com.enonic.xp.data.PropertySet; import com.enonic.xp.data.PropertyTree; import com.enonic.xp.icon.Thumbnail; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.node.NodeId; import com.enonic.xp.page.Page; import com.enonic.xp.project.ProjectName; diff --git a/modules/core/core-elasticsearch/src/main/java/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporter.java b/modules/core/core-elasticsearch/src/main/java/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporter.java index 7f2e1a9c0d3..ae8cf86080a 100644 --- a/modules/core/core-elasticsearch/src/main/java/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporter.java +++ b/modules/core/core-elasticsearch/src/main/java/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporter.java @@ -1,20 +1,33 @@ package com.enonic.xp.elasticsearch.impl.status.cluster; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) public final class ElasticsearchClusterReporter - extends JsonStatusReporter + implements StatusReporter { - private ClusterStateProvider clusterStateProvider; + private final ClusterStateProvider clusterStateProvider; + + private final ClusterHealthProvider clusterHealthProvider; - private ClusterHealthProvider clusterHealthProvider; + @Activate + public ElasticsearchClusterReporter( @Reference final ClusterStateProvider clusterStateProvider, + @Reference final ClusterHealthProvider clusterHealthProvider ) + { + this.clusterStateProvider = clusterStateProvider; + this.clusterHealthProvider = clusterHealthProvider; + } @Override public String getName() @@ -23,27 +36,25 @@ public String getName() } @Override - public JsonNode getReport() + public MediaType getMediaType() { - final ElasticsearchClusterReport elasticsearchClusterReport = ElasticsearchClusterReport.create(). - clusterState( clusterStateProvider.getInfo() ). - clusterHealth( clusterHealthProvider.getInfo() ). - build(); - - return elasticsearchClusterReport.toJson(); + return MediaType.JSON_UTF_8; } - @SuppressWarnings("WeakerAccess") - @Reference - public void setClusterStateProvider( final ClusterStateProvider clusterStateProvider ) + @Override + public void report( final OutputStream outputStream ) + throws IOException { - this.clusterStateProvider = clusterStateProvider; + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); } - @SuppressWarnings("WeakerAccess") - @Reference - public void setClusterHealthProvider( final ClusterHealthProvider clusterHealthProvider ) + private JsonNode getReport() { - this.clusterHealthProvider = clusterHealthProvider; + final ElasticsearchClusterReport elasticsearchClusterReport = ElasticsearchClusterReport.create(). + clusterState( clusterStateProvider.getInfo() ). + clusterHealth( clusterHealthProvider.getInfo() ). + build(); + + return elasticsearchClusterReport.toJson(); } } diff --git a/modules/core/core-elasticsearch/src/main/java/com/enonic/xp/elasticsearch/impl/status/index/IndexReporter.java b/modules/core/core-elasticsearch/src/main/java/com/enonic/xp/elasticsearch/impl/status/index/IndexReporter.java index 3b3e3f5a8eb..278e54e9282 100644 --- a/modules/core/core-elasticsearch/src/main/java/com/enonic/xp/elasticsearch/impl/status/index/IndexReporter.java +++ b/modules/core/core-elasticsearch/src/main/java/com/enonic/xp/elasticsearch/impl/status/index/IndexReporter.java @@ -1,36 +1,53 @@ package com.enonic.xp.elasticsearch.impl.status.index; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) public class IndexReporter - extends JsonStatusReporter + implements StatusReporter { - private IndexReportProvider indexReportProvider; + private final IndexReportProvider indexReportProvider; + + @Activate + public IndexReporter( @Reference final IndexReportProvider indexReportProvider ) + { + this.indexReportProvider = indexReportProvider; + } @Override - public String getName() + public MediaType getMediaType() { - return "index"; + return MediaType.JSON_UTF_8; } @Override - public JsonNode getReport() + public void report( final OutputStream outputStream ) + throws IOException { - return indexReportProvider.getInfo(). - toJson(); + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); } - @Reference - public void setIndexReportProvider( final IndexReportProvider indexReportProvider ) + @Override + public String getName() { - this.indexReportProvider = indexReportProvider; + return "index"; + } + + private JsonNode getReport() + { + return indexReportProvider.getInfo(). + toJson(); } } diff --git a/modules/core/core-elasticsearch/src/test/java/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest.java b/modules/core/core-elasticsearch/src/test/java/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest.java index de89b97cf83..fb015dfe36e 100644 --- a/modules/core/core-elasticsearch/src/test/java/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest.java +++ b/modules/core/core-elasticsearch/src/test/java/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest.java @@ -1,7 +1,7 @@ package com.enonic.xp.elasticsearch.impl.status.cluster; +import java.io.ByteArrayOutputStream; import java.util.HashMap; -import java.util.List; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; @@ -20,18 +20,17 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; +import com.google.common.net.MediaType; -import com.enonic.xp.status.JsonStatusReporterTest; +import com.enonic.xp.support.JsonTestHelper; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertIterableEquals; public class ElasticsearchClusterReporterTest - extends JsonStatusReporterTest { - private final ElasticsearchClusterReporter clusterReporter = new ElasticsearchClusterReporter(); + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + + private ElasticsearchClusterReporter reporter; private ClusterState clusterState; @@ -77,15 +76,14 @@ public void setup() clusterStateProvider.setClusterAdminClient( clusterAdminClient ); clusterStateProvider.setClusterService( clusterService ); - clusterReporter.setClusterHealthProvider( clusterHealthProvider ); - clusterReporter.setClusterStateProvider( clusterStateProvider ); + reporter = new ElasticsearchClusterReporter( clusterStateProvider, clusterHealthProvider); } @Test public void assertName() throws Exception { - assertEquals( "cluster.elasticsearch", clusterReporter.getName() ); + assertEquals( "cluster.elasticsearch", reporter.getName() ); } @Test @@ -104,7 +102,7 @@ public void cluster_with_one_node() Mockito.when( clusterState.getNodes() ).thenReturn( nodes ); Mockito.when( this.clusterService.localNode() ).thenReturn( node1 ); - assertJson( "cluster_with_one_node.json", clusterReporter.getReport() ); + assertJson( "cluster_with_one_node.json" ); } @Test @@ -113,7 +111,7 @@ public void testClusterState_Exception() { Mockito.when( clusterStateInfo.actionGet() ).thenThrow( new ElasticsearchException( "cluster state exception" ) ); - assertJson( "cluster_state_exception.json", clusterReporter.getReport() ); + assertJson( "cluster_state_exception.json" ); } @Test @@ -134,51 +132,19 @@ public void testClusterHealth_Exception() Mockito.when( clusterState.getNodes() ).thenReturn( nodes ); Mockito.when( this.clusterService.localNode() ).thenReturn( node1 ); - assertJson( "cluster_health_info_exception.json", clusterReporter.getReport() ); - } - - @Test - public void cluster_with_two_nodes() - throws Exception - { - final DiscoveryNode node1 = - new DiscoveryNode( "nodeName1", "nodeId1", "hostName1", "hostAddress1", new LocalTransportAddress( "10.10.10.1" ), - new HashMap<>(), Version.fromString( "1.0.0" ) ); - - final DiscoveryNode node2 = - new DiscoveryNode( "nodeName2", "nodeId2", "hostName2", "hostAddress2", new LocalTransportAddress( "10.10.10.2" ), - new HashMap<>(), Version.fromString( "1.0.0" ) ); - - final DiscoveryNodes nodes = DiscoveryNodes.builder(). - put( node1 ). - put( node2 ). - localNodeId( node1.getId() ). - masterNodeId( node2.getId() ). - build(); - - Mockito.when( clusterState.getNodes() ).thenReturn( nodes ); - Mockito.when( this.clusterService.localNode() ).thenReturn( node1 ); - - final JsonNode expectedReport = parseJson( readFromFile( "cluster_with_two_nodes.json" ) ); - final JsonNode report = clusterReporter.getReport(); - assertEquals( expectedReport.get( "name" ), report.get( "name" ) ); - assertEquals( expectedReport.get( "localNode" ), report.get( "localNode" ) ); - assertEquals( expectedReport.get( "state" ), report.get( "state" ) ); - final ArrayNode expectedMembers = (ArrayNode) expectedReport.get( "members" ); - final ArrayNode members = (ArrayNode) report.get( "members" ); - assertIterableEquals( List.of( members.get( 0 ), members.get( 1 ) ), expectedMembers ); + assertJson( "cluster_health_info_exception.json" ); } - - private void assertJson( final String fileName, final JsonNode actualNode ) + private void assertJson( final String fileName ) throws Exception { - final JsonNode expectedNode = parseJson( readFromFile( fileName ) ); + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); - final String expectedStr = toJson( expectedNode ); - final String actualStr = toJson( actualNode ); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); - assertEquals( expectedStr, actualStr ); + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( fileName ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); } } diff --git a/modules/core/core-elasticsearch/src/test/java/com/enonic/xp/elasticsearch/impl/status/index/IndexReporterTest.java b/modules/core/core-elasticsearch/src/test/java/com/enonic/xp/elasticsearch/impl/status/index/IndexReporterTest.java index b2b82ea8e04..fcd7f6de414 100644 --- a/modules/core/core-elasticsearch/src/test/java/com/enonic/xp/elasticsearch/impl/status/index/IndexReporterTest.java +++ b/modules/core/core-elasticsearch/src/test/java/com/enonic/xp/elasticsearch/impl/status/index/IndexReporterTest.java @@ -1,5 +1,6 @@ package com.enonic.xp.elasticsearch.impl.status.index; +import java.io.ByteArrayOutputStream; import java.util.Arrays; import org.elasticsearch.action.ActionListener; @@ -19,23 +20,23 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; -import com.enonic.xp.status.JsonStatusReporterTest; +import com.enonic.xp.support.JsonTestHelper; import static org.junit.jupiter.api.Assertions.assertEquals; public class IndexReporterTest - extends JsonStatusReporterTest { + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + private ClusterAdminClient clusterAdminClient; - private IndexReporter indexReporter; + private IndexReporter reporter; @BeforeEach public void setUp() { - clusterAdminClient = Mockito.mock( ClusterAdminClient.class ); final AdminClient adminClient = Mockito.mock( AdminClient.class ); @@ -44,8 +45,7 @@ public void setUp() final IndexReportProvider indexReportProvider = new IndexReportProvider(); indexReportProvider.setAdminClient( adminClient ); - indexReporter = new IndexReporter(); - indexReporter.setIndexReportProvider( indexReportProvider ); + reporter = new IndexReporter( indexReportProvider ); } @Test @@ -89,9 +89,8 @@ public void testGetReport() } ).when( clusterAdminClient ). execute( Mockito.any(), Mockito.any(), Mockito.any() ); - assertEquals( "index", indexReporter.getName() ); - final JsonNode report = indexReporter.getReport(); - assertEquals( parseJson( readFromFile( "index_report.json" ) ), report ); + assertEquals( "index", reporter.getName() ); + assertJson( "index_report.json" ); } @Test @@ -101,8 +100,20 @@ public void testGetReportWithError() Mockito.doAnswer( invocation -> null ). when( clusterAdminClient ). state( Mockito.any(), Mockito.any() ); - assertEquals( "index", indexReporter.getName() ); - final JsonNode report = indexReporter.getReport(); - assertEquals( parseJson( readFromFile( "index_report_failed.json" ) ), report ); + assertEquals( "index", reporter.getName() ); + assertJson( "index_report_failed.json" ); } + + private void assertJson( final String fileName ) + throws Exception + { + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); + + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); + + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( fileName ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); + } + } diff --git a/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/cluster_health_info_exception.json b/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest-cluster_health_info_exception.json similarity index 100% rename from modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/cluster_health_info_exception.json rename to modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest-cluster_health_info_exception.json diff --git a/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/cluster_state_exception.json b/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest-cluster_state_exception.json similarity index 100% rename from modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/cluster_state_exception.json rename to modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest-cluster_state_exception.json diff --git a/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/cluster_with_one_node.json b/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest-cluster_with_one_node.json similarity index 100% rename from modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/cluster_with_one_node.json rename to modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest-cluster_with_one_node.json diff --git a/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/local_node_info_exception.json b/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest-local_node_info_exception.json similarity index 100% rename from modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/local_node_info_exception.json rename to modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/ElasticsearchClusterReporterTest-local_node_info_exception.json diff --git a/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/cluster_with_two_nodes.json b/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/cluster_with_two_nodes.json deleted file mode 100644 index 1910eafcfde..00000000000 --- a/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/cluster/cluster_with_two_nodes.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "clusterName", - "localNode": { - "isMaster": false, - "id": "nodeId1", - "hostName": "hostName1", - "version": "1.0.0", - "numberOfNodesSeen": 2 - }, - "members": [ - { - "isMaster": false, - "id": "nodeId1", - "hostName": "hostName1", - "version": "1.0.0", - "address": "local[10.10.10.1]", - "name": "nodeName1", - "isDataNode": true, - "isClientNode": false - }, - { - "isMaster": true, - "id": "nodeId2", - "hostName": "hostName2", - "version": "1.0.0", - "address": "local[10.10.10.2]", - "name": "nodeName2", - "isDataNode": true, - "isClientNode": false - } - ], - "state": "GREEN" -} \ No newline at end of file diff --git a/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/index/index_report.json b/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/index/IndexReporterTest-index_report.json similarity index 100% rename from modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/index/index_report.json rename to modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/index/IndexReporterTest-index_report.json diff --git a/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/index/index_report_failed.json b/modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/index/IndexReporterTest-index_report_failed.json similarity index 100% rename from modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/index/index_report_failed.json rename to modules/core/core-elasticsearch/src/test/resources/com/enonic/xp/elasticsearch/impl/status/index/IndexReporterTest-index_report_failed.json diff --git a/modules/core/core-hazelcast/src/main/java/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporter.java b/modules/core/core-hazelcast/src/main/java/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporter.java index 121beffab7d..1a1429b68a8 100644 --- a/modules/core/core-hazelcast/src/main/java/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporter.java +++ b/modules/core/core-hazelcast/src/main/java/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporter.java @@ -1,5 +1,8 @@ package com.enonic.xp.core.impl.hazelcast.status.cluster; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.util.Set; import org.osgi.service.component.annotations.Activate; @@ -7,16 +10,16 @@ import org.osgi.service.component.annotations.Reference; import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; import com.hazelcast.core.Cluster; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.Member; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) public class HazelcastClusterReporter - extends JsonStatusReporter + implements StatusReporter { private final HazelcastInstance hazelcastInstance; @@ -33,7 +36,19 @@ public String getName() } @Override - public JsonNode getReport() + public MediaType getMediaType() + { + return MediaType.JSON_UTF_8; + } + + @Override + public void report( final OutputStream outputStream ) + throws IOException + { + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); + } + + private JsonNode getReport() { final Cluster cluster = hazelcastInstance.getCluster(); diff --git a/modules/core/core-hazelcast/src/main/java/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporter.java b/modules/core/core-hazelcast/src/main/java/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporter.java index cae2c2c4009..5ba2dc7490a 100644 --- a/modules/core/core-hazelcast/src/main/java/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporter.java +++ b/modules/core/core-hazelcast/src/main/java/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporter.java @@ -1,5 +1,8 @@ package com.enonic.xp.core.impl.hazelcast.status.objects; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.concurrent.TimeUnit; @@ -10,6 +13,7 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; import com.hazelcast.core.DistributedObject; import com.hazelcast.core.DistributedObjectUtil; import com.hazelcast.core.HazelcastInstance; @@ -21,12 +25,11 @@ import com.hazelcast.scheduledexecutor.IScheduledExecutorService; import com.hazelcast.scheduledexecutor.ScheduledTaskHandler; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) public class HazelcastObjectsReporter - extends JsonStatusReporter + implements StatusReporter { private static final Logger LOG = LoggerFactory.getLogger( HazelcastObjectsReporter.class ); @@ -45,7 +48,19 @@ public String getName() } @Override - public JsonNode getReport() + public MediaType getMediaType() + { + return MediaType.JSON_UTF_8; + } + + @Override + public void report( final OutputStream outputStream ) + throws IOException + { + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); + } + + private JsonNode getReport() { final Collection distributedObjects = hazelcastInstance.getDistributedObjects(); final HazelcastObjectsReport.Builder builder = HazelcastObjectsReport.create(); diff --git a/modules/core/core-hazelcast/src/test/java/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporterTest.java b/modules/core/core-hazelcast/src/test/java/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporterTest.java index 9c7f3f28391..f00403566f7 100644 --- a/modules/core/core-hazelcast/src/test/java/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporterTest.java +++ b/modules/core/core-hazelcast/src/test/java/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporterTest.java @@ -1,5 +1,6 @@ package com.enonic.xp.core.impl.hazelcast.status.cluster; +import java.io.ByteArrayOutputStream; import java.util.LinkedHashSet; import java.util.List; @@ -9,7 +10,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; import com.hazelcast.cluster.ClusterState; import com.hazelcast.core.Cluster; import com.hazelcast.core.HazelcastInstance; @@ -18,7 +19,8 @@ import com.hazelcast.version.MemberVersion; import com.hazelcast.version.Version; -import com.enonic.xp.status.JsonStatusReporterTest; +import com.enonic.xp.status.StatusReporter; +import com.enonic.xp.support.JsonTestHelper; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.lenient; @@ -27,8 +29,9 @@ @ExtendWith(MockitoExtension.class) class HazelcastClusterReporterTest - extends JsonStatusReporterTest { + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + @Mock HazelcastInstance hazelcastInstance; @@ -70,17 +73,18 @@ void getReport() when( cluster.getMembers() ).thenReturn( new LinkedHashSet<>( List.of( member1, member2 ) ) ); //hazelcast always returns master first - assertJson( "hazelcast_cluster.json", hazelcastClusterReporter.getReport() ); + assertJson( "hazelcast_cluster.json", hazelcastClusterReporter ); } - private void assertJson( final String fileName, final JsonNode actualJson ) + private void assertJson( final String fileName, StatusReporter reporter ) throws Exception { - final JsonNode expectedNode = parseJson( readFromFile( fileName ) ); + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); - final String expectedStr = toJson( expectedNode ); - final String actualStr = toJson( actualJson ); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); - assertEquals( expectedStr, actualStr ); + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( fileName ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); } } diff --git a/modules/core/core-hazelcast/src/test/java/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporterTest.java b/modules/core/core-hazelcast/src/test/java/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporterTest.java index 7baa5437e65..e24a106bdc6 100644 --- a/modules/core/core-hazelcast/src/test/java/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporterTest.java +++ b/modules/core/core-hazelcast/src/test/java/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporterTest.java @@ -1,5 +1,6 @@ package com.enonic.xp.core.impl.hazelcast.status.objects; +import java.io.ByteArrayOutputStream; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -10,7 +11,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IExecutorService; import com.hazelcast.core.IMap; @@ -24,7 +25,8 @@ import com.hazelcast.scheduledexecutor.ScheduledTaskHandler; import com.hazelcast.scheduledexecutor.ScheduledTaskStatistics; -import com.enonic.xp.status.JsonStatusReporterTest; +import com.enonic.xp.status.StatusReporter; +import com.enonic.xp.support.JsonTestHelper; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.lenient; @@ -33,8 +35,9 @@ @ExtendWith(MockitoExtension.class) class HazelcastObjectsReporterTest - extends JsonStatusReporterTest { + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + @Mock HazelcastInstance hazelcastInstance; @@ -100,17 +103,18 @@ void getReport() when( hazelcastInstance.getDistributedObjects() ).thenReturn( List.of( map, queue, scheduledExecutorService, executorService, topic, lock ) ); - assertJson( "hazelcast_objects.json", hazelcastClusterReporter.getReport() ); + assertJson( "hazelcast_objects.json", hazelcastClusterReporter ); } - private void assertJson( final String fileName, final JsonNode actualJson ) + private void assertJson( final String fileName, StatusReporter reporter ) throws Exception { - final JsonNode expectedNode = parseJson( readFromFile( fileName ) ); + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); - final String expectedStr = toJson( expectedNode ); - final String actualStr = toJson( actualJson ); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); - assertEquals( expectedStr, actualStr ); + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( fileName ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); } } diff --git a/modules/core/core-hazelcast/src/test/resources/com/enonic/xp/core/impl/hazelcast/status/cluster/hazelcast_cluster.json b/modules/core/core-hazelcast/src/test/resources/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporterTest-hazelcast_cluster.json similarity index 100% rename from modules/core/core-hazelcast/src/test/resources/com/enonic/xp/core/impl/hazelcast/status/cluster/hazelcast_cluster.json rename to modules/core/core-hazelcast/src/test/resources/com/enonic/xp/core/impl/hazelcast/status/cluster/HazelcastClusterReporterTest-hazelcast_cluster.json diff --git a/modules/core/core-hazelcast/src/test/resources/com/enonic/xp/core/impl/hazelcast/status/objects/hazelcast_objects.json b/modules/core/core-hazelcast/src/test/resources/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporterTest-hazelcast_objects.json similarity index 100% rename from modules/core/core-hazelcast/src/test/resources/com/enonic/xp/core/impl/hazelcast/status/objects/hazelcast_objects.json rename to modules/core/core-hazelcast/src/test/resources/com/enonic/xp/core/impl/hazelcast/status/objects/HazelcastObjectsReporterTest-hazelcast_objects.json diff --git a/modules/core/core-internal/build.gradle b/modules/core/core-internal/build.gradle index e1b1066c2b7..67f03a1ca84 100644 --- a/modules/core/core-internal/build.gradle +++ b/modules/core/core-internal/build.gradle @@ -1,7 +1,9 @@ dependencies { api libs.osgi.core + api libs.jackson.databind compileOnlyApi libs.osgi.service.componentannotations implementation libs.jsoup + implementation libs.jackson.datatype.jsr310 implementation( libs.owaspsanitizer ) { exclude group: 'com.google.guava' diff --git a/modules/core/core-internal/src/main/java/com/enonic/xp/core/internal/json/JsonHelper.java b/modules/core/core-internal/src/main/java/com/enonic/xp/core/internal/json/JsonHelper.java new file mode 100644 index 00000000000..a3b49c2a46e --- /dev/null +++ b/modules/core/core-internal/src/main/java/com/enonic/xp/core/internal/json/JsonHelper.java @@ -0,0 +1,81 @@ +package com.enonic.xp.core.internal.json; + +import java.io.IOException; +import java.net.URL; +import java.util.Iterator; +import java.util.Map; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public final class JsonHelper +{ + private static final ObjectMapper MAPPER = ObjectMapperHelper.create(). + enable( SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED ); + + private JsonHelper() + { + } + + public static JsonNode merge( JsonNode mainNode, JsonNode updateNode ) + { + Iterator fieldNames = updateNode.fieldNames(); + while ( fieldNames.hasNext() ) + { + String fieldName = fieldNames.next(); + JsonNode jsonNode = mainNode.get( fieldName ); + + if ( jsonNode instanceof ObjectNode ) + { + merge( jsonNode, updateNode.get( fieldName ) ); + } + else if ( mainNode instanceof ObjectNode ) + { + JsonNode value = updateNode.get( fieldName ); + ( (ObjectNode) mainNode ).replace( fieldName, value ); + } + } + return mainNode; + } + + public static JsonNode from( final URL url ) + { + if ( url == null ) + { + throw new IllegalArgumentException( "Cannot read JsonNode: URL not given" ); + } + + try + { + return MAPPER.readTree( url ); + } + catch ( IOException e ) + { + throw new IllegalArgumentException( "Cannot load settings from URL [" + url + "]", e ); + } + } + + public static JsonNode from( final Map settings ) + { + return MAPPER.valueToTree( settings ); + } + + public static Map toMap( final JsonNode node ) + { + return MAPPER.convertValue( node, Map.class ); + } + + public static JsonNode from( final String json ) + { + try + { + return MAPPER.readTree( json ); + } + catch ( IOException e ) + { + throw new IllegalArgumentException( "Cannot serialize settings from string [" + json + "]", e ); + } + } +} diff --git a/modules/core/core-internal/src/main/java/com/enonic/xp/core/internal/json/ObjectMapperHelper.java b/modules/core/core-internal/src/main/java/com/enonic/xp/core/internal/json/ObjectMapperHelper.java new file mode 100644 index 00000000000..65d20116b33 --- /dev/null +++ b/modules/core/core-internal/src/main/java/com/enonic/xp/core/internal/json/ObjectMapperHelper.java @@ -0,0 +1,28 @@ +package com.enonic.xp.core.internal.json; + +import java.text.SimpleDateFormat; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +public final class ObjectMapperHelper +{ + private ObjectMapperHelper() + { + } + + public static ObjectMapper create() + { + return JsonMapper.builder() + .defaultDateFormat( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ) ) + .disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS ) + .disable( SerializationFeature.FAIL_ON_EMPTY_BEANS ) + .enable( MapperFeature.SORT_PROPERTIES_ALPHABETICALLY ) + .serializationInclusion( JsonInclude.Include.NON_NULL ) + .addModule( new JavaTimeModule() ).build(); + } +} diff --git a/modules/core/core-media/build.gradle b/modules/core/core-media/build.gradle index 6d53a463323..895ea08a9fe 100644 --- a/modules/core/core-media/build.gradle +++ b/modules/core/core-media/build.gradle @@ -1,5 +1,7 @@ dependencies { implementation project( ':core:core-api' ) + + testImplementation( testFixtures( project(":core:core-api") ) ) } jar { diff --git a/modules/core/core-media/src/main/java/com/enonic/xp/core/impl/media/MediaTypeReporter.java b/modules/core/core-media/src/main/java/com/enonic/xp/core/impl/media/MediaTypeReporter.java index 803026dca9e..cee1348472b 100644 --- a/modules/core/core-media/src/main/java/com/enonic/xp/core/impl/media/MediaTypeReporter.java +++ b/modules/core/core-media/src/main/java/com/enonic/xp/core/impl/media/MediaTypeReporter.java @@ -1,5 +1,8 @@ package com.enonic.xp.core.impl.media; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.util.Map; import org.osgi.service.component.annotations.Component; @@ -9,13 +12,12 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.net.MediaType; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; import com.enonic.xp.util.MediaTypes; @Component(immediate = true, service = StatusReporter.class) public final class MediaTypeReporter - extends JsonStatusReporter + implements StatusReporter { @Override public String getName() @@ -24,7 +26,19 @@ public String getName() } @Override - public JsonNode getReport() + public MediaType getMediaType() + { + return MediaType.JSON_UTF_8; + } + + @Override + public void report( final OutputStream outputStream ) + throws IOException + { + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); + } + + private JsonNode getReport() { final ObjectNode json = JsonNodeFactory.instance.objectNode(); for ( final Map.Entry type : MediaTypes.instance().asMap().entrySet() ) diff --git a/modules/core/core-media/src/test/java/com/enonic/xp/core/impl/media/MediaTypeReporterTest.java b/modules/core/core-media/src/test/java/com/enonic/xp/core/impl/media/MediaTypeReporterTest.java index cb090633d9e..276476351c4 100644 --- a/modules/core/core-media/src/test/java/com/enonic/xp/core/impl/media/MediaTypeReporterTest.java +++ b/modules/core/core-media/src/test/java/com/enonic/xp/core/impl/media/MediaTypeReporterTest.java @@ -1,13 +1,20 @@ package com.enonic.xp.core.impl.media; +import java.io.ByteArrayOutputStream; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import com.google.common.net.MediaType; + +import com.enonic.xp.support.JsonTestHelper; + import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; public class MediaTypeReporterTest { + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + private MediaTypeReporter reporter; @BeforeEach @@ -24,7 +31,20 @@ public void testName() @Test public void testReport() + throws Exception { - assertNotNull( this.reporter.getReport() ); + assertJson( "report.json" ); + } + + private void assertJson( final String fileName ) + throws Exception + { + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); + + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); + + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( fileName ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); } } diff --git a/modules/core/core-media/src/test/resources/com/enonic/xp/core/impl/media/MediaTypeReporterTest-report.json b/modules/core/core-media/src/test/resources/com/enonic/xp/core/impl/media/MediaTypeReporterTest-report.json new file mode 100644 index 00000000000..cde37d1dc6b --- /dev/null +++ b/modules/core/core-media/src/test/resources/com/enonic/xp/core/impl/media/MediaTypeReporterTest-report.json @@ -0,0 +1,40 @@ +{ + "css" : "text/css", + "aac" : "audio/aac", + "bmp" : "image/bmp", + "gif" : "image/gif", + "apng" : "image/apng", + "webmanifest" : "application/manifest+json", + "flac" : "audio/flac", + "oga" : "audio/ogg", + "js" : "application/javascript", + "es6" : "application/javascript", + "jsonld" : "application/ld+json", + "eot" : "application/vnd.ms-fontobject", + "ico" : "image/vnd.microsoft.icon", + "xml" : "text/xml", + "ics" : "text/calendar", + "jpeg" : "image/jpeg", + "json" : "application/json", + "html" : "text/html", + "woff2" : "font/woff2", + "ogv" : "video/ogg", + "jpg" : "image/jpeg", + "htm" : "text/html", + "otf" : "font/otf", + "svg" : "image/svg+xml", + "ttf" : "font/ttf", + "png" : "image/png", + "webp" : "image/webp", + "es" : "application/javascript", + "webm" : "video/webm", + "woff" : "font/woff", + "mp4" : "video/mp4", + "txt" : "text/plain", + "mp3" : "audio/mpeg", + "pdf" : "application/pdf", + "mpeg" : "video/mpeg", + "mjs" : "application/javascript", + "weba" : "audio/webm", + "avif" : "image/avif" +} diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/branch/storage/BranchDocumentId.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/branch/storage/BranchDocumentId.java index 83633873b1a..aceb692a994 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/branch/storage/BranchDocumentId.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/branch/storage/BranchDocumentId.java @@ -2,6 +2,7 @@ import com.enonic.xp.branch.Branch; import com.enonic.xp.node.NodeId; +import com.enonic.xp.repo.impl.storage.RoutableId; public final class BranchDocumentId { @@ -11,4 +12,9 @@ public static String asString( final NodeId nodeId, final Branch branch ) { return nodeId + SEPARATOR + branch; } + + public static RoutableId asRoutableId( final NodeId nodeId, final Branch branch ) + { + return new RoutableId( asString( nodeId, branch ), nodeId.toString() ); + } } diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/branch/storage/BranchServiceImpl.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/branch/storage/BranchServiceImpl.java index 4396837a637..4379f1a2f9d 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/branch/storage/BranchServiceImpl.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/branch/storage/BranchServiceImpl.java @@ -109,7 +109,7 @@ public void delete( final Collection entries, final InternalCon { storageDao.delete( DeleteRequests.create() .ids( entries.stream() - .map( entry -> BranchDocumentId.asString( entry.getNodeId(), branch ) ) + .map( entry -> BranchDocumentId.asRoutableId( entry.getNodeId(), branch ) ) .collect( Collectors.toList() ) ) .settings( createStorageSettings( repositoryId ) ) .build() ); diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/dump/upgrade/AbstractDumpUpgrader.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/dump/upgrade/AbstractDumpUpgrader.java index 084da77a19c..70483ae3fdc 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/dump/upgrade/AbstractDumpUpgrader.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/dump/upgrade/AbstractDumpUpgrader.java @@ -13,8 +13,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.dump.DumpUpgradeStepResult; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.repo.impl.dump.RepoDumpException; import com.enonic.xp.repo.impl.dump.reader.FileDumpReader; import com.enonic.xp.util.Version; diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/elasticsearch/IndexServiceInternalImpl.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/elasticsearch/IndexServiceInternalImpl.java index 79025be9909..60b0de8db78 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/elasticsearch/IndexServiceInternalImpl.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/elasticsearch/IndexServiceInternalImpl.java @@ -110,14 +110,14 @@ public void createIndex( final com.enonic.xp.repo.impl.index.CreateIndexRequest LOG.info( "creating index {}", indexName ); CreateIndexRequest createIndexRequest = new CreateIndexRequest( indexName ); - createIndexRequest.settings( indexSettings.getAsString() ); + createIndexRequest.settings( indexSettings.getData() ); if ( request.getMappings() != null ) { for ( Map.Entry mappingEntry : request.getMappings().entrySet() ) { createIndexRequest.mapping( mappingEntry.getKey().isDynamicTypes() ? ES_DEFAULT_INDEX_TYPE_NAME : mappingEntry.getKey().getName(), - mappingEntry.getValue().getAsString() ); + mappingEntry.getValue().getData() ); } } @@ -156,7 +156,7 @@ public void updateIndex( final String indexName, final UpdateIndexSettings setti } @Override - public IndexSettings getIndexSettings( final RepositoryId repositoryId, final IndexType indexType ) + public Map getIndexSettings( final RepositoryId repositoryId, final IndexType indexType ) { if ( repositoryId == null || indexType == null ) { @@ -173,7 +173,7 @@ public IndexSettings getIndexSettings( final RepositoryId repositoryId, final In .actionGet( GET_SETTINGS_TIMEOUT ) .getIndexToSettings(); - return IndexSettings.from( (Map) settingsMap.get( indexName ).getAsMap() ); + return settingsMap.get( indexName ).getAsMap(); } @Override diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/elasticsearch/storage/StorageDaoImpl.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/elasticsearch/storage/StorageDaoImpl.java index fc3285c7832..fdec637747f 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/elasticsearch/storage/StorageDaoImpl.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/elasticsearch/storage/StorageDaoImpl.java @@ -38,6 +38,7 @@ import com.enonic.xp.repo.impl.storage.GetByIdRequest; import com.enonic.xp.repo.impl.storage.GetByIdsRequest; import com.enonic.xp.repo.impl.storage.GetResult; +import com.enonic.xp.repo.impl.storage.RoutableId; import com.enonic.xp.repo.impl.storage.StorageDao; import com.enonic.xp.repo.impl.storage.StoreRequest; import com.enonic.xp.repository.IndexException; @@ -124,7 +125,7 @@ public void delete( final DeleteRequests requests ) { final StorageSource settings = requests.getSettings(); - for ( final String id : requests.getIds() ) + for ( final RoutableId id : requests.getIds() ) { try { @@ -133,8 +134,8 @@ public void delete( final DeleteRequests requests ) setIndex( settings.getStorageName().getName() ). setType( settings.getStorageType().getName() ). setRefresh( requests.isForceRefresh() ). - setId( id ). - setRouting( id ). + setId( id.id ). + setRouting( id.routing ). request(); this.client.delete( request ).actionGet( requests.getTimeout(), TimeUnit.SECONDS ); diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexServiceImpl.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexServiceImpl.java index f1ced094c36..1211f623f66 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexServiceImpl.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexServiceImpl.java @@ -25,9 +25,8 @@ import com.enonic.xp.repo.impl.storage.IndexDataService; import com.enonic.xp.repository.IndexMapping; import com.enonic.xp.repository.IndexSettings; -import com.enonic.xp.repository.Repository; import com.enonic.xp.repository.RepositoryId; -import com.enonic.xp.util.JsonHelper; +import com.enonic.xp.repository.RepositorySettings; @Component public class IndexServiceImpl @@ -132,7 +131,7 @@ private void updateIndexSettings( final String indexName, final UpdateIndexSetti @Override public IndexSettings getIndexSettings( final RepositoryId repositoryId, final IndexType indexType ) { - return this.indexServiceInternal.getIndexSettings( repositoryId, indexType ); + return IndexSettings.from( this.indexServiceInternal.getIndexSettings( repositoryId, indexType ) ); } @Override @@ -164,10 +163,14 @@ private void doPurgeSearchIndex( final RepositoryId repositoryId ) { final String searchIndexName = IndexNameResolver.resolveSearchIndexName( repositoryId ); + final RepositorySettings repositorySettings = repositoryEntryService.getRepositoryEntry( repositoryId ).getSettings(); + indexServiceInternal.deleteIndices( searchIndexName ); - final IndexSettings indexSettings = getSearchIndexSettings( repositoryId ); - final IndexMapping indexMapping = getSearchIndexMapping( repositoryId ); + final IndexSettings indexSettings = IndexSettingsMerger.merge( DEFAULT_INDEX_RESOURCE_PROVIDER.getSettings( IndexType.SEARCH ), + repositorySettings.getIndexSettings( IndexType.SEARCH ) ); + final IndexMapping indexMapping = IndexSettingsMerger.merge( DEFAULT_INDEX_RESOURCE_PROVIDER.getMapping( IndexType.SEARCH ), + repositorySettings.getIndexMappings( IndexType.SEARCH ) ); indexServiceInternal.createIndex( CreateIndexRequest.create() .indexName( searchIndexName ) @@ -178,42 +181,6 @@ private void doPurgeSearchIndex( final RepositoryId repositoryId ) indexServiceInternal.waitForYellowStatus( searchIndexName ); } - private IndexSettings getSearchIndexSettings( final RepositoryId repositoryId ) - { - final IndexSettings defaultIndexSettings = DEFAULT_INDEX_RESOURCE_PROVIDER.getSettings( repositoryId, IndexType.SEARCH ); - - final Repository repositoryEntry = repositoryEntryService.getRepositoryEntry( repositoryId ); - if ( repositoryEntry != null ) - { - final IndexSettings indexSettings = repositoryEntry.getSettings().getIndexSettings( IndexType.SEARCH ); - - if ( indexSettings != null ) - { - return new IndexSettings( JsonHelper.merge( defaultIndexSettings.getNode(), indexSettings.getNode() ) ); - } - } - - return defaultIndexSettings; - } - - private IndexMapping getSearchIndexMapping( final RepositoryId repositoryId ) - { - final IndexMapping defaultIndexMapping = DEFAULT_INDEX_RESOURCE_PROVIDER.getMapping( repositoryId, IndexType.SEARCH ); - - final Repository repositoryEntry = repositoryEntryService.getRepositoryEntry( repositoryId ); - if ( repositoryEntry != null ) - { - final IndexMapping indexMapping = repositoryEntry.getSettings().getIndexMappings( IndexType.SEARCH ); - - if ( indexMapping != null ) - { - return new IndexMapping( JsonHelper.merge( defaultIndexMapping.getNode(), indexMapping.getNode() ) ); - } - } - - return defaultIndexMapping; - } - public void setIndexServiceInternal( final IndexServiceInternal indexServiceInternal ) { this.indexServiceInternal = indexServiceInternal; diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexServiceInternal.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexServiceInternal.java index ccd8a6abc12..96a095989f4 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexServiceInternal.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexServiceInternal.java @@ -4,7 +4,6 @@ import com.enonic.xp.branch.Branch; import com.enonic.xp.index.IndexType; -import com.enonic.xp.repository.IndexSettings; import com.enonic.xp.repository.RepositoryId; public interface IndexServiceInternal @@ -23,7 +22,7 @@ public interface IndexServiceInternal boolean waitForYellowStatus( String... indexNames ); - IndexSettings getIndexSettings( RepositoryId repositoryId, IndexType indexType ); + Map getIndexSettings( RepositoryId repositoryId, IndexType indexType ); Map getIndexMapping( RepositoryId repositoryId, Branch branch, IndexType indexType ); diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexSettingsMerger.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexSettingsMerger.java new file mode 100644 index 00000000000..7301176a69e --- /dev/null +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/index/IndexSettingsMerger.java @@ -0,0 +1,36 @@ +package com.enonic.xp.repo.impl.index; + +import com.fasterxml.jackson.databind.JsonNode; + +import com.enonic.xp.core.internal.json.JsonHelper; +import com.enonic.xp.repository.IndexMapping; +import com.enonic.xp.repository.IndexSettings; + +public final class IndexSettingsMerger +{ + private IndexSettingsMerger() + { + } + + public static IndexSettings merge( final IndexSettings first, final IndexSettings second ) + { + if ( second == null ) + { + return first; + } + final JsonNode firstJsonNode = JsonHelper.from( first.getData() ); + final JsonNode secondJsonNode = JsonHelper.from( second.getData() ); + return IndexSettings.from( JsonHelper.toMap( JsonHelper.merge( firstJsonNode, secondJsonNode ) ) ); + } + + public static IndexMapping merge( final IndexMapping first, final IndexMapping second ) + { + if ( second == null ) + { + return first; + } + final JsonNode firstJsonNode = JsonHelper.from( first.getData() ); + final JsonNode secondJsonNode = JsonHelper.from( second.getData() ); + return IndexMapping.from( JsonHelper.toMap( JsonHelper.merge( firstJsonNode, secondJsonNode ) ) ); + } +} diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/node/json/ImmutableVersionData.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/node/json/ImmutableVersionData.java index 585bc954cdd..e97f0676845 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/node/json/ImmutableVersionData.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/node/json/ImmutableVersionData.java @@ -15,10 +15,10 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.common.io.ByteSource; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.data.ValueType; import com.enonic.xp.data.ValueTypes; import com.enonic.xp.index.ChildOrder; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.node.AttachedBinaries; import com.enonic.xp.node.AttachedBinary; import com.enonic.xp.node.NodeId; diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/node/json/NodeVersionJsonSerializer.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/node/json/NodeVersionJsonSerializer.java index f5ceae1c2d3..b5eb99f9d02 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/node/json/NodeVersionJsonSerializer.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/node/json/NodeVersionJsonSerializer.java @@ -6,9 +6,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.ByteSource; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.index.IndexConfigDocument; import com.enonic.xp.index.PatternIndexConfigDocument; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.node.NodeVersion; import com.enonic.xp.security.acl.AccessControlList; diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/DefaultIndexResourceProvider.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/DefaultIndexResourceProvider.java index a51187a80f9..933acdac434 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/DefaultIndexResourceProvider.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/DefaultIndexResourceProvider.java @@ -1,17 +1,13 @@ package com.enonic.xp.repo.impl.repository; import java.net.URL; -import java.util.Objects; - -import com.fasterxml.jackson.databind.JsonNode; +import com.enonic.xp.core.internal.json.JsonHelper; import com.enonic.xp.index.IndexType; import com.enonic.xp.repository.IndexException; import com.enonic.xp.repository.IndexMapping; import com.enonic.xp.repository.IndexResourceType; import com.enonic.xp.repository.IndexSettings; -import com.enonic.xp.repository.RepositoryId; -import com.enonic.xp.util.JsonHelper; public class DefaultIndexResourceProvider implements IndexResourceProvider @@ -24,30 +20,26 @@ public DefaultIndexResourceProvider( final String resourceBaseFolder ) } @Override - public IndexMapping getMapping( final RepositoryId repositoryId, final IndexType indexType ) + public IndexMapping getMapping( final IndexType indexType ) { - final JsonNode defaultMapping = getResource( indexType, IndexResourceType.MAPPING ); - - return new IndexMapping( defaultMapping ); + return IndexMapping.from( JsonHelper.toMap( JsonHelper.from( getResource( indexType, IndexResourceType.MAPPING ) ) ) ); } @Override - public IndexSettings getSettings( final RepositoryId repositoryId, final IndexType indexType ) + public IndexSettings getSettings( final IndexType indexType ) { - final JsonNode defaultSettings = getResource( indexType, IndexResourceType.SETTINGS ); - return new IndexSettings( defaultSettings ); + return IndexSettings.from( JsonHelper.toMap( JsonHelper.from( getResource( indexType, IndexResourceType.SETTINGS ) ) ) ); } - private JsonNode getResource( final IndexType indexType, final IndexResourceType type ) + private URL getResource( final IndexType indexType, final IndexResourceType type ) { String fileName = resourceBaseFolder + "/" + type.getName() + "/" + "default" + "/" + indexType.getName() + "-" + type.getName() + ".json"; try { - final URL resource = DefaultIndexResourceProvider.class.getResource( fileName ); - return JsonHelper.from( Objects.requireNonNull( resource ) ); + return DefaultIndexResourceProvider.class.getResource( fileName ); } catch ( Exception e ) { diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/IndexResourceProvider.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/IndexResourceProvider.java index 8620e6ef0f7..9d9131ae463 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/IndexResourceProvider.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/IndexResourceProvider.java @@ -3,11 +3,10 @@ import com.enonic.xp.index.IndexType; import com.enonic.xp.repository.IndexMapping; import com.enonic.xp.repository.IndexSettings; -import com.enonic.xp.repository.RepositoryId; public interface IndexResourceProvider { - IndexMapping getMapping( RepositoryId repositoryId, IndexType indexType ); + IndexMapping getMapping( IndexType indexType ); - IndexSettings getSettings( RepositoryId repositoryId, IndexType indexType ); + IndexSettings getSettings( IndexType indexType ); } diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/JsonToPropertyTreeTranslator.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/JsonToPropertyTreeTranslator.java deleted file mode 100644 index a4d0835d538..00000000000 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/JsonToPropertyTreeTranslator.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.enonic.xp.repo.impl.repository; - -import java.util.Iterator; -import java.util.Map; - -import com.fasterxml.jackson.databind.JsonNode; - -import com.enonic.xp.data.PropertySet; -import com.enonic.xp.data.Value; -import com.enonic.xp.data.ValueFactory; - -final class JsonToPropertyTreeTranslator -{ - static void translate( final JsonNode json, final PropertySet into ) - { - final Iterator> fields = json.fields(); - - while ( fields.hasNext() ) - { - final Map.Entry next = fields.next(); - addValue( into, next.getKey(), next.getValue() ); - } - } - - private static void addValue( final PropertySet parent, final String key, final JsonNode value ) - { - if ( value.isArray() ) - { - for ( final JsonNode objNode : value ) - { - addValue( parent, key, objNode ); - } - } - else if ( value.isObject() ) - { - final PropertySet parentSet = parent.addSet( key ); - value.fields().forEachRemaining( ( objectValue ) -> addValue( parentSet, objectValue.getKey(), objectValue.getValue() ) ); - } - else - { - parent.addProperty( key, resolveCoreValue( value ) ); - } - } - - private static Value resolveCoreValue( final JsonNode value ) - { - if ( value.isDouble() ) - { - return ValueFactory.newDouble( value.doubleValue() ); - } - - if ( value.isTextual() ) - { - return ValueFactory.newString( value.textValue() ); - } - - if ( value.isInt() ) - { - return ValueFactory.newLong( (long) value.intValue() ); - } - - if ( value.isLong() ) - { - return ValueFactory.newLong( value.longValue() ); - } - - if ( value.isBoolean() ) - { - return ValueFactory.newBoolean( value.booleanValue() ); - } - - return ValueFactory.newString( value.toString() ); - } -} diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/NodeRepositoryServiceImpl.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/NodeRepositoryServiceImpl.java index ce163693d7f..674218ec61b 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/NodeRepositoryServiceImpl.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/NodeRepositoryServiceImpl.java @@ -1,8 +1,6 @@ package com.enonic.xp.repo.impl.repository; -import java.util.Arrays; import java.util.Map; -import java.util.Objects; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; @@ -10,12 +8,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; - import com.enonic.xp.index.IndexType; import com.enonic.xp.repo.impl.index.CreateIndexRequest; import com.enonic.xp.repo.impl.index.IndexServiceInternal; +import com.enonic.xp.repo.impl.index.IndexSettingsMerger; import com.enonic.xp.repository.CreateRepositoryParams; import com.enonic.xp.repository.IndexMapping; import com.enonic.xp.repository.IndexSettings; @@ -23,7 +19,6 @@ import com.enonic.xp.repository.RepositoryId; import com.enonic.xp.repository.RepositorySettings; import com.enonic.xp.security.SystemConstants; -import com.enonic.xp.util.JsonHelper; @Component public class NodeRepositoryServiceImpl @@ -51,12 +46,12 @@ public void create( final CreateRepositoryParams params ) final RepositorySettings repositorySettings = params.getRepositorySettings(); createIndex( params, IndexType.VERSION, - Map.ofEntries( mergeWithDefaultMapping( repositorySettings, repositoryId, IndexType.VERSION ), - mergeWithDefaultMapping( repositorySettings, repositoryId, IndexType.BRANCH ), - mergeWithDefaultMapping( repositorySettings, repositoryId, IndexType.COMMIT ) ) ); + Map.ofEntries( mergeWithDefaultMapping( repositorySettings, IndexType.VERSION ), + mergeWithDefaultMapping( repositorySettings, IndexType.BRANCH ), + mergeWithDefaultMapping( repositorySettings, IndexType.COMMIT ) ) ); createIndex( params, IndexType.SEARCH, - Map.ofEntries( mergeWithDefaultMapping( repositorySettings, repositoryId, IndexType.SEARCH ) ) ); + Map.ofEntries( mergeWithDefaultMapping( repositorySettings, IndexType.SEARCH ) ) ); indexServiceInternal.waitForYellowStatus( resolveIndexNames( repositoryId ) ); } @@ -76,7 +71,7 @@ public boolean isInitialized( final RepositoryId repositoryId ) private void createIndex( final CreateRepositoryParams params, final IndexType indexType, final Map mappings ) { final RepositoryId repositoryId = params.getRepositoryId(); - final IndexSettings mergedSettings = mergeWithDefaultSettings( params, indexType ); + final IndexSettings mergedSettings = mergeWithDefaultSettings( repositoryId, params.getRepositorySettings().getIndexSettings( indexType ), indexType ); indexServiceInternal.createIndex( CreateIndexRequest.create() .indexName( resolveIndexName( repositoryId, indexType ) ) @@ -86,61 +81,43 @@ private void createIndex( final CreateRepositoryParams params, final IndexType i } - private IndexSettings mergeWithDefaultSettings( final CreateRepositoryParams params, final IndexType indexType ) + private IndexSettings mergeWithDefaultSettings( final RepositoryId repositoryId, final IndexSettings indexSettings, final IndexType indexType ) { - final IndexSettings defaultSettings = getDefaultSettings( params.getRepositoryId(), indexType ); - - final IndexSettings indexSettings = params.getRepositorySettings().getIndexSettings( indexType ); - if ( indexSettings != null ) + final IndexSettings defaultFromFile = DEFAULT_INDEX_RESOURCE_PROVIDER.getSettings( indexType ); + if ( SystemConstants.SYSTEM_REPO_ID.equals( repositoryId ) ) { - return new IndexSettings( JsonHelper.merge( defaultSettings.getNode(), indexSettings.getNode() ) ); + return defaultFromFile; } + final IndexSettings defaultSettings = adjustNumberOfReplicas( defaultFromFile ); - return defaultSettings; + return IndexSettingsMerger.merge( defaultSettings, indexSettings ); } - private IndexSettings getDefaultSettings( final RepositoryId repositoryId, final IndexType indexType ) + private IndexSettings adjustNumberOfReplicas( final IndexSettings defaultSettings ) { - final IndexSettings defaultSettings = DEFAULT_INDEX_RESOURCE_PROVIDER.getSettings( repositoryId, indexType ); - if ( SystemConstants.SYSTEM_REPO_ID.equals( repositoryId ) ) - { - return defaultSettings; - } - try { - final String numberOfReplicasString = indexServiceInternal.getIndexSettings( SystemConstants.SYSTEM_REPO_ID, IndexType.VERSION ) - .getNode() - .get( "index.number_of_replicas" ) - .textValue(); - final int numberOfReplicas = Integer.parseInt( numberOfReplicasString ); - final ObjectNode indexNodeObject = (ObjectNode) defaultSettings.getNode().get( "index" ); - indexNodeObject.put( "number_of_replicas", numberOfReplicas ); + final String numberOfReplicas = indexServiceInternal.getIndexSettings( SystemConstants.SYSTEM_REPO_ID, IndexType.VERSION ) + .get( "index.number_of_replicas" ); + + return IndexSettingsMerger.merge( defaultSettings, + IndexSettings.from( Map.of( "index", Map.of( "number_of_replicas", numberOfReplicas ) ) ) ); } catch ( Exception e ) { - LOG.warn( "Failed to retrieve number of replicas from [" + - IndexNameResolver.resolveStorageIndexName( SystemConstants.SYSTEM_REPO_ID ) + "]" ); + LOG.warn( "Failed to retrieve number of replicas from [{}]", + IndexNameResolver.resolveStorageIndexName( SystemConstants.SYSTEM_REPO_ID ) ); } return defaultSettings; } - private static Map.Entry mergeWithDefaultMapping( final RepositorySettings repositorySettings, - final RepositoryId repositoryId, final IndexType indexType ) - { - return Map.entry( indexType, mergeMappings( DEFAULT_INDEX_RESOURCE_PROVIDER.getMapping( repositoryId, indexType ), - repositorySettings.getIndexMappings( indexType ) ) ); - } - - private static IndexMapping mergeMappings( IndexMapping... indexMappings ) + private static Map.Entry mergeWithDefaultMapping( final RepositorySettings repositorySettings, final IndexType indexType ) { - JsonNode intermediate = JsonHelper.from( Map.of() ); + final IndexMapping defaultMapping = DEFAULT_INDEX_RESOURCE_PROVIDER.getMapping( indexType ); + final IndexMapping settingsMapping = repositorySettings.getIndexMappings( indexType ); - Arrays.stream( indexMappings ) - .filter( Objects::nonNull ) - .forEach( indexMapping -> JsonHelper.merge( intermediate, indexMapping.getNode() ) ); - return new IndexMapping( intermediate ); + return Map.entry( indexType, IndexSettingsMerger.merge( defaultMapping, settingsMapping ) ); } private static String[] resolveIndexNames( final RepositoryId repositoryId ) diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/RepositoryNodeTranslator.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/RepositoryNodeTranslator.java index e682260404a..88ac4b3bc36 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/RepositoryNodeTranslator.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/repository/RepositoryNodeTranslator.java @@ -126,17 +126,13 @@ private static void toNodeData( final IndexDefinitions indexDefinitions, final P final IndexMapping indexMapping = indexDefinition.getMapping(); if ( indexMapping != null ) { - PropertySet indexMappingPropertySet = data.newSet(); - JsonToPropertyTreeTranslator.translate( indexMapping.getNode(), indexMappingPropertySet ); - indexConfigPropertySet.setSet( MAPPING_KEY, indexMappingPropertySet ); + indexConfigPropertySet.setSet( MAPPING_KEY, PropertyTree.fromMap( indexMapping.getData() ).getRoot().copy( data ) ); } final IndexSettings indexSettings = indexDefinition.getSettings(); if ( indexSettings != null ) { - PropertySet indexMappingPropertySet = data.newSet(); - JsonToPropertyTreeTranslator.translate( indexSettings.getNode(), indexMappingPropertySet ); - indexConfigPropertySet.setSet( SETTINGS_KEY, indexMappingPropertySet ); + indexConfigPropertySet.setSet( SETTINGS_KEY, PropertyTree.fromMap( indexSettings.getData() ).getRoot().copy( data ) ); } } } @@ -185,10 +181,10 @@ private static IndexDefinitions toIndexConfigs( final PropertyTree nodeData ) final IndexDefinition.Builder indexConfig = IndexDefinition.create(); final PropertySet mappingSet = indexConfigSet.getSet( MAPPING_KEY ); - indexConfig.mapping( mappingSet == null ? null : IndexMapping.from( mappingSet.toTree() ) ); + indexConfig.mapping( mappingSet == null ? null : IndexMapping.from( mappingSet.toTree().toMap() ) ); final PropertySet settingsSet = indexConfigSet.getSet( SETTINGS_KEY ); - indexConfig.settings( settingsSet == null ? null : IndexSettings.from( settingsSet.toTree() ) ); + indexConfig.settings( settingsSet == null ? null : IndexSettings.from( settingsSet.toTree().toMap() ) ); indexConfigs.add( indexType, indexConfig.build() ); } diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/DeleteRequests.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/DeleteRequests.java index 33fddf3bdbf..4b68e4a89e8 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/DeleteRequests.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/DeleteRequests.java @@ -6,7 +6,7 @@ public class DeleteRequests { - private final List ids; + private final List ids; private final StorageSource settings; @@ -27,7 +27,7 @@ public static Builder create() return new Builder(); } - public List getIds() + public List getIds() { return ids; } @@ -55,7 +55,7 @@ public static final class Builder private int timeout = 5; - private List ids; + private List ids; private Builder() { @@ -84,7 +84,7 @@ public DeleteRequests build() return new DeleteRequests( this ); } - public Builder ids( final List val ) + public Builder ids( final List val ) { ids = val; return this; diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/IndexDataServiceImpl.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/IndexDataServiceImpl.java index c4e71929aaf..7984cc9a762 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/IndexDataServiceImpl.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/IndexDataServiceImpl.java @@ -88,7 +88,7 @@ public void delete( final Collection nodeIds, final InternalContext cont storageType( SearchStorageType.from( context.getBranch() ) ). storageName( SearchStorageName.from( context.getRepositoryId() ) ). build() ). - ids( nodeIds.stream().map( NodeId::toString ).collect( Collectors.toList() ) ). + ids( nodeIds.stream().map( NodeId::toString ).map( RoutableId::new ).collect( Collectors.toList() ) ). build() ); } diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/RoutableId.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/RoutableId.java new file mode 100644 index 00000000000..aa3d1cf3b5b --- /dev/null +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/storage/RoutableId.java @@ -0,0 +1,34 @@ +package com.enonic.xp.repo.impl.storage; + +import java.util.Objects; + +public final class RoutableId +{ + public final String id; + + public final String routing; + + public RoutableId( final String id ) + { + this.id = id; + this.routing = null; + } + + public RoutableId( final String id, final String routing ) + { + this.id = id; + this.routing = routing; + } + + @Override + public boolean equals( final Object o ) + { + return ( o instanceof final RoutableId that ) && Objects.equals( id, that.id ) && Objects.equals( routing, that.routing ); + } + + @Override + public int hashCode() + { + return Objects.hash( id, routing ); + } +} diff --git a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/version/VersionServiceImpl.java b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/version/VersionServiceImpl.java index a43b4f8a23a..6735664c1b6 100644 --- a/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/version/VersionServiceImpl.java +++ b/modules/core/core-repo/src/main/java/com/enonic/xp/repo/impl/version/VersionServiceImpl.java @@ -14,6 +14,7 @@ import com.enonic.xp.repo.impl.storage.DeleteRequests; import com.enonic.xp.repo.impl.storage.GetByIdRequest; import com.enonic.xp.repo.impl.storage.GetResult; +import com.enonic.xp.repo.impl.storage.RoutableId; import com.enonic.xp.repo.impl.storage.StaticStorageType; import com.enonic.xp.repo.impl.storage.StorageDao; import com.enonic.xp.repo.impl.storage.StoreRequest; @@ -50,7 +51,7 @@ public void store( final NodeVersionMetadata nodeVersionMetadata, final Internal public void delete( final NodeVersionId nodeVersionId, final InternalContext context ) { storageDao.delete( DeleteRequests.create() - .ids( List.of( nodeVersionId.toString() ) ) + .ids( List.of( new RoutableId( nodeVersionId.toString() ) ) ) .settings( createStorageSettings( context.getRepositoryId() ) ) .build() ); } diff --git a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/dump/upgrade/FlattenedPageDataUpgraderTest.java b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/dump/upgrade/FlattenedPageDataUpgraderTest.java index 90a47685234..9ef671faeee 100644 --- a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/dump/upgrade/FlattenedPageDataUpgraderTest.java +++ b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/dump/upgrade/FlattenedPageDataUpgraderTest.java @@ -2,6 +2,7 @@ import java.net.URL; import java.util.HashMap; +import java.util.Map; import org.junit.jupiter.api.Test; @@ -9,7 +10,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.json.JsonToPropertyTreeTranslator; import com.enonic.xp.repo.impl.dump.upgrade.flattenedpage.FlattenedPageDataUpgrader; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -53,8 +53,8 @@ private void test( final String oldJsonFile, final String newJsonFile ) final JsonNode oldPageComponents = loadJson( oldJsonFile ); final JsonNode newPageComponents = loadJson( newJsonFile ); - final PropertyTree oldData = new JsonToPropertyTreeTranslator().translate( oldPageComponents ); - final PropertyTree newData = new JsonToPropertyTreeTranslator().translate( newPageComponents ); + final PropertyTree oldData = PropertyTree.fromMap( MAPPER.convertValue( oldPageComponents, Map.class ) ); + final PropertyTree newData = PropertyTree.fromMap( MAPPER.convertValue( newPageComponents, Map.class ) ); final HashMap templateControllerMap = new HashMap<>(); templateControllerMap.put( "templateId", "com.enonic.app.features:main" ); diff --git a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/dump/upgrade/FlattenedPageIndexUpgraderTest.java b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/dump/upgrade/FlattenedPageIndexUpgraderTest.java index 3ec750383a1..b2ff0cea628 100644 --- a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/dump/upgrade/FlattenedPageIndexUpgraderTest.java +++ b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/dump/upgrade/FlattenedPageIndexUpgraderTest.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.net.URL; import java.util.List; +import java.util.Map; import org.junit.jupiter.api.Test; @@ -10,12 +11,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.data.PropertyPath; import com.enonic.xp.data.PropertySet; import com.enonic.xp.data.PropertyTree; import com.enonic.xp.index.PatternIndexConfigDocument; -import com.enonic.xp.json.JsonToPropertyTreeTranslator; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.page.DescriptorKey; import com.enonic.xp.repo.impl.dump.upgrade.flattenedpage.FlattenedPageIndexUpgrader; import com.enonic.xp.repo.impl.node.json.IndexConfigDocumentJson; @@ -40,7 +40,7 @@ private void test( final String dataFile, final String oldIndexDocumentFile, fin { final JsonNode pageComponents = loadJson( dataFile ); - final PropertyTree data = new JsonToPropertyTreeTranslator().translate( pageComponents ); + final PropertyTree data = PropertyTree.fromMap( MAPPER.convertValue( pageComponents, Map.class ) ); final List components = Lists.newArrayList( data.getSets( "components" ) ); diff --git a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/elasticsearch/query/translator/factory/dsl/QueryBuilderTest.java b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/elasticsearch/query/translator/factory/dsl/QueryBuilderTest.java index 1901243b4e2..79ad6e8cbdd 100644 --- a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/elasticsearch/query/translator/factory/dsl/QueryBuilderTest.java +++ b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/elasticsearch/query/translator/factory/dsl/QueryBuilderTest.java @@ -13,11 +13,11 @@ import com.fasterxml.jackson.databind.ObjectWriter; import com.enonic.xp.core.impl.PropertyTreeMarshallerServiceFactory; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.data.PropertyTree; import com.enonic.xp.form.PropertyTreeMarshallerService; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.schema.mixin.MixinService; -import com.enonic.xp.util.JsonHelper; +import com.enonic.xp.core.internal.json.JsonHelper; public abstract class QueryBuilderTest { diff --git a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/node/dao/NodeVersionServiceImplTest.java b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/node/dao/NodeVersionServiceImplTest.java index f3642baebfb..607c6d1eb6d 100644 --- a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/node/dao/NodeVersionServiceImplTest.java +++ b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/node/dao/NodeVersionServiceImplTest.java @@ -19,6 +19,7 @@ import com.enonic.xp.context.Context; import com.enonic.xp.context.ContextAccessor; import com.enonic.xp.context.ContextBuilder; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.data.PropertyArrayJson; import com.enonic.xp.data.PropertySet; import com.enonic.xp.data.PropertyTree; @@ -29,7 +30,6 @@ import com.enonic.xp.index.PatternIndexConfigDocument; import com.enonic.xp.internal.blobstore.MemoryBlobRecord; import com.enonic.xp.internal.blobstore.MemoryBlobStore; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.node.NodeId; import com.enonic.xp.node.NodeType; import com.enonic.xp.node.NodeVersion; diff --git a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/node/json/NodeVersionJsonDumpSerializerTest.java b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/node/json/NodeVersionJsonDumpSerializerTest.java index cde78c19fc1..c8b5be37fdc 100644 --- a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/node/json/NodeVersionJsonDumpSerializerTest.java +++ b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/node/json/NodeVersionJsonDumpSerializerTest.java @@ -11,6 +11,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.CharSource; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.data.PropertyTree; import com.enonic.xp.data.Value; import com.enonic.xp.index.ChildOrder; @@ -18,7 +19,6 @@ import com.enonic.xp.index.IndexPath; import com.enonic.xp.index.IndexValueProcessor; import com.enonic.xp.index.PatternIndexConfigDocument; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.node.AttachedBinaries; import com.enonic.xp.node.AttachedBinary; import com.enonic.xp.node.NodeId; diff --git a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/repository/RepositoryNodeTranslatorTest.java b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/repository/RepositoryNodeTranslatorTest.java index 0c2c28a8bb1..cc3040027b2 100644 --- a/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/repository/RepositoryNodeTranslatorTest.java +++ b/modules/core/core-repo/src/test/java/com/enonic/xp/repo/impl/repository/RepositoryNodeTranslatorTest.java @@ -35,16 +35,16 @@ public void values_not_duplicated() settings( RepositorySettings.create(). indexDefinitions( IndexDefinitions.create(). add( IndexType.VERSION, IndexDefinition.create(). - mapping( IndexMapping.from( indexMapping ) ). - settings( IndexSettings.from( indexSettings ) ). + mapping( IndexMapping.from( indexMapping.toMap() ) ). + settings( IndexSettings.from( indexSettings.toMap() ) ). build() ). add( IndexType.BRANCH, IndexDefinition.create(). - mapping( IndexMapping.from( indexMapping ) ). - settings( IndexSettings.from( indexSettings ) ). + mapping( IndexMapping.from( indexMapping.toMap() ) ). + settings( IndexSettings.from( indexSettings.toMap() ) ). build() ). add( IndexType.COMMIT, IndexDefinition.create(). - mapping( IndexMapping.from( indexMapping ) ). - settings( IndexSettings.from( indexSettings ) ). + mapping( IndexMapping.from( indexMapping.toMap() ) ). + settings( IndexSettings.from( indexSettings.toMap() ) ). build() ). build() ). build() ). diff --git a/modules/core/core-repo/src/test/resources/com/enonic/xp/repo/impl/node/json/serialized-node.json b/modules/core/core-repo/src/test/resources/com/enonic/xp/repo/impl/node/json/serialized-node.json index c9930c3b46b..a7f966db200 100644 --- a/modules/core/core-repo/src/test/resources/com/enonic/xp/repo/impl/node/json/serialized-node.json +++ b/modules/core/core-repo/src/test/resources/com/enonic/xp/repo/impl/node/json/serialized-node.json @@ -87,6 +87,5 @@ } ], "id": "myId", - "manualOrderValue": null, "nodeType": "myNodeType" -} \ No newline at end of file +} diff --git a/modules/core/core-schema/build.gradle b/modules/core/core-schema/build.gradle index 4268312ed16..3d91f32d17f 100644 --- a/modules/core/core-schema/build.gradle +++ b/modules/core/core-schema/build.gradle @@ -1,5 +1,6 @@ dependencies { implementation project( ':core:core-api' ) + implementation project( ':core:core-internal' ) testFixturesApi project( ':core:core-api' ) testImplementation( testFixtures( project(":core:core-app") ) ) diff --git a/modules/core/core-schema/src/main/java/com/enonic/xp/core/impl/form/PropertyTreeMarshallerServiceImpl.java b/modules/core/core-schema/src/main/java/com/enonic/xp/core/impl/form/PropertyTreeMarshallerServiceImpl.java index 6d48750c114..63e2d4d985c 100644 --- a/modules/core/core-schema/src/main/java/com/enonic/xp/core/impl/form/PropertyTreeMarshallerServiceImpl.java +++ b/modules/core/core-schema/src/main/java/com/enonic/xp/core/impl/form/PropertyTreeMarshallerServiceImpl.java @@ -8,10 +8,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.data.PropertyTree; import com.enonic.xp.form.Form; import com.enonic.xp.form.PropertyTreeMarshallerService; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.schema.mixin.MixinService; @Component(immediate = true) diff --git a/modules/core/core-task/build.gradle b/modules/core/core-task/build.gradle index 0aa891289e0..939b99f3fc6 100644 --- a/modules/core/core-task/build.gradle +++ b/modules/core/core-task/build.gradle @@ -8,6 +8,7 @@ dependencies { testImplementation( testFixtures( project(":core:core-api") ) ) testImplementation( testFixtures( project(":core:core-app") ) ) testImplementation( testFixtures( project(":core:core-internal") ) ) + testImplementation project( ':tools:testing' ) } jar { diff --git a/modules/core/core-task/src/test/java/com/enonic/xp/impl/task/script/PropertyTreeMapperTest.java b/modules/core/core-task/src/test/java/com/enonic/xp/impl/task/script/PropertyTreeMapperTest.java index aff3a9414cd..a1b79a6522d 100644 --- a/modules/core/core-task/src/test/java/com/enonic/xp/impl/task/script/PropertyTreeMapperTest.java +++ b/modules/core/core-task/src/test/java/com/enonic/xp/impl/task/script/PropertyTreeMapperTest.java @@ -1,29 +1,16 @@ package com.enonic.xp.impl.task.script; -import java.net.URL; - import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - import com.enonic.xp.data.PropertySet; import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.script.serializer.JsonMapGenerator; import com.enonic.xp.script.serializer.MapGenerator; +import com.enonic.xp.testing.helper.JsonAssert; import com.enonic.xp.util.GeoPoint; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class PropertyTreeMapperTest { - private static final ObjectMapper MAPPER = new ObjectMapper(). - enable( SerializationFeature.INDENT_OUTPUT ). - enable( SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS ); - @Test public void numbers() throws Exception @@ -110,23 +97,7 @@ public void string() } private void serializeAndAssert( final String name, final PropertyTree value ) - throws Exception { - final String resource = name + ".json"; - final URL url = getClass().getResource( resource ); - - assertNotNull( url, "File [" + resource + "] not found" ); - final JsonNode expectedJson = MAPPER.readTree( url ); - - final JsonMapGenerator generator = new JsonMapGenerator(); - new PropertyTreeMapper( value ).serialize( generator ); - final JsonNode actualJson = (JsonNode) generator.getRoot(); - - final String expectedStr = MAPPER.writeValueAsString( expectedJson ); - final String actualStr = MAPPER.writeValueAsString( actualJson ); - - assertEquals( expectedStr, actualStr ); + JsonAssert.assertMapper( getClass(), name + ".json", new PropertyTreeMapper( value ) ); } - - } diff --git a/modules/itest/itest-core/src/test/java/com/enonic/xp/core/index/IndexServiceImplTest.java b/modules/itest/itest-core/src/test/java/com/enonic/xp/core/index/IndexServiceImplTest.java index 1ca441ddf33..b173c1323b6 100644 --- a/modules/itest/itest-core/src/test/java/com/enonic/xp/core/index/IndexServiceImplTest.java +++ b/modules/itest/itest-core/src/test/java/com/enonic/xp/core/index/IndexServiceImplTest.java @@ -286,7 +286,7 @@ public void getIndexSettings_empty() { final IndexSettings indexSettings = this.indexService.getIndexSettings( testRepoId, IndexType.SEARCH ); - assertNull( indexSettings.getNode().get( "index.invalid_path" ) ); + assertNull( indexSettings.getData().get( "index.invalid_path" ) ); } @Test @@ -300,7 +300,7 @@ public void getIndexSettings() final IndexSettings indexSettings = this.indexService.getIndexSettings( testRepoId, IndexType.SEARCH ); - assertEquals( "\"2\"", indexSettings.getNode().get( "index.number_of_replicas" ).toString() ); + assertEquals( "2", indexSettings.getData().get( "index.number_of_replicas" ) ); } } diff --git a/modules/jaxrs/jaxrs-impl/build.gradle b/modules/jaxrs/jaxrs-impl/build.gradle index de5153e9577..8987ebe14cf 100644 --- a/modules/jaxrs/jaxrs-impl/build.gradle +++ b/modules/jaxrs/jaxrs-impl/build.gradle @@ -4,6 +4,7 @@ dependencies { implementation ( libs.resteasy ) { exclude group: 'org.jboss.spec.javax.ws.rs' } + implementation project( ':core:core-internal' ) testFixturesApi project( ':jaxrs:jaxrs-api' ) testFixturesImplementation ( libs.resteasy ) { @@ -12,7 +13,9 @@ dependencies { testFixturesImplementation libs.jetty.client testFixturesImplementation libs.junit.jupiter.api testFixturesImplementation libs.mockito.core + testFixturesImplementation libs.jackson.jaxrs.jsonprovider testFixturesImplementation ( testFixtures( project( ':core:core-api' ) ) ) + testFixturesImplementation project( ':core:core-internal' ) testImplementation( testFixtures( project(":web:web-jetty") ) ) } diff --git a/modules/jaxrs/jaxrs-impl/src/main/java/com/enonic/xp/jaxrs/impl/CommonFeature.java b/modules/jaxrs/jaxrs-impl/src/main/java/com/enonic/xp/jaxrs/impl/CommonFeature.java index 95cd0bbb46f..3050f3dc105 100644 --- a/modules/jaxrs/jaxrs-impl/src/main/java/com/enonic/xp/jaxrs/impl/CommonFeature.java +++ b/modules/jaxrs/jaxrs-impl/src/main/java/com/enonic/xp/jaxrs/impl/CommonFeature.java @@ -3,9 +3,11 @@ import javax.ws.rs.core.Feature; import javax.ws.rs.core.FeatureContext; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.jaxrs.JaxRsComponent; import com.enonic.xp.jaxrs.impl.exception.JsonExceptionMapper; -import com.enonic.xp.jaxrs.impl.json.JsonObjectProvider; import com.enonic.xp.jaxrs.impl.multipart.MultipartFormReader; import com.enonic.xp.web.multipart.MultipartService; @@ -23,7 +25,7 @@ final class CommonFeature public boolean configure( final FeatureContext context ) { context.register( new MultipartFormReader( this.multipartService ) ); - context.register( new JsonObjectProvider() ); + context.register( new JacksonJsonProvider( ObjectMapperHelper.create() ) ); context.register( new JsonExceptionMapper() ); return true; } diff --git a/modules/jaxrs/jaxrs-impl/src/main/java/com/enonic/xp/jaxrs/impl/json/JsonObjectProvider.java b/modules/jaxrs/jaxrs-impl/src/main/java/com/enonic/xp/jaxrs/impl/json/JsonObjectProvider.java deleted file mode 100644 index 29247640b2a..00000000000 --- a/modules/jaxrs/jaxrs-impl/src/main/java/com/enonic/xp/jaxrs/impl/json/JsonObjectProvider.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.enonic.xp.jaxrs.impl.json; - -import javax.ws.rs.ext.Provider; - -import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; - -import com.enonic.xp.json.ObjectMapperHelper; - -@Provider -public final class JsonObjectProvider - extends JacksonJsonProvider -{ - public JsonObjectProvider() - { - super( ObjectMapperHelper.create() ); - } -} diff --git a/modules/jaxrs/jaxrs-impl/src/testFixtures/java/com/enonic/xp/jaxrs/impl/JaxRsResourceTestSupport.java b/modules/jaxrs/jaxrs-impl/src/testFixtures/java/com/enonic/xp/jaxrs/impl/JaxRsResourceTestSupport.java index ee2ec1cb688..ddc6709f48e 100644 --- a/modules/jaxrs/jaxrs-impl/src/testFixtures/java/com/enonic/xp/jaxrs/impl/JaxRsResourceTestSupport.java +++ b/modules/jaxrs/jaxrs-impl/src/testFixtures/java/com/enonic/xp/jaxrs/impl/JaxRsResourceTestSupport.java @@ -8,7 +8,6 @@ import javax.servlet.http.HttpServletRequest; -import org.jboss.resteasy.core.ResteasyContext; import org.jboss.resteasy.mock.MockDispatcherFactory; import org.jboss.resteasy.spi.Dispatcher; import org.junit.jupiter.api.AfterEach; @@ -20,13 +19,13 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.enonic.xp.context.ContextAccessor; import com.enonic.xp.context.ContextAccessorSupport; import com.enonic.xp.context.LocalScope; -import com.enonic.xp.jaxrs.impl.json.JsonObjectProvider; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.jaxrs.impl.multipart.MultipartFormReader; -import com.enonic.xp.json.ObjectMapperHelper; import com.enonic.xp.session.Session; import com.enonic.xp.session.SessionMock; import com.enonic.xp.web.multipart.MultipartService; @@ -59,11 +58,10 @@ public final void setUp() throws Exception { this.multipartService = Mockito.mock( MultipartService.class ); - final MultipartFormReader reader = new MultipartFormReader( multipartService ); this.dispatcher = MockDispatcherFactory.createDispatcher(); - this.dispatcher.getProviderFactory().register( JsonObjectProvider.class ); - this.dispatcher.getProviderFactory().register( reader ); + this.dispatcher.getProviderFactory().register( new JacksonJsonProvider( MAPPER ) ); + this.dispatcher.getProviderFactory().register( new MultipartFormReader( multipartService ) ); this.dispatcher.getRegistry().addSingletonResource( getResourceInstance() ); mockCurrentContextHttpRequest(); @@ -145,37 +143,8 @@ protected String readFromFile( final String fileName ) } } - protected final void assertArrayEquals( Object[] a1, Object[] a2 ) - { - Assertions.assertEquals( arrayToString( a1 ), arrayToString( a2 ) ); - } - - - protected final String arrayToString( Object[] a ) - { - final StringBuilder result = new StringBuilder( "[" ); - - for ( int i = 0; i < a.length; i++ ) - { - result.append( i ).append( ": " ).append( a[i] ); - if ( i < a.length - 1 ) - { - result.append( ", " ); - } - } - - result.append( "]" ); - - return result.toString(); - } - protected final RestRequestBuilder request() { return new RestRequestBuilder( this.dispatcher ).path( this.basePath ); } - - protected void setHttpRequest( final HttpServletRequest request ) - { - ResteasyContext.getContextDataMap().put( HttpServletRequest.class, request ); - } } diff --git a/modules/lib/lib-common/src/main/java/com/enonic/xp/lib/common/JsonToPropertyTreeTranslator.java b/modules/lib/lib-common/src/main/java/com/enonic/xp/lib/common/JsonToPropertyTreeTranslator.java deleted file mode 100644 index 2434b5562df..00000000000 --- a/modules/lib/lib-common/src/main/java/com/enonic/xp/lib/common/JsonToPropertyTreeTranslator.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.enonic.xp.lib.common; - -import java.util.Iterator; -import java.util.Map; - -import com.fasterxml.jackson.databind.JsonNode; - -import com.enonic.xp.data.PropertySet; -import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.data.Value; -import com.enonic.xp.data.ValueFactory; - -public final class JsonToPropertyTreeTranslator -{ - public static PropertyTree translate( final JsonNode json ) - { - final PropertyTree propertyTree = new PropertyTree(); - traverse( json, propertyTree.getRoot() ); - return propertyTree; - } - - private static void traverse( final JsonNode json, final PropertySet parent ) - { - final Iterator> fields = json.fields(); - - while ( fields.hasNext() ) - { - final Map.Entry next = fields.next(); - addValue( parent, next.getKey(), next.getValue() ); - } - } - - private static void addValue( final PropertySet parent, final String key, final JsonNode value ) - { - if ( value.isArray() ) - { - for ( final JsonNode objNode : value ) - { - addValue( parent, key, objNode ); - } - } - else if ( value.isObject() ) - { - final PropertySet parentSet = parent.addSet( key ); - value.fields().forEachRemaining( ( objectValue ) -> addValue( parentSet, objectValue.getKey(), objectValue.getValue() ) ); - } - else - { - parent.addProperty( key, resolveCoreValue( value ) ); - } - } - - private static Value resolveCoreValue( final JsonNode value ) - { - if ( value.isDouble() ) - { - return ValueFactory.newDouble( value.doubleValue() ); - } - - if ( value.isTextual() ) - { - return ValueFactory.newString( value.textValue() ); - } - - if ( value.isInt() ) - { - return ValueFactory.newLong( (long) value.intValue() ); - } - - if ( value.isLong() ) - { - return ValueFactory.newLong( value.longValue() ); - } - - if ( value.isBoolean() ) - { - return ValueFactory.newBoolean( value.booleanValue() ); - } - - return ValueFactory.newString( value.toString() ); - } -} diff --git a/modules/lib/lib-common/src/test/java/com/enonic/xp/lib/common/JsonToPropertyTreeTranslatorTest.java b/modules/lib/lib-common/src/test/java/com/enonic/xp/lib/common/JsonToPropertyTreeTranslatorTest.java deleted file mode 100644 index 0e03c313606..00000000000 --- a/modules/lib/lib-common/src/test/java/com/enonic/xp/lib/common/JsonToPropertyTreeTranslatorTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.enonic.xp.lib.common; - -import java.net.URL; - -import org.junit.jupiter.api.Test; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import com.enonic.xp.data.Property; -import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.data.ValueTypes; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class JsonToPropertyTreeTranslatorTest -{ - private static final ObjectMapper MAPPER = new ObjectMapper(); - - @Test - public void all_input_types() - throws Exception - { - final JsonNode node = loadJson( "allInputTypes" ); - final PropertyTree data = JsonToPropertyTreeTranslator.translate( node ); - - final Property media = data.getProperty( "media" ); - assertNotNull( media ); - assertEquals( ValueTypes.PROPERTY_SET.getName(), media.getType().getName() ); - } - - @Test - public void map_array_values() - throws Exception - { - final JsonNode node = loadJson( "stringArray" ); - - final PropertyTree data = JsonToPropertyTreeTranslator.translate( node ); - - final Property myArray = data.getProperty( "stringArray" ); - assertNotNull( myArray ); - assertEquals( ValueTypes.STRING.getName(), myArray.getType().getName() ); - - final Property myArray0 = data.getProperty( "stringArray[0]" ); - assertNotNull( myArray0 ); - - final Property myArray1 = data.getProperty( "stringArray[1]" ); - assertNotNull( myArray1 ); - - final Property myArray2 = data.getProperty( "stringArray[2]" ); - assertNotNull( myArray2 ); - } - - @Test - public void boolean_value() - throws Exception - { - final JsonNode node = loadJson( "allInputTypes" ); - - final PropertyTree data = JsonToPropertyTreeTranslator.translate( node ); - - final Property property = data.getProperty( "checkbox" ); - - assertTrue( property.getValue().isBoolean()); - assertEquals( true, property.getBoolean()); - } - - - private JsonNode loadJson( final String name ) - throws Exception - { - final String resource = "/" + getClass().getName().replace( '.', '/' ) + "-" + name + ".json"; - final URL url = getClass().getResource( resource ); - - assertNotNull( url, "File [" + resource + "] not found" ); - return MAPPER.readTree( url ); - } -} - diff --git a/modules/lib/lib-common/src/test/java/com/enonic/xp/lib/common/PropertyTreeMapperTest.java b/modules/lib/lib-common/src/test/java/com/enonic/xp/lib/common/PropertyTreeMapperTest.java index d42319e819d..388cef7fb01 100644 --- a/modules/lib/lib-common/src/test/java/com/enonic/xp/lib/common/PropertyTreeMapperTest.java +++ b/modules/lib/lib-common/src/test/java/com/enonic/xp/lib/common/PropertyTreeMapperTest.java @@ -1,29 +1,16 @@ package com.enonic.xp.lib.common; -import java.net.URL; - import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - import com.enonic.xp.data.PropertySet; import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.script.serializer.JsonMapGenerator; import com.enonic.xp.script.serializer.MapGenerator; +import com.enonic.xp.testing.helper.JsonAssert; import com.enonic.xp.util.GeoPoint; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - public class PropertyTreeMapperTest { - private static final ObjectMapper MAPPER = new ObjectMapper(). - enable( SerializationFeature.INDENT_OUTPUT ). - enable( SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS ); - @Test public void numbers() throws Exception @@ -110,23 +97,7 @@ public void string() } private void serializeAndAssert( final String name, final PropertyTree value ) - throws Exception { - final String resource = name + ".json"; - final URL url = getClass().getResource( resource ); - - assertNotNull( url, "File [" + resource + "] not found" ); - final JsonNode expectedJson = MAPPER.readTree( url ); - - final JsonMapGenerator generator = new JsonMapGenerator(); - new PropertyTreeMapper( value ).serialize( generator ); - final JsonNode actualJson = (JsonNode) generator.getRoot(); - - final String expectedStr = MAPPER.writeValueAsString( expectedJson ); - final String actualStr = MAPPER.writeValueAsString( actualJson ); - - assertEquals( expectedStr, actualStr ); + JsonAssert.assertMapper( getClass(), name + ".json", new PropertyTreeMapper( value ) ); } - - } diff --git a/modules/lib/lib-content/src/main/java/com/enonic/xp/lib/content/QueryContentHandler.java b/modules/lib/lib-content/src/main/java/com/enonic/xp/lib/content/QueryContentHandler.java index 56bb2cece63..ecaba38a402 100644 --- a/modules/lib/lib-content/src/main/java/com/enonic/xp/lib/content/QueryContentHandler.java +++ b/modules/lib/lib-content/src/main/java/com/enonic/xp/lib/content/QueryContentHandler.java @@ -11,8 +11,8 @@ import com.enonic.xp.content.Contents; import com.enonic.xp.content.FindContentIdsByQueryResult; import com.enonic.xp.content.GetContentByIdsParams; +import com.enonic.xp.data.PropertyTree; import com.enonic.xp.lib.common.JsonToFilterMapper; -import com.enonic.xp.lib.common.JsonToPropertyTreeTranslator; import com.enonic.xp.lib.content.mapper.ContentsResultMapper; import com.enonic.xp.query.aggregation.AggregationQuery; import com.enonic.xp.query.expr.ConstraintExpr; @@ -26,7 +26,6 @@ import com.enonic.xp.query.parser.QueryParser; import com.enonic.xp.schema.content.ContentTypeNames; import com.enonic.xp.script.ScriptValue; -import com.enonic.xp.util.JsonHelper; @SuppressWarnings("unused") public final class QueryContentHandler @@ -94,14 +93,14 @@ else if ( sort.isValue() ) else if ( sort.isObject() ) { - return List.of( DslOrderExpr.from( JsonToPropertyTreeTranslator.translate( JsonHelper.from( sort.getMap() ) ) ) ); + return List.of( DslOrderExpr.from( PropertyTree.fromMap( sort.getMap() ) ) ); } else if ( sort.isArray() ) { return sort.getArray() .stream() - .map( expr -> DslOrderExpr.from( JsonToPropertyTreeTranslator.translate( JsonHelper.from( expr.getMap() ) ) ) ) + .map( expr -> DslOrderExpr.from( PropertyTree.fromMap( expr.getMap() ) ) ) .collect( Collectors.toList() ); } @@ -120,7 +119,7 @@ else if ( query.isValue() ) } else if ( query.isObject() ) { - return DslExpr.from( JsonToPropertyTreeTranslator.translate( JsonHelper.from( query.getMap() ) ) ); + return DslExpr.from( PropertyTree.fromMap( query.getMap() ) ); } throw new IllegalArgumentException( "query must be a String or JSON object" ); diff --git a/modules/lib/lib-content/src/test/java/com/enonic/xp/lib/content/QueryContentHandlerTest.java b/modules/lib/lib-content/src/test/java/com/enonic/xp/lib/content/QueryContentHandlerTest.java index 7fda5efd0da..174f5dc2f6c 100644 --- a/modules/lib/lib-content/src/test/java/com/enonic/xp/lib/content/QueryContentHandlerTest.java +++ b/modules/lib/lib-content/src/test/java/com/enonic/xp/lib/content/QueryContentHandlerTest.java @@ -34,9 +34,9 @@ import com.enonic.xp.lib.content.mapper.ContentsResultMapper; import com.enonic.xp.resource.ResourceKey; import com.enonic.xp.script.ScriptValue; -import com.enonic.xp.script.serializer.JsonMapGenerator; import com.enonic.xp.security.PrincipalKey; import com.enonic.xp.sortvalues.SortValuesProperty; +import com.enonic.xp.testing.serializer.JsonMapGenerator; public class QueryContentHandlerTest extends BaseContentHandlerTest diff --git a/modules/lib/lib-content/src/test/java/com/enonic/xp/lib/content/mapper/DuplicateContentsResultMapperTest.java b/modules/lib/lib-content/src/test/java/com/enonic/xp/lib/content/mapper/DuplicateContentsResultMapperTest.java index f5e6c0aee0b..cd651ba576a 100644 --- a/modules/lib/lib-content/src/test/java/com/enonic/xp/lib/content/mapper/DuplicateContentsResultMapperTest.java +++ b/modules/lib/lib-content/src/test/java/com/enonic/xp/lib/content/mapper/DuplicateContentsResultMapperTest.java @@ -7,7 +7,7 @@ import com.enonic.xp.content.ContentId; import com.enonic.xp.content.ContentPath; import com.enonic.xp.content.DuplicateContentsResult; -import com.enonic.xp.script.serializer.JsonMapGenerator; +import com.enonic.xp.testing.serializer.JsonMapGenerator; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/modules/lib/lib-context/src/test/java/com/enonic/xp/lib/context/ContextMapperTest.java b/modules/lib/lib-context/src/test/java/com/enonic/xp/lib/context/ContextMapperTest.java index 81c62507663..acd64f2c62d 100644 --- a/modules/lib/lib-context/src/test/java/com/enonic/xp/lib/context/ContextMapperTest.java +++ b/modules/lib/lib-context/src/test/java/com/enonic/xp/lib/context/ContextMapperTest.java @@ -8,7 +8,6 @@ import com.enonic.xp.context.Context; import com.enonic.xp.context.ContextBuilder; import com.enonic.xp.repository.RepositoryId; -import com.enonic.xp.script.serializer.JsonMapGenerator; import com.enonic.xp.script.serializer.MapGenerator; import com.enonic.xp.script.serializer.MapSerializable; import com.enonic.xp.security.PrincipalKey; @@ -16,6 +15,7 @@ import com.enonic.xp.security.User; import com.enonic.xp.security.auth.AuthenticationInfo; import com.enonic.xp.session.SessionMock; +import com.enonic.xp.testing.serializer.JsonMapGenerator; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; diff --git a/modules/lib/lib-node/build.gradle b/modules/lib/lib-node/build.gradle index 814e80529f3..914beccf8e8 100644 --- a/modules/lib/lib-node/build.gradle +++ b/modules/lib/lib-node/build.gradle @@ -5,5 +5,6 @@ dependencies { implementation project( ':lib:lib-value' ) implementation project( ':lib:lib-common' ) + testImplementation project( ':core:core-internal' ) testImplementation project( ':tools:testing' ) } diff --git a/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/AbstractFindNodesQueryHandler.java b/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/AbstractFindNodesQueryHandler.java index 57f61b93029..88123905c62 100644 --- a/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/AbstractFindNodesQueryHandler.java +++ b/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/AbstractFindNodesQueryHandler.java @@ -4,8 +4,8 @@ import java.util.Map; import java.util.stream.Collectors; +import com.enonic.xp.data.PropertyTree; import com.enonic.xp.lib.common.JsonToFilterMapper; -import com.enonic.xp.lib.common.JsonToPropertyTreeTranslator; import com.enonic.xp.node.NodeQuery; import com.enonic.xp.query.aggregation.AggregationQueries; import com.enonic.xp.query.expr.ConstraintExpr; @@ -18,7 +18,6 @@ import com.enonic.xp.query.parser.QueryParser; import com.enonic.xp.query.suggester.SuggestionQueries; import com.enonic.xp.script.ScriptValue; -import com.enonic.xp.util.JsonHelper; abstract class AbstractFindNodesQueryHandler extends AbstractNodeHandler @@ -92,7 +91,7 @@ else if ( query.isValue() ) } else if ( query.isObject() ) { - return DslExpr.from( JsonToPropertyTreeTranslator.translate( JsonHelper.from( query.getMap() ) ) ); + return DslExpr.from( PropertyTree.fromMap( query.getMap() ) ); } throw new IllegalArgumentException( "query must be a String or JSON object" ); } @@ -109,15 +108,13 @@ private List buildOrderExpr() } else if ( sort.isObject() ) { - - return List.of( DslOrderExpr.from( JsonToPropertyTreeTranslator.translate( JsonHelper.from( sort.getMap() ) ) ) ); - + return List.of( DslOrderExpr.from( PropertyTree.fromMap( sort.getMap() ) ) ); } else if ( sort.isArray() ) { return sort.getArray() .stream() - .map( expr -> DslOrderExpr.from( JsonToPropertyTreeTranslator.translate( JsonHelper.from( expr.getMap() ) ) ) ) + .map( expr -> DslOrderExpr.from( PropertyTree.fromMap( expr.getMap() ) ) ) .collect( Collectors.toList() ); } diff --git a/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/AbstractNodeHandler.java b/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/AbstractNodeHandler.java index 9f7e6b2eef1..bcbec795dbb 100644 --- a/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/AbstractNodeHandler.java +++ b/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/AbstractNodeHandler.java @@ -95,6 +95,5 @@ public B nodeService( final NodeService val ) nodeService = val; return (B) this; } - } } diff --git a/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/NodeHandler.java b/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/NodeHandler.java index e401b7c3498..54c1b5ec0c0 100644 --- a/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/NodeHandler.java +++ b/modules/lib/lib-node/src/main/java/com/enonic/xp/lib/node/NodeHandler.java @@ -36,7 +36,10 @@ public NodeHandler( final Context context, final NodeService nodeService ) @SuppressWarnings("unused") public Object create( final ScriptValue params ) { - return execute( CreateNodeHandler.create().nodeService( this.nodeService ).params( params ).build() ); + return execute( CreateNodeHandler.create() + .nodeService( this.nodeService ) + .params( params ) + .build() ); } @SuppressWarnings("unused") @@ -64,7 +67,10 @@ public Object get( final GetNodeHandlerParams params ) @SuppressWarnings("unused") public Object delete( final String[] keys ) { - return execute( DeleteNodeHandler.create().nodeService( this.nodeService ).keys( NodeKeys.from( keys ) ).build() ); + return execute( DeleteNodeHandler.create() + .nodeService( this.nodeService ) + .keys( NodeKeys.from( keys ) ) + .build() ); } @SuppressWarnings("unused") diff --git a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/IndexConfigFactoryTest.java b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/IndexConfigFactoryTest.java index da26caa97e9..6d049a0a49a 100644 --- a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/IndexConfigFactoryTest.java +++ b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/IndexConfigFactoryTest.java @@ -4,7 +4,6 @@ import org.junit.jupiter.api.Test; -import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableSortedSet; import com.enonic.xp.data.PropertyPath; @@ -15,10 +14,10 @@ import com.enonic.xp.index.IndexValueProcessor; import com.enonic.xp.index.PathIndexConfig; import com.enonic.xp.index.PatternIndexConfigDocument; -import com.enonic.xp.lib.common.JsonToPropertyTreeTranslator; -import com.enonic.xp.util.JsonHelper; +import com.enonic.xp.core.internal.json.JsonHelper; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -107,9 +106,7 @@ public void unknown_alias() private IndexConfigDocument create( final String json ) { - final JsonNode node = JsonHelper.from( json ); - - final PropertyTree properties = JsonToPropertyTreeTranslator.translate( node ); + final PropertyTree properties = PropertyTree.fromMap( JsonHelper.toMap( JsonHelper.from( json ) ) ); return new IndexConfigFactory( properties.getRoot() ).create(); } @@ -133,7 +130,7 @@ private PatternIndexConfigDocument createFullConfig() " \"indexValueProcessors\": []\n" + " }\n" + " }\n" + " ]\n" + " }" ); - assertTrue( indexConfigDoc instanceof PatternIndexConfigDocument ); + assertInstanceOf( PatternIndexConfigDocument.class, indexConfigDoc ); return (PatternIndexConfigDocument) indexConfigDoc; } diff --git a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/PermissionsFactoryTest.java b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/PermissionsFactoryTest.java index 2370addc40c..5e481ffb53d 100644 --- a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/PermissionsFactoryTest.java +++ b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/PermissionsFactoryTest.java @@ -4,16 +4,13 @@ import org.junit.jupiter.api.Test; -import com.fasterxml.jackson.databind.JsonNode; - import com.enonic.xp.data.PropertyTree; -import com.enonic.xp.lib.common.JsonToPropertyTreeTranslator; import com.enonic.xp.security.PrincipalKey; import com.enonic.xp.security.RoleKeys; import com.enonic.xp.security.acl.AccessControlEntry; import com.enonic.xp.security.acl.AccessControlList; import com.enonic.xp.security.acl.Permission; -import com.enonic.xp.util.JsonHelper; +import com.enonic.xp.core.internal.json.JsonHelper; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -110,9 +107,7 @@ private void checkDenied( final AccessControlList acl, final String principalKey private AccessControlList create( final String json ) { - final JsonNode node = JsonHelper.from( json ); - - final PropertyTree properties = JsonToPropertyTreeTranslator.translate( node ); + final PropertyTree properties = PropertyTree.fromMap( JsonHelper.toMap( JsonHelper.from( json ) ) ); return new PermissionsFactory( properties.getRoot().getSets( "_permissions" ) ).create(); } diff --git a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/AggregationMapperTest.java b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/AggregationMapperTest.java index bf4b2cd1680..7258afe658f 100644 --- a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/AggregationMapperTest.java +++ b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/AggregationMapperTest.java @@ -6,7 +6,7 @@ import com.enonic.xp.aggregation.Aggregations; import com.enonic.xp.aggregation.SingleValueMetricAggregation; -import com.enonic.xp.script.serializer.JsonMapGenerator; +import com.enonic.xp.testing.serializer.JsonMapGenerator; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/BaseMapperTest.java b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/BaseMapperTest.java deleted file mode 100644 index d8644de51ed..00000000000 --- a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/BaseMapperTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.enonic.xp.lib.node.mapper; - -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import com.enonic.xp.json.ObjectMapperHelper; -import com.enonic.xp.node.NodeBranchEntry; -import com.enonic.xp.node.NodeId; -import com.enonic.xp.node.NodePath; -import com.enonic.xp.script.serializer.JsonMapGenerator; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public abstract class BaseMapperTest -{ - private static final ObjectMapper MAPPER = ObjectMapperHelper.create(); - - NodeBranchEntry createEntry( final String a ) - { - return NodeBranchEntry.create(). - nodeId( NodeId.from( a ) ). - nodePath( new NodePath( "/" + a ) ). - build(); - } - - - void assertJson( final String fileName, final JsonMapGenerator actualNode ) - throws Exception - { - final JsonNode expectedNode = MAPPER.readTree( readFromFile( fileName ) ); - - assertEquals( expectedNode, actualNode.getRoot() ); - } - - private String readFromFile( final String fileName ) - throws Exception - { - final InputStream stream = - Objects.requireNonNull( getClass().getResourceAsStream( fileName ), "Resource file [" + fileName + "] not found" ); - try (stream) - { - return new String( stream.readAllBytes(), StandardCharsets.UTF_8 ); - } - } -} diff --git a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/IndexConfigDocMapperTest.java b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/IndexConfigDocMapperTest.java index cf32451c419..913764fdb92 100644 --- a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/IndexConfigDocMapperTest.java +++ b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/IndexConfigDocMapperTest.java @@ -5,10 +5,9 @@ import com.enonic.xp.index.IndexConfig; import com.enonic.xp.index.IndexConfigDocument; import com.enonic.xp.index.PatternIndexConfigDocument; -import com.enonic.xp.script.serializer.JsonMapGenerator; +import com.enonic.xp.testing.helper.JsonAssert; public class IndexConfigDocMapperTest - extends BaseMapperTest { @Test public void all() @@ -28,9 +27,6 @@ public void all() add( "property1.*.property3", IndexConfig.create( IndexConfig.BY_TYPE ).addLanguage( "en" ).build() ). build(); - final JsonMapGenerator jsonGenerator = new JsonMapGenerator(); - new IndexConfigDocMapper( doc ).serialize( jsonGenerator ); - - assertJson( "index_config_full.json", jsonGenerator ); + JsonAssert.assertMapper( getClass(), "index_config_full.json", new IndexConfigDocMapper( doc ) ); } } diff --git a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/NodeMultiRepoQueryResultMapperTest.java b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/NodeMultiRepoQueryResultMapperTest.java index 4bf1a0502fe..cb31f95906a 100644 --- a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/NodeMultiRepoQueryResultMapperTest.java +++ b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/NodeMultiRepoQueryResultMapperTest.java @@ -10,11 +10,11 @@ import com.enonic.xp.node.NodeId; import com.enonic.xp.query.QueryExplanation; import com.enonic.xp.repository.RepositoryId; -import com.enonic.xp.script.serializer.JsonMapGenerator; import com.enonic.xp.suggester.Suggestions; import com.enonic.xp.suggester.TermSuggestion; import com.enonic.xp.suggester.TermSuggestionEntry; import com.enonic.xp.suggester.TermSuggestionOption; +import com.enonic.xp.testing.serializer.JsonMapGenerator; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; diff --git a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/PushNodesResultMapperTest.java b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/PushNodesResultMapperTest.java index 7da4f3e0dd0..ca0b662bf0d 100644 --- a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/PushNodesResultMapperTest.java +++ b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/PushNodesResultMapperTest.java @@ -2,12 +2,13 @@ import org.junit.jupiter.api.Test; +import com.enonic.xp.node.NodeBranchEntry; +import com.enonic.xp.node.NodeId; import com.enonic.xp.node.NodePath; import com.enonic.xp.node.PushNodesResult; -import com.enonic.xp.script.serializer.JsonMapGenerator; +import com.enonic.xp.testing.helper.JsonAssert; public class PushNodesResultMapperTest - extends BaseMapperTest { @Test public void single_successful() @@ -15,10 +16,7 @@ public void single_successful() { final PushNodesResult result = PushNodesResult.create().addSuccess( createEntry( "a" ), new NodePath( "/a" ) ).build(); - final JsonMapGenerator jsonGenerator = new JsonMapGenerator(); - new PushNodesResultMapper( result ).serialize( jsonGenerator ); - - assertJson( "nodeResult/single_successful.json", jsonGenerator ); + JsonAssert.assertMapper( getClass(), "nodeResult/single_successful.json", new PushNodesResultMapper( result ) ); } @Test @@ -29,10 +27,7 @@ public void single_failed() addFailed( createEntry( "a" ), PushNodesResult.Reason.ACCESS_DENIED ). build(); - final JsonMapGenerator jsonGenerator = new JsonMapGenerator(); - new PushNodesResultMapper( result ).serialize( jsonGenerator ); - - assertJson( "nodeResult/single_failed.json", jsonGenerator ); + JsonAssert.assertMapper( getClass(), "nodeResult/single_failed.json", new PushNodesResultMapper( result ) ); } @Test @@ -48,10 +43,14 @@ public void complex() .addFailed( createEntry( "f" ), PushNodesResult.Reason.PARENT_NOT_FOUND ) .build(); - final JsonMapGenerator jsonGenerator = new JsonMapGenerator(); - new PushNodesResultMapper( result ).serialize( jsonGenerator ); - - assertJson( "nodeResult/full.json", jsonGenerator ); + JsonAssert.assertMapper( getClass(), "nodeResult/full.json", new PushNodesResultMapper( result ) ); } + static NodeBranchEntry createEntry( final String a ) + { + return NodeBranchEntry.create(). + nodeId( NodeId.from( a ) ). + nodePath( new NodePath( "/" + a ) ). + build(); + } } diff --git a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/ResolveSyncWorkResultMapperTest.java b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/ResolveSyncWorkResultMapperTest.java index 7a4290310a7..9334cc0286f 100644 --- a/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/ResolveSyncWorkResultMapperTest.java +++ b/modules/lib/lib-node/src/test/java/com/enonic/xp/lib/node/mapper/ResolveSyncWorkResultMapperTest.java @@ -3,12 +3,14 @@ import org.junit.jupiter.api.Test; import com.enonic.xp.content.CompareStatus; +import com.enonic.xp.node.NodeBranchEntry; import com.enonic.xp.node.NodeComparison; +import com.enonic.xp.node.NodeId; +import com.enonic.xp.node.NodePath; import com.enonic.xp.node.ResolveSyncWorkResult; -import com.enonic.xp.script.serializer.JsonMapGenerator; +import com.enonic.xp.testing.helper.JsonAssert; public class ResolveSyncWorkResultMapperTest - extends BaseMapperTest { @Test public void full() @@ -20,9 +22,14 @@ public void full() add( new NodeComparison( createEntry( "c" ), createEntry( "c" ), CompareStatus.NEWER ) ). build(); - final JsonMapGenerator jsonGenerator = new JsonMapGenerator(); - new ResolveSyncWorkResultMapper( result ).serialize( jsonGenerator ); + JsonAssert.assertMapper( getClass(), "resolveSyncWork/full.json", new ResolveSyncWorkResultMapper( result ) ); + } - assertJson( "resolveSyncWork/full.json", jsonGenerator ); + static NodeBranchEntry createEntry( final String a ) + { + return NodeBranchEntry.create(). + nodeId( NodeId.from( a ) ). + nodePath( new NodePath( "/" + a ) ). + build(); } } diff --git a/modules/lib/lib-project/src/test/java/com/enonic/xp/lib/project/BaseProjectHandlerTest.java b/modules/lib/lib-project/src/test/java/com/enonic/xp/lib/project/BaseProjectHandlerTest.java index 28a4a45027d..be18f88766f 100644 --- a/modules/lib/lib-project/src/test/java/com/enonic/xp/lib/project/BaseProjectHandlerTest.java +++ b/modules/lib/lib-project/src/test/java/com/enonic/xp/lib/project/BaseProjectHandlerTest.java @@ -17,7 +17,6 @@ import com.enonic.xp.content.UpdateContentParams; import com.enonic.xp.data.PropertyTree; import com.enonic.xp.form.PropertyTreeMarshallerService; -import com.enonic.xp.lib.common.ObjectToValueMapper; import com.enonic.xp.project.CreateProjectParams; import com.enonic.xp.project.ModifyProjectParams; import com.enonic.xp.project.Project; @@ -126,14 +125,7 @@ protected void mockMarshaller() when( this.propertyTreeMarshallerService.marshal( isA( Map.class ) ) ).thenAnswer( mock -> { final Map map = (Map) mock.getArguments()[0]; - final PropertyTree tree = new PropertyTree(); - - for ( String key : map.keySet() ) - { - tree.addProperty( key, ObjectToValueMapper.map( map.get( key ) ) ); - } - - return tree; + return PropertyTree.fromMap( map ); } ); } diff --git a/modules/lib/lib-repo/src/main/java/com/enonic/xp/lib/repo/CreateRepositoryHandler.java b/modules/lib/lib-repo/src/main/java/com/enonic/xp/lib/repo/CreateRepositoryHandler.java index d16c8e7cee2..d0ffb1d563f 100644 --- a/modules/lib/lib-repo/src/main/java/com/enonic/xp/lib/repo/CreateRepositoryHandler.java +++ b/modules/lib/lib-repo/src/main/java/com/enonic/xp/lib/repo/CreateRepositoryHandler.java @@ -5,9 +5,6 @@ import java.util.function.Supplier; import java.util.stream.Collectors; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - import com.enonic.xp.index.ChildOrder; import com.enonic.xp.index.IndexType; import com.enonic.xp.lib.repo.mapper.RepositoryMapper; @@ -32,8 +29,6 @@ public class CreateRepositoryHandler implements ScriptBean { - private static final ObjectMapper MAPPER = new ObjectMapper(); - private RepositoryId repositoryId; private IndexDefinitions indexDefinitions; @@ -87,11 +82,13 @@ public void setIndexDefinitions( final ScriptValue data ) if ( indexDefinitionMap != null ) { final Map indexDefinitionSettingsMap = (Map) indexDefinitionMap.get( "settings" ); - IndexSettings indexSettings = - indexDefinitionSettingsMap == null ? null : new IndexSettings( createJson( indexDefinitionSettingsMap ) ); + IndexSettings indexSettings; + indexSettings = + indexDefinitionSettingsMap == null ? null : IndexSettings.from( indexDefinitionSettingsMap ); final Map indexDefinitionMappingMap = (Map) indexDefinitionMap.get( "mapping" ); - IndexMapping indexMapping = - indexDefinitionMappingMap == null ? null : new IndexMapping( createJson( indexDefinitionMappingMap ) ); + IndexMapping indexMapping; + indexMapping = + indexDefinitionMappingMap == null ? null : IndexMapping.from( indexDefinitionMappingMap ); final IndexDefinition indexDefinition = IndexDefinition.create().settings( indexSettings ).mapping( indexMapping ).build(); indexDefinitionsBuilder.add( indexType, indexDefinition ); @@ -154,11 +151,6 @@ private List resolvePermissions( ScriptValue permissions ) collect( Collectors.toUnmodifiableList() ); } - private JsonNode createJson( final Map value ) - { - return MAPPER.valueToTree( value ); - } - @Override public void initialize( final BeanContext context ) { diff --git a/modules/lib/lib-repo/src/main/java/com/enonic/xp/lib/repo/mapper/RepositoryMapper.java b/modules/lib/lib-repo/src/main/java/com/enonic/xp/lib/repo/mapper/RepositoryMapper.java index 437880d6582..276ea85507d 100644 --- a/modules/lib/lib-repo/src/main/java/com/enonic/xp/lib/repo/mapper/RepositoryMapper.java +++ b/modules/lib/lib-repo/src/main/java/com/enonic/xp/lib/repo/mapper/RepositoryMapper.java @@ -1,11 +1,8 @@ package com.enonic.xp.lib.repo.mapper; -import com.fasterxml.jackson.databind.JsonNode; - import com.enonic.xp.branch.Branches; import com.enonic.xp.data.PropertyTree; import com.enonic.xp.index.IndexType; -import com.enonic.xp.lib.common.JsonToPropertyTreeTranslator; import com.enonic.xp.lib.common.PropertyTreeMapper; import com.enonic.xp.repository.IndexDefinition; import com.enonic.xp.repository.IndexDefinitions; @@ -31,7 +28,7 @@ public void serialize( final MapGenerator gen ) gen.value( "transient", repository.isTransient() ); serialize( gen, repository.getBranches() ); serialize( gen, repository.getSettings() ); - serialize( gen, repository.getData() ); + serialize( "data", gen, repository.getData() ); } private void serialize( final MapGenerator gen, final Branches branches ) @@ -48,9 +45,9 @@ private void serialize( final MapGenerator gen, final RepositorySettings setting gen.end(); } - private void serialize( final MapGenerator gen, final PropertyTree repositoryData ) + private void serialize( String field, final MapGenerator gen, final PropertyTree repositoryData ) { - gen.map( "data" ); + gen.map( field ); new PropertyTreeMapper( repositoryData ).serialize( gen ); gen.end(); } @@ -69,17 +66,12 @@ private void serialize( final MapGenerator gen, final IndexDefinitions indexDefi if ( indexDefinition.getSettings() != null ) { - gen.map( "settings" ); - serialize( gen, indexDefinition.getSettings().getNode() ); - gen.end(); + serialize( "settings", gen, PropertyTree.fromMap( indexDefinition.getSettings().getData() ) ); } if ( indexDefinition.getMapping() != null ) { - - gen.map( "mapping" ); - serialize( gen, indexDefinition.getMapping().getNode() ); - gen.end(); + serialize( "mapping", gen, PropertyTree.fromMap( indexDefinition.getMapping().getData() ) ); } gen.end(); @@ -88,10 +80,4 @@ private void serialize( final MapGenerator gen, final IndexDefinitions indexDefi gen.end(); } } - - private void serialize( final MapGenerator gen, final JsonNode jsonNode ) - { - final PropertyTree propertyTree = JsonToPropertyTreeTranslator.translate( jsonNode ); - new PropertyTreeMapper( propertyTree ).serialize( gen ); - } } diff --git a/modules/script/script-api/src/test/java/com/enonic/xp/script/event/ScriptEventListenerImplTest.java b/modules/script/script-api/src/test/java/com/enonic/xp/script/event/ScriptEventListenerImplTest.java index 1a795bf2f20..d72564b677e 100644 --- a/modules/script/script-api/src/test/java/com/enonic/xp/script/event/ScriptEventListenerImplTest.java +++ b/modules/script/script-api/src/test/java/com/enonic/xp/script/event/ScriptEventListenerImplTest.java @@ -7,7 +7,6 @@ import com.enonic.xp.app.ApplicationKey; import com.enonic.xp.event.Event; -import com.enonic.xp.script.serializer.JsonMapGenerator; import com.enonic.xp.script.serializer.MapSerializable; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -67,11 +66,6 @@ public void testEvent() assertNotNull( this.event ); assertTrue( this.event instanceof MapSerializable ); - - final MapSerializable serializable = (MapSerializable) this.event; - final JsonMapGenerator generator = new JsonMapGenerator(); - - serializable.serialize( generator ); } @Test diff --git a/modules/server/server-rest/src/main/java/com/enonic/xp/impl/server/rest/ModelToStringHelper.java b/modules/server/server-rest/src/main/java/com/enonic/xp/impl/server/rest/ModelToStringHelper.java index 6d434847b4c..c4df04e23ac 100644 --- a/modules/server/server-rest/src/main/java/com/enonic/xp/impl/server/rest/ModelToStringHelper.java +++ b/modules/server/server-rest/src/main/java/com/enonic/xp/impl/server/rest/ModelToStringHelper.java @@ -3,7 +3,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.enonic.xp.json.ObjectMapperHelper; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; public final class ModelToStringHelper { diff --git a/modules/server/server-rest/src/main/java/com/enonic/xp/impl/server/rest/StatusResource.java b/modules/server/server-rest/src/main/java/com/enonic/xp/impl/server/rest/StatusResource.java deleted file mode 100644 index ccfb9239def..00000000000 --- a/modules/server/server-rest/src/main/java/com/enonic/xp/impl/server/rest/StatusResource.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.enonic.xp.impl.server.rest; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import javax.annotation.security.RolesAllowed; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Reference; -import org.osgi.service.component.annotations.ReferenceCardinality; -import org.osgi.service.component.annotations.ReferencePolicy; - -import com.enonic.xp.jaxrs.JaxRsComponent; -import com.enonic.xp.security.RoleKeys; -import com.enonic.xp.status.StatusReporter; -import com.enonic.xp.util.Exceptions; - -@Path("/status") -@Produces(MediaType.APPLICATION_JSON) -@RolesAllowed(RoleKeys.ADMIN_ID) -@Component(immediate = true, property = "group=api") -public final class StatusResource - implements JaxRsComponent -{ - private static final String SERVER_REPORTER_NAME = "server"; - - private StatusReporter serverReporter; - - @GET - @Path("server") - public String server() - { - final ByteArrayOutputStream response = new ByteArrayOutputStream(); - try - { - StatusReporter serverReporter = this.serverReporter; - if (serverReporter == null) { - throw new WebApplicationException( "Server reporter not found", Response.Status.NOT_FOUND ); - } - serverReporter.report( response ); - } - catch ( IOException e ) - { - throw Exceptions.unchecked( e ); - } - return response.toString( serverReporter.getMediaType().charset().or( StandardCharsets.UTF_8 ) ); - } - - @SuppressWarnings("UnusedDeclaration") - @Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE) - public void addStatusReporter( final StatusReporter reporter ) - { - if ( SERVER_REPORTER_NAME.equals( reporter.getName() ) ) - { - this.serverReporter = reporter; - } - } - - @SuppressWarnings("UnusedDeclaration") - public void removeStatusReporter( final StatusReporter reporter ) - { - if ( SERVER_REPORTER_NAME.equals( reporter.getName() ) ) - { - this.serverReporter = null; - } - } -} diff --git a/modules/server/server-rest/src/test/java/com/enonic/xp/impl/server/rest/ApplicationResourceTest.java b/modules/server/server-rest/src/test/java/com/enonic/xp/impl/server/rest/ApplicationResourceTest.java index b5b65c76c65..8f527722285 100644 --- a/modules/server/server-rest/src/test/java/com/enonic/xp/impl/server/rest/ApplicationResourceTest.java +++ b/modules/server/server-rest/src/test/java/com/enonic/xp/impl/server/rest/ApplicationResourceTest.java @@ -139,7 +139,7 @@ public void install_url_not_allowed_protocol() entity( "{\"URL\":\"" + application.getUrl() + "\"}", MediaType.APPLICATION_JSON_TYPE ). post().getAsString(); - assertEquals( "{\"applicationInstalledJson\":null,\"failure\":\"Illegal protocol: ftp\"}", jsonString ); + assertEquals( "{\"failure\":\"Illegal protocol: ftp\"}", jsonString ); } @Test @@ -155,7 +155,7 @@ public void install_url_process_error() entity( "{\"URL\":\"" + application.getUrl() + "\"}", MediaType.APPLICATION_JSON_TYPE ). post().getAsString(); - assertEquals( "{\"applicationInstalledJson\":null,\"failure\":\"Failed to process application from http://enonic.net\"}", + assertEquals( "{\"failure\":\"Failed to process application from http://enonic.net\"}", jsonString ); } @@ -169,7 +169,7 @@ public void install_invalid_url() entity( "{\"URL\":\"" + application.getUrl() + "\"}", MediaType.APPLICATION_JSON_TYPE ). post().getAsString(); - assertEquals( "{\"applicationInstalledJson\":null,\"failure\":\"Failed to upload application from invalid url\"}", jsonString ); + assertEquals( "{\"failure\":\"Failed to upload application from invalid url\"}", jsonString ); } @Test diff --git a/modules/server/server-rest/src/test/java/com/enonic/xp/impl/server/rest/StatusResourceTest.java b/modules/server/server-rest/src/test/java/com/enonic/xp/impl/server/rest/StatusResourceTest.java deleted file mode 100644 index 8023f3b4287..00000000000 --- a/modules/server/server-rest/src/test/java/com/enonic/xp/impl/server/rest/StatusResourceTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.enonic.xp.impl.server.rest; - -import java.io.IOException; -import java.io.OutputStream; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; - -import com.google.common.net.MediaType; - -import com.enonic.xp.jaxrs.impl.JaxRsResourceTestSupport; -import com.enonic.xp.status.StatusReporter; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class StatusResourceTest - extends JaxRsResourceTestSupport -{ - private StatusReporter serverReporter; - - @BeforeEach - public void setup() - throws Exception - { - } - - @Override - protected StatusResource getResourceInstance() - { - serverReporter = mock( StatusReporter.class ); - when( serverReporter.getName() ).thenReturn( "server" ); - - final StatusResource resource = new StatusResource(); - resource.addStatusReporter( serverReporter ); - when( serverReporter.getMediaType() ).thenReturn( MediaType.PLAIN_TEXT_UTF_8 ); - return resource; - } - - @Test - public void server() - throws Exception - { - final ArgumentCaptor commentCaptor = ArgumentCaptor.forClass( OutputStream.class ); - - request().path( "status/server" ).get(); - - Mockito.verify( serverReporter ).report( commentCaptor.capture() ); - Mockito.verify( serverReporter, Mockito.times( 1 ) ).report( any( OutputStream.class ) ); - } - - @Test - public void server_error() - throws Exception - { - Mockito.doThrow( new IOException( "error_message" ) ).when( serverReporter ).report( any( OutputStream.class ) ); - - assertThrows( IOException.class, () -> request().path( "status/server" ).get() ); - } -} diff --git a/modules/server/server-rest/src/test/resources/com/enonic/xp/impl/server/rest/install_url_result.json b/modules/server/server-rest/src/test/resources/com/enonic/xp/impl/server/rest/install_url_result.json index 8498befde6f..044e79d6ad0 100644 --- a/modules/server/server-rest/src/test/resources/com/enonic/xp/impl/server/rest/install_url_result.json +++ b/modules/server/server-rest/src/test/resources/com/enonic/xp/impl/server/rest/install_url_result.json @@ -15,6 +15,5 @@ "vendorUrl": "https://www.enonic.com", "version": "1.0.0" } - }, - "failure": null -} \ No newline at end of file + } +} diff --git a/modules/server/server-rest/src/test/resources/com/enonic/xp/impl/server/rest/list_scheduled_jobs.json b/modules/server/server-rest/src/test/resources/com/enonic/xp/impl/server/rest/list_scheduled_jobs.json index e08aee2b391..7cb8bd0641a 100644 --- a/modules/server/server-rest/src/test/resources/com/enonic/xp/impl/server/rest/list_scheduled_jobs.json +++ b/modules/server/server-rest/src/test/resources/com/enonic/xp/impl/server/rest/list_scheduled_jobs.json @@ -36,14 +36,10 @@ "config": [], "createdTime": "2010-01-01T00:00:00Z", "creator": "user:system:creator", - "description": null, "descriptor": "com.enonic.app.features:landing", "enabled": false, - "lastRun": null, - "lastTaskId": null, "modifiedTime": "2011-02-01T00:00:00Z", "modifier": "user:system:creator", - "name": "test2", - "user": null + "name": "test2" } -] \ No newline at end of file +] diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JsonStatusReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JsonStatusReporter.java new file mode 100644 index 00000000000..8c5b9270d03 --- /dev/null +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JsonStatusReporter.java @@ -0,0 +1,29 @@ +package com.enonic.xp.server.impl.status; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.net.MediaType; + +import com.enonic.xp.status.StatusReporter; + +abstract class JsonStatusReporter + implements StatusReporter +{ + @Override + public final MediaType getMediaType() + { + return MediaType.JSON_UTF_8; + } + + @Override + public final void report( final OutputStream outputStream ) + throws IOException + { + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); + } + + public abstract JsonNode getReport(); +} diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmGCReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmGCReporter.java index f14168362d8..599d1e80dc6 100644 --- a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmGCReporter.java +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmGCReporter.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmInfoReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmInfoReporter.java index b483ebf546e..410ce59760c 100644 --- a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmInfoReporter.java +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmInfoReporter.java @@ -9,7 +9,6 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmMemoryReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmMemoryReporter.java index 95765fc3bd5..4bdac724ba4 100644 --- a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmMemoryReporter.java +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmMemoryReporter.java @@ -13,7 +13,6 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmOsReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmOsReporter.java index 14efc132f28..307fcc53c83 100644 --- a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmOsReporter.java +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmOsReporter.java @@ -9,7 +9,6 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmThreadsReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmThreadsReporter.java index a2e42d0d070..589a2a6db6f 100644 --- a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmThreadsReporter.java +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/JvmThreadsReporter.java @@ -9,7 +9,6 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiBundleReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiBundleReporter.java index e3d52f4c1f7..2734a34a673 100644 --- a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiBundleReporter.java +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiBundleReporter.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiComponentReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiComponentReporter.java index 54462d77793..7e206ca2193 100644 --- a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiComponentReporter.java +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiComponentReporter.java @@ -15,7 +15,6 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiServiceReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiServiceReporter.java index 29cedab91bb..f3ad7898337 100644 --- a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiServiceReporter.java +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/OsgiServiceReporter.java @@ -12,7 +12,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) @@ -21,16 +20,16 @@ public final class OsgiServiceReporter { private BundleContext context; - @Override - public String getName() + @Activate + public OsgiServiceReporter( final BundleContext context ) { - return "osgi.service"; + this.context = context; } - @Activate - public void activate( final BundleContext context ) + @Override + public String getName() { - this.context = context; + return "osgi.service"; } @Override diff --git a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/ServerReporter.java b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/ServerReporter.java index d7005506bb7..ef680cf6236 100644 --- a/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/ServerReporter.java +++ b/modules/server/server-status/src/main/java/com/enonic/xp/server/impl/status/ServerReporter.java @@ -10,7 +10,6 @@ import com.enonic.xp.server.RunMode; import com.enonic.xp.server.ServerInfo; import com.enonic.xp.server.VersionInfo; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) diff --git a/modules/server/server-status/src/test/java/com/enonic/xp/server/impl/status/OsgiServiceReporterTest.java b/modules/server/server-status/src/test/java/com/enonic/xp/server/impl/status/OsgiServiceReporterTest.java index 586d6adc9a7..844b7822a5b 100644 --- a/modules/server/server-status/src/test/java/com/enonic/xp/server/impl/status/OsgiServiceReporterTest.java +++ b/modules/server/server-status/src/test/java/com/enonic/xp/server/impl/status/OsgiServiceReporterTest.java @@ -28,9 +28,7 @@ protected OsgiServiceReporter newReporter() final BundleContext context = Mockito.mock( BundleContext.class ); Mockito.when( context.getAllServiceReferences( null, null ) ).thenReturn( new ServiceReference[]{ref1, ref2} ); - final OsgiServiceReporter reporter = new OsgiServiceReporter(); - reporter.activate( context ); - return reporter; + return new OsgiServiceReporter( context ); } private ServiceReference newServiceReference( final Bundle bundle, final long id, final String... ifaces ) diff --git a/modules/tools/testing/src/main/java/com/enonic/xp/testing/helper/JsonAssert.java b/modules/tools/testing/src/main/java/com/enonic/xp/testing/helper/JsonAssert.java index 8bbc4115fd2..defe5dc4948 100644 --- a/modules/tools/testing/src/main/java/com/enonic/xp/testing/helper/JsonAssert.java +++ b/modules/tools/testing/src/main/java/com/enonic/xp/testing/helper/JsonAssert.java @@ -1,13 +1,16 @@ package com.enonic.xp.testing.helper; +import java.io.IOException; +import java.io.InputStream; import java.net.URL; +import java.util.Objects; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.enonic.xp.json.ObjectMapperHelper; -import com.enonic.xp.script.serializer.JsonMapGenerator; +import com.enonic.xp.core.internal.json.ObjectMapperHelper; import com.enonic.xp.script.serializer.MapSerializable; +import com.enonic.xp.testing.serializer.JsonMapGenerator; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -16,7 +19,16 @@ public final class JsonAssert { private static final ObjectMapper MAPPER = ObjectMapperHelper.create(); - public static void assertJson( final Class context, final String name, final MapSerializable value ) + public static void assertMapper( final Class context, String fileName, final MapSerializable value ) + { + final JsonMapGenerator generator = new JsonMapGenerator(); + value.serialize( generator ); + final JsonNode actualJson = (JsonNode) generator.getRoot(); + final JsonNode expectedNode = readFromFile( context, fileName ); + assertEquals( expectedNode, actualJson ); + } + + public static void assertJson( final Class context, final String name, final MapSerializable value ) throws Exception { final String resource = "/" + context.getName().replace( '.', '/' ) + "-" + name + ".json"; @@ -34,4 +46,17 @@ public static void assertJson( final Class context, final String name, final Map assertEquals( expectedStr, actualStr ); } + + private static JsonNode readFromFile( final Class context, final String fileName ) + { + final InputStream stream = + Objects.requireNonNull( context.getResourceAsStream( fileName ), "Resource file [" + fileName + "] not found" ); + try (stream) + { + return MAPPER.readTree( stream.readAllBytes() ); + } catch ( IOException e ) + { + throw new RuntimeException( "Failed to read file [" + fileName + "]", e ); + } + } } diff --git a/modules/script/script-api/src/main/java/com/enonic/xp/script/serializer/JsonMapGenerator.java b/modules/tools/testing/src/main/java/com/enonic/xp/testing/serializer/JsonMapGenerator.java similarity index 96% rename from modules/script/script-api/src/main/java/com/enonic/xp/script/serializer/JsonMapGenerator.java rename to modules/tools/testing/src/main/java/com/enonic/xp/testing/serializer/JsonMapGenerator.java index 24ca4de7556..f93ea1bbfca 100644 --- a/modules/script/script-api/src/main/java/com/enonic/xp/script/serializer/JsonMapGenerator.java +++ b/modules/tools/testing/src/main/java/com/enonic/xp/testing/serializer/JsonMapGenerator.java @@ -1,4 +1,4 @@ -package com.enonic.xp.script.serializer; +package com.enonic.xp.testing.serializer; import java.util.function.Function; @@ -14,7 +14,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; -@Deprecated +import com.enonic.xp.script.serializer.MapGeneratorBase; + public final class JsonMapGenerator extends MapGeneratorBase { diff --git a/modules/web/web-dispatch/src/main/java/com/enonic/xp/web/impl/dispatch/status/ResourceStatusReporter.java b/modules/web/web-dispatch/src/main/java/com/enonic/xp/web/impl/dispatch/status/ResourceStatusReporter.java index 76b4f3d561c..fd451e642e1 100644 --- a/modules/web/web-dispatch/src/main/java/com/enonic/xp/web/impl/dispatch/status/ResourceStatusReporter.java +++ b/modules/web/web-dispatch/src/main/java/com/enonic/xp/web/impl/dispatch/status/ResourceStatusReporter.java @@ -1,5 +1,8 @@ package com.enonic.xp.web.impl.dispatch.status; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Comparator; import java.util.List; @@ -12,14 +15,15 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.net.MediaType; import com.enonic.xp.core.internal.concurrent.AtomicSortedList; -import com.enonic.xp.status.JsonStatusReporter; +import com.enonic.xp.status.StatusReporter; import com.enonic.xp.web.dispatch.DispatchConstants; import com.enonic.xp.web.impl.dispatch.mapping.ResourceDefinition; public abstract class ResourceStatusReporter - extends JsonStatusReporter + implements StatusReporter { private final String name; @@ -39,7 +43,19 @@ public final String getName() } @Override - public final JsonNode getReport() + public MediaType getMediaType() + { + return MediaType.JSON_UTF_8; + } + + @Override + public void report( final OutputStream outputStream ) + throws IOException + { + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); + } + + private JsonNode getReport() { final ArrayNode json = JsonNodeFactory.instance.arrayNode(); for ( final ResourceDefinition def : this.list.snapshot() ) diff --git a/modules/web/web-dispatch/src/test/java/com/enonic/xp/web/impl/dispatch/status/FilterStatusReporterTest.java b/modules/web/web-dispatch/src/test/java/com/enonic/xp/web/impl/dispatch/status/FilterStatusReporterTest.java index 4205bc173b8..9eb2854ced9 100644 --- a/modules/web/web-dispatch/src/test/java/com/enonic/xp/web/impl/dispatch/status/FilterStatusReporterTest.java +++ b/modules/web/web-dispatch/src/test/java/com/enonic/xp/web/impl/dispatch/status/FilterStatusReporterTest.java @@ -1,5 +1,6 @@ package com.enonic.xp.web.impl.dispatch.status; +import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.servlet.Filter; @@ -14,13 +15,17 @@ import org.mockito.Mockito; import org.osgi.framework.ServiceReference; -import com.enonic.xp.status.JsonStatusReporterTest; +import com.google.common.net.MediaType; + +import com.enonic.xp.status.StatusReporter; +import com.enonic.xp.support.JsonTestHelper; import static org.junit.jupiter.api.Assertions.assertEquals; -public class FilterStatusReporterTest - extends JsonStatusReporterTest +class FilterStatusReporterTest { + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + @Test public void testReport() throws Exception @@ -39,9 +44,20 @@ public void testReport() reporter.addFilter( filter2, serviceReference2 ); assertEquals( "http.filter", reporter.getName() ); - assertEquals( parseJson( readFromFile( "filter_status_report.json" ) ), reporter.getReport() ); + assertJson( "filter_status_report.json", reporter ); } + private void assertJson( final String fileName, final StatusReporter reporter ) + throws Exception + { + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); + + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); + + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( fileName ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); + } @WebFilter private static final class MyFilter diff --git a/modules/web/web-dispatch/src/test/java/com/enonic/xp/web/impl/dispatch/status/ServletStatusReporterTest.java b/modules/web/web-dispatch/src/test/java/com/enonic/xp/web/impl/dispatch/status/ServletStatusReporterTest.java index 918eadc808d..4f6b9aaa24c 100644 --- a/modules/web/web-dispatch/src/test/java/com/enonic/xp/web/impl/dispatch/status/ServletStatusReporterTest.java +++ b/modules/web/web-dispatch/src/test/java/com/enonic/xp/web/impl/dispatch/status/ServletStatusReporterTest.java @@ -1,5 +1,7 @@ package com.enonic.xp.web.impl.dispatch.status; +import java.io.ByteArrayOutputStream; + import javax.servlet.Servlet; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; @@ -9,14 +11,18 @@ import org.mockito.Mockito; import org.osgi.framework.ServiceReference; +import com.google.common.net.MediaType; + import com.enonic.xp.annotation.Order; -import com.enonic.xp.status.JsonStatusReporterTest; +import com.enonic.xp.status.StatusReporter; +import com.enonic.xp.support.JsonTestHelper; import static org.junit.jupiter.api.Assertions.assertEquals; public class ServletStatusReporterTest - extends JsonStatusReporterTest { + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + @Test public void testReport() throws Exception @@ -35,7 +41,19 @@ public void testReport() reporter.addServlet( servlet2, serviceReference2 ); assertEquals( "http.servlet", reporter.getName() ); - assertEquals( parseJson( readFromFile( "servlet_status_report.json" ) ), reporter.getReport() ); + assertJson( "servlet_status_report.json", reporter ); + } + + private void assertJson( final String fileName, final StatusReporter reporter ) + throws Exception + { + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); + + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); + + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( fileName ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); } @Order(10) diff --git a/modules/web/web-dispatch/src/test/resources/com/enonic/xp/web/impl/dispatch/status/filter_status_report.json b/modules/web/web-dispatch/src/test/resources/com/enonic/xp/web/impl/dispatch/status/FilterStatusReporterTest-filter_status_report.json similarity index 100% rename from modules/web/web-dispatch/src/test/resources/com/enonic/xp/web/impl/dispatch/status/filter_status_report.json rename to modules/web/web-dispatch/src/test/resources/com/enonic/xp/web/impl/dispatch/status/FilterStatusReporterTest-filter_status_report.json diff --git a/modules/web/web-dispatch/src/test/resources/com/enonic/xp/web/impl/dispatch/status/servlet_status_report.json b/modules/web/web-dispatch/src/test/resources/com/enonic/xp/web/impl/dispatch/status/ServletStatusReporterTest-servlet_status_report.json similarity index 100% rename from modules/web/web-dispatch/src/test/resources/com/enonic/xp/web/impl/dispatch/status/servlet_status_report.json rename to modules/web/web-dispatch/src/test/resources/com/enonic/xp/web/impl/dispatch/status/ServletStatusReporterTest-servlet_status_report.json diff --git a/modules/web/web-impl/src/main/java/com/enonic/xp/web/impl/handler/WebDispatcherReporter.java b/modules/web/web-impl/src/main/java/com/enonic/xp/web/impl/handler/WebDispatcherReporter.java index 75bca83c2ec..1b34837467c 100644 --- a/modules/web/web-impl/src/main/java/com/enonic/xp/web/impl/handler/WebDispatcherReporter.java +++ b/modules/web/web-impl/src/main/java/com/enonic/xp/web/impl/handler/WebDispatcherReporter.java @@ -1,5 +1,10 @@ package com.enonic.xp.web.impl.handler; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; @@ -7,16 +12,35 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.net.MediaType; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; import com.enonic.xp.web.handler.WebHandler; @Component(immediate = true, service = StatusReporter.class) public final class WebDispatcherReporter - extends JsonStatusReporter + implements StatusReporter { - private WebDispatcher webDispatcher; + private final WebDispatcher webDispatcher; + + @Activate + public WebDispatcherReporter( @Reference final WebDispatcher webDispatcher ) + { + this.webDispatcher = webDispatcher; + } + + @Override + public MediaType getMediaType() + { + return MediaType.JSON_UTF_8; + } + + @Override + public void report( final OutputStream outputStream ) + throws IOException + { + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); + } @Override public String getName() @@ -24,8 +48,7 @@ public String getName() return "http.webHandler"; } - @Override - public JsonNode getReport() + private JsonNode getReport() { final ArrayNode json = JsonNodeFactory.instance.arrayNode(); for ( final WebHandler handler : this.webDispatcher ) @@ -37,10 +60,4 @@ public JsonNode getReport() return json; } - - @Reference - public void setWebDispatcher( final WebDispatcher webDispatcher ) - { - this.webDispatcher = webDispatcher; - } } diff --git a/modules/web/web-impl/src/test/java/com/enonic/xp/web/impl/handler/WebDispatcherReporterTest.java b/modules/web/web-impl/src/test/java/com/enonic/xp/web/impl/handler/WebDispatcherReporterTest.java index f35bdd207b0..3e87577eb95 100644 --- a/modules/web/web-impl/src/test/java/com/enonic/xp/web/impl/handler/WebDispatcherReporterTest.java +++ b/modules/web/web-impl/src/test/java/com/enonic/xp/web/impl/handler/WebDispatcherReporterTest.java @@ -1,23 +1,43 @@ package com.enonic.xp.web.impl.handler; +import java.io.ByteArrayOutputStream; + import org.junit.jupiter.api.Test; +import com.google.common.net.MediaType; + +import com.enonic.xp.status.StatusReporter; +import com.enonic.xp.support.JsonTestHelper; + import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -public class WebDispatcherReporterTest +class WebDispatcherReporterTest { + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + @Test - public void testReport() + void report() + throws Exception { final WebDispatcherImpl dispatcher = new WebDispatcherImpl(); dispatcher.add( new TestWebHandler() ); dispatcher.add( new TestWebHandler() ); - final WebDispatcherReporter reporter = new WebDispatcherReporter(); - reporter.setWebDispatcher( dispatcher ); + final WebDispatcherReporter reporter = new WebDispatcherReporter( dispatcher ); assertEquals( "http.webHandler", reporter.getName() ); - assertNotNull( reporter.getReport() ); + assertJson( "report.json", reporter ); + } + + private void assertJson( final String fileName, final StatusReporter reporter ) + throws Exception + { + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); + + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); + + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( fileName ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); } } diff --git a/modules/web/web-impl/src/test/resources/com/enonic/xp/web/impl/handler/WebDispatcherReporterTest-report.json b/modules/web/web-impl/src/test/resources/com/enonic/xp/web/impl/handler/WebDispatcherReporterTest-report.json new file mode 100644 index 00000000000..66f6af5b765 --- /dev/null +++ b/modules/web/web-impl/src/test/resources/com/enonic/xp/web/impl/handler/WebDispatcherReporterTest-report.json @@ -0,0 +1,7 @@ +[ { + "order" : 0, + "class" : "com.enonic.xp.web.impl.handler.TestWebHandler" +}, { + "order" : 0, + "class" : "com.enonic.xp.web.impl.handler.TestWebHandler" +} ] diff --git a/modules/web/web-jetty/src/main/java/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporter.java b/modules/web/web-jetty/src/main/java/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporter.java index 11548aec578..c7fe31b977d 100644 --- a/modules/web/web-jetty/src/main/java/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporter.java +++ b/modules/web/web-jetty/src/main/java/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporter.java @@ -1,5 +1,9 @@ package com.enonic.xp.web.jetty.impl; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.ThreadPool; import org.osgi.service.component.annotations.Activate; @@ -9,13 +13,13 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.net.MediaType; -import com.enonic.xp.status.JsonStatusReporter; import com.enonic.xp.status.StatusReporter; @Component(immediate = true, service = StatusReporter.class) public class HttpThreadPoolStatusReporter - extends JsonStatusReporter + implements StatusReporter { private final ThreadPool threadPool; @@ -25,14 +29,26 @@ public HttpThreadPoolStatusReporter( @Reference final Server server ) this.threadPool = server.getThreadPool(); } + @Override + public final MediaType getMediaType() + { + return MediaType.JSON_UTF_8; + } + + @Override + public final void report( final OutputStream outputStream ) + throws IOException + { + outputStream.write( getReport().toString().getBytes( StandardCharsets.UTF_8 ) ); + } + @Override public String getName() { return "http.threadpool"; } - @Override - public JsonNode getReport() + private JsonNode getReport() { final ObjectNode json = JsonNodeFactory.instance.objectNode(); json.put( "threads", this.threadPool.getThreads() ); diff --git a/modules/web/web-jetty/src/test/java/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporterTest.java b/modules/web/web-jetty/src/test/java/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporterTest.java index d913812a0c2..3ba08f78f5a 100644 --- a/modules/web/web-jetty/src/test/java/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporterTest.java +++ b/modules/web/web-jetty/src/test/java/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporterTest.java @@ -1,18 +1,24 @@ package com.enonic.xp.web.jetty.impl; +import java.io.ByteArrayOutputStream; + import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.thread.ThreadPool; import org.junit.jupiter.api.Test; -import com.enonic.xp.status.JsonStatusReporterTest; +import com.google.common.net.MediaType; + +import com.enonic.xp.status.StatusReporter; +import com.enonic.xp.support.JsonTestHelper; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class HttpThreadPoolStatusReporterTest - extends JsonStatusReporterTest { + JsonTestHelper jsonTestHelper = new JsonTestHelper( this ); + @Test public void getName() throws Exception @@ -31,7 +37,19 @@ public void getReport() when( server.getThreadPool() ).thenReturn( new ThreadPoolImpl( 8, 2, false ) ); final HttpThreadPoolStatusReporter reporter = new HttpThreadPoolStatusReporter( server ); - assertEquals( parseJson( readFromFile( "http_thread_pool_report.json" ) ), reporter.getReport() ); + assertJson( "http_thread_pool_report.json" , reporter ); + } + + private void assertJson( final String fileName, final StatusReporter reporter ) + throws Exception + { + assertEquals( MediaType.JSON_UTF_8, reporter.getMediaType() ); + + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + reporter.report( outputStream ); + + jsonTestHelper.assertJsonEquals( jsonTestHelper.loadTestJson( fileName ), + jsonTestHelper.bytesToJson( outputStream.toByteArray() ) ); } private static class ThreadPoolImpl diff --git a/modules/web/web-jetty/src/test/resources/com/enonic/xp/web/jetty/impl/http_thread_pool_report.json b/modules/web/web-jetty/src/test/resources/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporterTest-http_thread_pool_report.json similarity index 100% rename from modules/web/web-jetty/src/test/resources/com/enonic/xp/web/jetty/impl/http_thread_pool_report.json rename to modules/web/web-jetty/src/test/resources/com/enonic/xp/web/jetty/impl/HttpThreadPoolStatusReporterTest-http_thread_pool_report.json